fixed obvious bug in map selection... still there is some bug hidden there
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 string GetMapname();
2 void GotoNextMap();
3
4 void SetDefaultAlpha()
5 {
6         if(cvar("g_cloaked"))
7         {
8                 default_player_alpha = cvar("g_balance_cloaked_alpha");
9         }
10         else
11         {
12                 default_player_alpha = cvar("g_player_alpha");
13                 if(default_player_alpha <= 0)
14                         default_player_alpha = 1;
15         }
16 }
17
18 void GotoFirstMap()
19 {
20         if(cvar("_sv_init"))
21         {
22                 cvar_set("_sv_init", "0");
23                 tokenize(cvar_string("g_maplist"));
24                 if(argv(0) != GetMapname())
25                 {
26                         cvar_set("nextmap", argv(0));
27                         GotoNextMap();
28                 }
29         }
30 }
31
32 void worldspawn (void)
33 {
34
35         // Precache all player models
36         // Workaround for "invisible players"
37         precache_model("models/player/carni.zym");
38         precache_model("models/player/crash.zym");
39         precache_model("models/player/grunt.zym");
40         precache_model("models/player/headhunter.zym");
41         precache_model("models/player/insurrectionist.zym");
42         precache_model("models/player/jeandarc.zym");
43         precache_model("models/player/lurk.zym");
44         precache_model("models/player/lycanthrope.zym");
45         precache_model("models/player/marine.zym");
46         precache_model("models/player/nexus.zym");
47         precache_model("models/player/pyria.zym");
48         precache_model("models/player/shock.zym");
49         precache_model("models/player/skadi.zym");
50         precache_model("models/player/specop.zym");
51         precache_model("models/player/visitant.zym");
52
53         //precache_model ("progs/beam.mdl");
54         precache_model ("models/bullet.mdl");
55         precache_model ("models/casing_bronze.mdl");
56         precache_model ("models/casing_shell.mdl");
57         precache_model ("models/casing_steel.mdl");
58         precache_model ("models/ebomb.mdl");
59         precache_model ("models/elaser.mdl");
60         precache_model ("models/flash.md3");
61         precache_model ("models/gibs/bloodyskull.md3");
62         precache_model ("models/gibs/chunk.mdl");
63         precache_model ("models/gibs/eye.md3");
64         precache_model ("models/gibs/gib1.md3");
65         //precache_model ("models/gibs/gib2.md3");
66         //precache_model ("models/gibs/gib3.md3");
67         //precache_model ("models/gibs/gib4.md3");
68         precache_model ("models/gibs/gib5.md3");
69         //precache_model ("models/gibs/gib6.md3");
70         precache_model ("models/gibs/gib1.mdl");
71         precache_model ("models/gibs/gib2.mdl");
72         precache_model ("models/gibs/gib3.mdl");
73         precache_model ("models/grenademodel.md3");
74         precache_model ("models/hagarmissile.mdl");
75         precache_model ("models/items/a_bullets.mdl");
76         precache_model ("models/items/a_cells.md3");
77         precache_model ("models/items/a_rockets.md3");
78         precache_model ("models/items/a_shells.md3");
79         precache_model ("models/items/g_a1.md3");
80         precache_model ("models/items/g_a25.md3");
81         precache_model ("models/items/g_h1.md3");
82         precache_model ("models/items/g_h25.md3");
83         precache_model ("models/items/g_h100.md3");
84         precache_model ("models/items/g_invincible.md3");
85         precache_model ("models/items/g_strength.md3");
86         precache_model ("models/laser.mdl");
87         precache_model ("models/misc/chatbubble.spr");
88         precache_model ("models/misc/teambubble.spr");
89         precache_model ("models/nexflash.md3");
90         precache_model ("models/plasma.mdl");
91         precache_model ("models/plasmatrail.mdl");
92         precache_model ("models/rocket.md3");
93         //precache_model ("models/sprites/grenexpl.spr");
94         precache_model ("models/runematch/rune.mdl");
95         precache_model ("models/runematch/curse.mdl");
96         //precache_model ("models/sprites/hagar.spr");
97         //precache_model ("models/sprites/muzzleflash.spr32");
98         //precache_model ("models/sprites/electrocombo.spr32");
99         //precache_model ("models/sprites/plasmahitwall.spr32");
100         //precache_model ("models/sprites/plasmashot.spr32");
101         //precache_model ("models/sprites/rockexpl.spr");
102         precache_model ("models/tracer.mdl");
103         precache_model ("models/uziflash.md3");
104         precache_model ("models/weapons/g_crylink.md3");
105         precache_model ("models/weapons/g_electro.md3");
106         precache_model ("models/weapons/g_gl.md3");
107         precache_model ("models/weapons/g_hagar.md3");
108         precache_model ("models/weapons/g_nex.md3");
109         precache_model ("models/weapons/g_rl.md3");
110         precache_model ("models/weapons/g_shotgun.md3");
111         precache_model ("models/weapons/g_uzi.md3");
112         precache_model ("models/weapons/v_crylink.md3");
113         precache_model ("models/weapons/v_electro.md3");
114         precache_model ("models/weapons/v_gl.md3");
115         precache_model ("models/weapons/v_hagar.md3");
116         precache_model ("models/weapons/v_laser.md3");
117         precache_model ("models/weapons/v_nex.md3");
118         precache_model ("models/weapons/v_rl.md3");
119         precache_model ("models/weapons/v_shotgun.md3");
120         precache_model ("models/weapons/v_uzi.md3");
121         precache_model ("models/weapons/w_crylink.zym");
122         precache_model ("models/weapons/w_electro.zym");
123         precache_model ("models/weapons/w_gl.zym");
124         precache_model ("models/weapons/w_hagar.zym");
125         precache_model ("models/weapons/w_laser.zym");
126         precache_model ("models/weapons/w_nex.zym");
127         precache_model ("models/weapons/w_rl.zym");
128         precache_model ("models/weapons/w_shotgun.zym");
129         precache_model ("models/weapons/w_uzi.zym");
130
131         // laser for laser-guided weapons
132         precache_model ("models/laser_dot.mdl");
133
134         precache_sound ("misc/null.wav");
135         precache_sound ("misc/armor1.wav");
136         precache_sound ("misc/armor25.wav");
137         precache_sound ("misc/armorimpact.wav");
138         precache_sound ("misc/bodyimpact1.wav");
139         precache_sound ("misc/bodyimpact2.wav");
140         precache_sound ("misc/gib.wav");
141         precache_sound ("misc/gib_splat01.wav");
142         precache_sound ("misc/gib_splat02.wav");
143         precache_sound ("misc/gib_splat03.wav");
144         precache_sound ("misc/gib_splat04.wav");
145         //precache_sound ("misc/h2ohit.wav");
146         precache_sound ("misc/hit.wav");
147         precache_sound ("misc/footstep01.wav");
148         precache_sound ("misc/footstep02.wav");
149         precache_sound ("misc/footstep03.wav");
150         precache_sound ("misc/footstep04.wav");
151         precache_sound ("misc/footstep05.wav");
152         precache_sound ("misc/footstep06.wav");
153         precache_sound ("misc/hitground1.ogg");
154         precache_sound ("misc/hitground2.ogg");
155         precache_sound ("misc/hitground3.ogg");
156         precache_sound ("misc/hitground4.ogg");
157         precache_sound ("misc/itempickup.ogg");
158         precache_sound ("misc/itemrespawn.ogg");
159         precache_sound ("misc/jumppad.ogg");
160         precache_sound ("misc/mediumhealth.ogg");
161         precache_sound ("misc/megahealth.ogg");
162         precache_sound ("misc/minihealth.ogg");
163         precache_sound ("misc/powerup.ogg");
164         precache_sound ("misc/powerup_shield.ogg");
165         precache_sound ("misc/talk.wav");
166         precache_sound ("misc/teleport.ogg");
167         precache_sound ("plats/medplat1.wav");
168         precache_sound ("plats/medplat2.wav");
169         precache_sound ("player/lava.wav");
170         precache_sound ("player/slime.wav");
171         precache_sound ("weapons/crylink_fire.ogg");
172         precache_sound ("weapons/electro_bounce.ogg");
173         precache_sound ("weapons/electro_fire.ogg");
174         precache_sound ("weapons/electro_fire2.ogg");
175         precache_sound ("weapons/electro_fly.wav");
176         precache_sound ("weapons/electro_impact.ogg");
177         precache_sound ("weapons/electro_impact_combo.ogg");
178         //precache_sound ("weapons/grenade_bounce.ogg");
179         precache_sound ("weapons/grenade_bounce1.ogg");
180         precache_sound ("weapons/grenade_bounce2.ogg");
181         precache_sound ("weapons/grenade_bounce3.ogg");
182         precache_sound ("weapons/grenade_fire.ogg");
183         precache_sound ("weapons/grenade_impact.ogg");
184         precache_sound ("weapons/hagar_fire.ogg");
185         precache_sound ("weapons/hagexp1.ogg");
186         precache_sound ("weapons/hagexp2.ogg");
187         precache_sound ("weapons/hagexp3.ogg");
188         precache_sound ("weapons/hook_fire.ogg");
189         precache_sound ("weapons/hook_impact.ogg");
190         precache_sound ("weapons/lasergun_fire.ogg");
191         precache_sound ("weapons/laserimpact.ogg");
192         precache_sound ("weapons/nexfire.ogg");
193         precache_sound ("weapons/neximpact.ogg");
194         precache_sound ("weapons/ric1.ogg");
195         precache_sound ("weapons/ric2.ogg");
196         precache_sound ("weapons/ric3.ogg");
197         precache_sound ("weapons/rocket_fire.ogg");
198         precache_sound ("weapons/rocket_fly.wav");
199         precache_sound ("weapons/rocket_impact.ogg");
200         precache_sound ("weapons/rocket_det.ogg");
201         precache_sound ("weapons/shotgun_fire.ogg");
202         precache_sound ("weapons/tink1.ogg");
203         precache_sound ("weapons/uzi_fire.ogg");
204         precache_sound ("weapons/weapon_switch.ogg");
205         precache_sound ("weapons/weaponpickup.ogg");
206         precache_sound ("weapons/strength_fire.ogg");
207
208         //precache_sound ("announce/male/kill10.ogg");
209         //precache_sound ("announce/male/kill15.ogg");
210         //precache_sound ("announce/male/kill20.ogg");
211         //precache_sound ("announce/male/kill25.ogg");
212         //precache_sound ("announce/male/kill3.ogg");
213         //precache_sound ("announce/male/kill30.ogg");
214         //precache_sound ("announce/male/kill4.ogg");
215         //precache_sound ("announce/male/kill5.ogg");
216         //precache_sound ("announce/male/kill6.ogg");
217         //precache_sound ("announce/male/mapkill1.ogg");
218         //precache_sound ("announce/robotic/last_second_save.ogg");
219         //precache_sound ("announce/robotic/narrowly_averted.ogg");
220         //precache_sound ("minstagib/mockery.ogg");
221
222         // announcer sounds - male
223         precache_sound ("announcer/male/03kills.ogg");
224         precache_sound ("announcer/male/05kills.ogg");
225         precache_sound ("announcer/male/10kills.ogg");
226         precache_sound ("announcer/male/15kills.ogg");
227         precache_sound ("announcer/male/20kills.ogg");
228         precache_sound ("announcer/male/25kills.ogg");
229         precache_sound ("announcer/male/30kills.ogg");
230         precache_sound ("announcer/male/botlike.ogg");
231         precache_sound ("announcer/male/electrobitch.ogg");
232         precache_sound ("announcer/male/welcome.ogg");
233         precache_sound ("announcer/male/yoda.ogg");
234
235         // announcer sounds - robotic
236         precache_sound ("announcer/robotic/1fragleft.ogg");
237         precache_sound ("announcer/robotic/1minuteremains.ogg");
238         precache_sound ("announcer/robotic/2fragsleft.ogg");
239         precache_sound ("announcer/robotic/3fragsleft.ogg");
240         precache_sound ("announcer/robotic/lastsecond.ogg");
241         precache_sound ("announcer/robotic/narrowly.ogg");
242
243         // plays music for the level if there is any
244         if (self.noise)
245         {
246                 precache_sound (self.noise);
247                 ambientsound ('0 0 0', self.noise, 1.00, ATTN_NONE);
248         }
249
250                 // 0 normal
251         lightstyle(0, "m");
252
253         // 1 FLICKER (first variety)
254         lightstyle(1, "mmnmmommommnonmmonqnmmo");
255
256         // 2 SLOW STRONG PULSE
257         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
258
259         // 3 CANDLE (first variety)
260         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
261
262         // 4 FAST STROBE
263         lightstyle(4, "mamamamamama");
264
265         // 5 GENTLE PULSE 1
266         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
267
268         // 6 FLICKER (second variety)
269         lightstyle(6, "nmonqnmomnmomomno");
270
271         // 7 CANDLE (second variety)
272         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
273
274         // 8 CANDLE (third variety)
275         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
276
277         // 9 SLOW STROBE (fourth variety)
278         lightstyle(9, "aaaaaaaazzzzzzzz");
279
280         // 10 FLUORESCENT FLICKER
281         lightstyle(10, "mmamammmmammamamaaamammma");
282
283         // 11 SLOW PULSE NOT FADE TO BLACK
284         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
285
286         // styles 32-62 are assigned by the light program for switchable lights
287
288         // 63 testing
289         lightstyle(63, "a");
290
291         player_count = 0;
292         lms_dead_count = 0;
293         lms_lowest_lives = 0;
294         lms_next_place = 0;
295
296         GotoFirstMap();
297
298         if(cvar("g_campaign"))
299                 CampaignPreInit();
300
301         InitGameplayMode();
302         //if (cvar("g_domination"))
303         //      dom_init();
304
305         local entity head;
306         head = nextent(world);
307         maxclients = 0;
308         while(head)
309         {
310                 maxclients++;
311                 head = nextent(head);
312         }
313
314         GameLogInit(); // prepare everything
315         if(cvar("sv_eventlog"))
316         {
317                 local string s;
318                 GameLogEcho(":logversion:2", FALSE);
319                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
320                 s = strcat(s, ftos(random()));
321                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
322                 s = ":gameinfo:mutators:LIST";
323                 if(cvar("g_grappling_hook"))
324                         s = strcat(s, ":grappling_hook");
325                 if(!cvar("g_use_ammunition"))
326                         s = strcat(s, ":no_use_ammunition");
327                 if(!cvar("g_pickup_items"))
328                         s = strcat(s, ":no_pickup_items");
329                 if(cvar("g_instagib"))
330                         s = strcat(s, ":instagib");
331                 if(cvar("g_rocketarena"))
332                         s = strcat(s, ":rockerarena");
333                 if(cvar("g_nixnex"))
334                         s = strcat(s, ":nixnex");
335                 if(cvar("g_vampire"))
336                         s = strcat(s, ":vampire");
337                 if(cvar("g_laserguided_missile"))
338                         s = strcat(s, ":laserguided_missile");
339                 if(cvar("g_norecoil"))
340                         s = strcat(s, ":norecoil");
341                 if(cvar("g_midair"))
342                         s = strcat(s, ":midair");
343                 if(cvar("g_minstagib"))
344                         s = strcat(s, ":minstagib");
345                 GameLogEcho(s, FALSE);
346                 GameLogEcho(":gameinfo:end", FALSE);
347         }
348
349         cvar_set("nextmap", "");
350
351         SetDefaultAlpha();
352
353         if(cvar("g_campaign"))
354                 CampaignPostInit();
355 }
356
357 void light (void)
358 {
359         makestatic (self);
360 }
361
362 float( string pFilename ) TryFile =
363 {
364         local float lHandle;
365         dprint("TryFile(\"", pFilename, "\")\n");
366         lHandle = fopen( pFilename, FILE_READ );
367         if( lHandle != -1 ) {
368                 fclose( lHandle );
369                 return TRUE;
370         } else {
371                 return FALSE;
372         }
373 };
374
375 string GetMapname()
376 {
377         if (game == GAME_DEATHMATCH)
378                 return strcat("dm_", mapname);
379         else if (game == GAME_TEAM_DEATHMATCH)
380                 return strcat("tdm_", mapname);
381         else if (game == GAME_DOMINATION)
382                 return strcat("dom_", mapname);
383         else if (game == GAME_CTF)
384                 return strcat("ctf_", mapname);
385         else if (game == GAME_RUNEMATCH)
386                 return strcat("rune_", mapname);
387         else if (game == GAME_LMS)
388                 return strcat("lms_", mapname);
389         return strcat("dm_", mapname);
390 }
391
392 float GetMaplistPosition()
393 {
394         float pos, f;
395         string map, s;
396
397         map = strzone(GetMapname());
398         pos = 0;
399         f = tokenize(cvar_string("g_maplist"));
400
401         while(pos < f)
402         {
403                 s = strzone(argv(pos));
404                 if(s == map)
405                 {
406                         strunzone(s);
407                         strunzone(map);
408                         return pos;
409                 }
410                 strunzone(s);
411                 pos++;
412         }
413
414         strunzone(map);
415         // resume normal maplist rotation if current map is not in g_maplist
416         return cvar("g_maplist_index");
417 }
418
419 float MapHasRightSize(string map)
420 {
421         // open map size restriction file
422         float fh;
423         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
424         if(fh >= 0)
425         {
426                 float mapmin, mapmax;
427                 mapmin = stof(fgets(fh));
428                 mapmax = stof(fgets(fh));
429                 fclose(fh);
430                 if(player_count < mapmin)
431                         return FALSE;
432                 if(player_count > mapmax)
433                         return FALSE;
434         }
435         return TRUE;
436 }
437
438 void() GotoNextMap =
439 {
440         //local string nextmap;
441         //local float n, nummaps;
442         //local string s;
443         string exit_cfg;
444         if (alreadychangedlevel)
445                 return;
446         alreadychangedlevel = TRUE;
447
448         if(cvar("g_campaign"))
449         {
450                 CampaignPostIntermission();
451                 return;
452         }
453
454         if (cvar("samelevel")) // if samelevel is set, stay on same level
455         {
456                 // 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)
457                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
458                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
459                 localcmd("restart\n");
460                 //changelevel (mapname);
461                 return;
462         }
463
464         // if an exit cfg is defined by exiting map, exec it.
465         exit_cfg = cvar_string("exit_cfg");
466         if(exit_cfg != "")
467                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
468
469         ResetGameCvars();
470
471
472         if (cvar("lastlevel"))
473         {
474                 localcmd(strcat("set lastlevel 0\n"));
475                 localcmd(strcat("togglemenu\n"));
476         }
477         else
478         {
479                 // method 0
480                 local float lCurrent;
481                 local float lSize;
482                 local float lOldCurrent;
483                 local float lBeforeCurrent;
484                 local float pass;
485                 local float found_but_wrong_size;
486                 found_but_wrong_size = FALSE;
487
488                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
489                 {
490                         localcmd(strcat("exec \"maps/", cvar_string("nextmap"), ".mapcfg\"\n"));
491                         return;
492                 }
493
494                 pass = 0;
495                 while (pass < 2)
496                 {
497                         pass = pass + 1;
498                         local string temp;
499                         temp = cvar_string( "g_maplist" );
500                         if(temp == "")
501                         {
502                                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
503                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
504                                 temp = cvar_string( "g_maplist" );
505                         }
506                         temp = strzone(temp);
507                         dprint("g_maplist is ", temp, "\n");
508                         lCurrent = max(0, GetMaplistPosition());
509                         lSize = tokenize( temp );
510                         lOldCurrent = lCurrent;
511                         dprint(ftos(lOldCurrent), " / ", ftos(lSize), " (start)\n");
512
513                         // if we want a random map selection...
514                         if(cvar("g_maplist_selectrandom") && lSize > 1)
515                         {
516                                 lBeforeCurrent = lCurrent - 1;
517                                 if(lBeforeCurrent < 0)
518                                         lBeforeCurrent = lSize - 1;
519                                 lCurrent = ceil(random() * (lSize - 1)) - 1; // random in 0..lsize-2
520                                 if(lCurrent >= lBeforeCurrent)
521                                         lCurrent += 1;
522                                 // choose any map except for the current one
523                         }
524
525                         while( 1 ) {
526                                 local string lFilename;
527
528                                 lCurrent = lCurrent + 1;
529                                 dprint(ftos(lCurrent), " / ", ftos(lSize), "\n");
530                                 if( lCurrent >= lSize ) {
531                                         lCurrent = 0;
532                                 }
533                                 if( lOldCurrent == lCurrent ) {
534                                         // we couldn't find a valid map at all
535                                         if (pass == 1)
536                                         {
537                                                 if(!found_but_wrong_size)
538                                                 {
539                                                         bprint( "Maplist is bad/messed up. Not one good mapcfg can be found in it!  Resetting it to default map list.\n" );
540                                                         cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
541                                                         // let the loop restart with the default list now
542                                                 }
543                                         }
544                                         else
545                                         {
546                                                 bprint( "Both g_maplist and g_maplist_defaultlist are messed up!  Complain to developers!\n" );
547                                                 localcmd( "disconnect\n" );
548                                         }
549                                         break;
550                                 }
551
552                                 cvar_set( "g_maplist_index", ftos( lCurrent ) );
553
554                                 lFilename = strzone(strcat( "maps/", argv( lCurrent ), ".mapcfg" ));
555                                 if( TryFile( lFilename ) ) {
556                                         if((pass == 2) || MapHasRightSize(argv(lCurrent)))
557                                         {
558                                                 localcmd(strcat("exec \"", lFilename ,"\"\n"));
559                                                 strunzone(lFilename);
560                                                 pass = 2; // exit the outer loop
561                                                 break;
562                                         }
563                                         else
564                                                 found_but_wrong_size = TRUE;
565                                 } else {
566                                         dprint( "Couldn't find '", lFilename, "'..\n" );
567                                 }
568                                 strunzone(lFilename);
569                                 //changelevel( argv( lCurrent ) );
570                         }
571                         strunzone(temp);
572                 }
573
574                 /*
575                 // method 1
576
577                 //local entity pos;
578                 local float fh;
579                 local string line;
580
581                 // restart current map if no cycle is found
582                 nextmap = strzone(mapname);
583                 fh = fopen("maplist.cfg", FILE_READ);
584                 if (fh >= 0)
585                 {
586                         while (1)
587                         {
588                                 line = fgets(fh);
589                                 if (nextmap == mapname)
590                                 {
591                                         strunzone(nextmap);
592                                         nextmap = strzone(line);
593                                 }
594                                 if (!line)
595                                         break;
596                                 if (line == mapname)
597                                 {
598                                         line = fgets(fh);
599                                         if (!line)
600                                                 break;
601                                         strunzone(nextmap);
602                                         nextmap = strzone(line);
603                                         break;
604                                 }
605                         }
606                         fclose(fh);
607                 }
608                 changelevel (nextmap);
609                 strunzone(nextmap);*/
610
611                 // method 3
612                 /*
613                 s = cvar_string("g_maplist");
614                 nummaps = tokenize(s);
615                 // if no map list, restart current one
616                 nextmap = mapname;
617                 if (nummaps >= 1)
618                 {
619                         n = 0;
620                         while (n < nummaps)
621                         {
622                                 if (argv(n) == mapname)
623                                         break;
624                                 n = n + 1;
625                         }
626                         n = n + 1;
627                         if (n >= nummaps)
628                                 n = 0;
629                         nextmap = argv(n);
630                 }
631                 changelevel (nextmap);
632                 */
633         }
634 };
635
636
637 /*
638 ============
639 IntermissionThink
640
641 When the player presses attack or jump, change to the next level
642 ============
643 */
644 void() IntermissionThink =
645 {
646         if (time < intermission_exittime)
647                 return;
648
649         if (time < intermission_exittime + 10 && !self.button0 && !self.button1 && !self.button2 && !self.button3)
650                 return;
651
652         GotoNextMap ();
653 };
654
655 /*
656 ============
657 FindIntermission
658
659 Returns the entity to view from
660 ============
661 */
662 /*
663 entity() FindIntermission =
664 {
665         local   entity spot;
666         local   float cyc;
667
668 // look for info_intermission first
669         spot = find (world, classname, "info_intermission");
670         if (spot)
671         {       // pick a random one
672                 cyc = random() * 4;
673                 while (cyc > 1)
674                 {
675                         spot = find (spot, classname, "info_intermission");
676                         if (!spot)
677                                 spot = find (spot, classname, "info_intermission");
678                         cyc = cyc - 1;
679                 }
680                 return spot;
681         }
682
683 // then look for the start position
684         spot = find (world, classname, "info_player_start");
685         if (spot)
686                 return spot;
687
688 // testinfo_player_start is only found in regioned levels
689         spot = find (world, classname, "testplayerstart");
690         if (spot)
691                 return spot;
692
693 // then look for the start position
694         spot = find (world, classname, "info_player_deathmatch");
695         if (spot)
696                 return spot;
697
698         //objerror ("FindIntermission: no spot");
699         return world;
700 };
701 */
702
703 /*
704 ===============================================================================
705
706 RULES
707
708 ===============================================================================
709 */
710
711 void() DumpStats =
712 {
713         local float file;
714         local string s;
715
716         if(cvar("_printstats"))
717                 cvar_set("_printstats", "0");
718         else if(!gameover)
719                 return;
720
721         if(gameover)
722                 s = ":scores:";
723         else
724                 s = ":status:";
725
726         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
727
728         if(cvar("sv_eventlog") && gameover)
729                 GameLogEcho(s, FALSE);
730         else if(cvar("sv_logscores_console"))
731                 ServerConsoleEcho(s, FALSE);
732         if(cvar("sv_logscores_file"))
733         {
734                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
735                 fputs(file, strcat(s, "\n"));
736         }
737
738         other = findchainflags(flags, FL_CLIENT);
739         while (other)
740         {
741                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
742                 {
743                         s = strcat(":player:", ftos(other.frags), ":");
744                         s = strcat(s, ftos(other.deaths), ":");
745                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
746                         s = strcat(s, ftos(other.team), ":");
747
748                         if(cvar("sv_logscores_file"))
749                                 fputs(file, strcat(s, other.netname, "\n"));
750                         if(cvar("sv_eventlog") && gameover)
751                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
752                         else if(cvar("sv_logscores_console"))
753                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
754                 }
755                 other = other.chain;
756         }
757
758         if(cvar("sv_eventlog") && gameover)
759                 GameLogEcho(":end", FALSE);
760         else if(cvar("sv_logscores_console"))
761                 ServerConsoleEcho(":end", FALSE);
762         if(cvar("sv_logscores_file"))
763         {
764                 fputs(file, ":end\n");
765                 fclose(file);
766         }
767 }
768
769
770 /*
771 go to the next level for deathmatch
772 only called if a time or frag limit has expired
773 */
774 void() NextLevel =
775 {
776         gameover = TRUE;
777
778         intermission_running = 1;
779
780 // enforce a wait time before allowing changelevel
781         if(player_count > 0)
782                 intermission_exittime = time + cvar("sv_mapchange_delay");
783         else
784                 intermission_exittime = -60;
785
786         WriteByte (MSG_ALL, SVC_CDTRACK);
787         WriteByte (MSG_ALL, 3);
788         WriteByte (MSG_ALL, 3);
789
790         //pos = FindIntermission ();
791
792         VoteReset();
793
794         DumpStats();
795
796         if(cvar("sv_eventlog"))
797                 GameLogEcho(":gameover", FALSE);
798
799         GameLogClose();
800
801         other = findchainflags(flags, FL_CLIENT);
802         while (other != world)
803         {
804                 //other.nextthink = time + 0.5;
805                 other.takedamage = DAMAGE_NO;
806                 other.solid = SOLID_NOT;
807                 other.movetype = MOVETYPE_NONE;
808                 other.angles = other.v_angle;
809                 other.angles_x = other.angles_x * -1;
810
811                 self = other;
812
813                 if(other.winning)
814                         bprint(strcat(other.netname, " ^7wins.\n"));
815
816                 /*
817                 if (pos != world);
818                 {
819                         other.modelindex = 0;
820                         other.weaponentity = world; // remove weapon model
821                         other.view_ofs = '0 0 0';
822                         other.angles = other.v_angle = pos.mangle;
823                         if (!other.angles)
824                         {
825                                 other.angles = other.v_angle = pos.angles;
826                                 other.v_angle_x = other.v_angle_x * -1;
827                         }
828                         other.fixangle = TRUE;          // turn this way immediately
829                         setorigin (other, pos.origin);
830                 }
831                 */
832                 other = other.chain;
833         }
834
835         if(cvar("g_campaign"))
836                 CampaignPreIntermission();
837
838         WriteByte (MSG_ALL, SVC_INTERMISSION);
839
840         other = findchainflags(flags, FL_CLIENT);
841         while(other)
842         {
843                 if(clienttype(other) == CLIENTTYPE_REAL)
844                 if(cvar("sv_autoscreenshot"))
845                         stuffcmd(other, "wait\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
846                 other = other.chain;
847         }
848 };
849
850 /*
851 ============
852 CheckRules_Player
853
854 Exit deathmatch games upon conditions
855 ============
856 */
857 void() CheckRules_Player =
858 {
859         if (gameover)   // someone else quit the game already
860                 return;
861
862         // fixme: don't check players; instead check dom_team and ctf_team entities
863         //   (div0: and that in CheckRules_World please)
864         centermsg_check();
865 };
866
867 float checkrules_oneminutewarning;
868 float checkrules_leaderfrags;
869 float tdm_max_score, tdm_old_score;
870
871 float checkrules_equality;
872 float checkrules_overtimewarning;
873 float checkrules_overtimeend;
874
875 void() InitiateOvertime =
876 {
877         if(!checkrules_overtimeend)
878                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
879 }
880
881 float WINNING_NO = 0; // no winner, but time limits may terminate the game
882 float WINNING_YES = 1; // winner found
883 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
884 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
885
886 float(float fraglimitreached, float equality) GetWinningCode =
887 {
888         if(equality)
889                 if(fraglimitreached)
890                         return WINNING_STARTOVERTIME;
891                 else
892                         return WINNING_NEVER;
893         else
894                 if(fraglimitreached)
895                         return WINNING_YES;
896                 else
897                         return WINNING_NO;
898 }
899
900 // set the .winning flag for exactly those players with a given field value
901 void(.float field, float value) SetWinners =
902 {
903         entity head;
904         head = findchain(classname, "player");
905         while (head)
906         {
907                 head.winning = (head.field == value);
908                 head = head.chain;
909         }
910 }
911
912 // set the .winning flag for those players with a given field value
913 void(.float field, float value) AddWinners =
914 {
915         entity head;
916         head = findchain(classname, "player");
917         while (head)
918         {
919                 if(head.field == value)
920                         head.winning = 1;
921                 head = head.chain;
922         }
923 }
924
925 // clear the .winning flags
926 void(void) ClearWinners =
927 {
928         entity head;
929         head = findchain(classname, "player");
930         while (head)
931         {
932                 head.winning = 0;
933                 head = head.chain;
934         }
935 }
936
937 // LMS winning condition: game terminates if and only if there's at most one
938 // one player who's living lives. Top two scores being equal cancels the time
939 // limit.
940 float() WinningCondition_LMS =
941 {
942         entity head;
943
944         if(lms_dead_count < 0)
945                 lms_dead_count = 0;
946
947         if(player_count > 1 && lms_dead_count >= player_count - 1)
948                 return WINNING_YES; // He's the last man standing!
949
950         if((player_count == 1 && lms_dead_count == 1))
951                 return WINNING_YES; // All dead... (n:n is handled by the test above)
952
953         dprint("player count = "); dprint(ftos(player_count));
954         dprint(", dead count = "); dprint(ftos(lms_dead_count));
955         dprint("\n");
956
957         // When we get here, we have at least two players who are actually LIVING,
958         // or one player who is still waiting for a victim to join the server. Now
959         // check if the top two players have equal score.
960
961         checkrules_leaderfrags = 0;
962         head = findchain(classname, "player");
963         checkrules_equality = FALSE;
964         while (head)
965         {
966                 if(head.frags > checkrules_leaderfrags)
967                 {
968                         checkrules_leaderfrags = head.frags;
969                         checkrules_equality = FALSE;
970                 }
971                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
972                         checkrules_equality = TRUE;
973                 head = head.chain;
974         }
975
976         SetWinners(frags, checkrules_leaderfrags);
977
978         // The top two players have the same amount of lives? No timelimit then,
979         // enter overtime...
980
981         if(checkrules_equality)
982                 return WINNING_NEVER;
983
984         // Top two have different scores? Way to go for our beloved TIMELIMIT!
985         return WINNING_NO;
986 }
987
988 // DM winning condition: game terminates if a player reached the fraglimit,
989 // unless the first two players have the same score. The latter case also
990 // breaks the time limit.
991 float(float fraglimit) WinningCondition_MaxIndividualScore =
992 {
993         float checkrules_oldleaderfrags;
994         entity head;
995
996         checkrules_oldleaderfrags = checkrules_leaderfrags;
997         checkrules_leaderfrags = 0;
998         head = findchain(classname, "player");
999         checkrules_equality = FALSE;
1000         while (head)
1001         {
1002                 if(head.frags > checkrules_leaderfrags)
1003                 {
1004                         checkrules_leaderfrags = head.frags;
1005                         checkrules_equality = FALSE;
1006                 }
1007                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1008                         checkrules_equality = TRUE;
1009                 head = head.chain;
1010         }
1011
1012         SetWinners(frags, checkrules_leaderfrags);
1013
1014         if (!cvar("g_runematch"))
1015                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1016                 {
1017                         if (checkrules_leaderfrags == fraglimit - 1)
1018                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1019                         else if (checkrules_leaderfrags == fraglimit - 2)
1020                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1021                         else if (checkrules_leaderfrags == fraglimit - 3)
1022                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1023                 }
1024
1025         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1026 }
1027
1028 float(float fraglimit) WinningConditionBase_Teamplay =
1029 {
1030         tdm_old_score = tdm_max_score;
1031         tdm_max_score = max(team1_score, team2_score, team3_score, team4_score);
1032
1033         checkrules_equality =
1034         (
1035                 (tdm_max_score > 0)
1036                 &&
1037                 (
1038                           (team1_score == tdm_max_score)
1039                         + (team2_score == tdm_max_score)
1040                         + (team3_score == tdm_max_score)
1041                         + (team4_score == tdm_max_score)
1042                         >= 2));
1043
1044         ClearWinners();
1045         if(team1_score == tdm_max_score)
1046                 AddWinners(team, COLOR_TEAM1);
1047         if(team2_score == tdm_max_score)
1048                 AddWinners(team, COLOR_TEAM2);
1049         if(team3_score == tdm_max_score)
1050                 AddWinners(team, COLOR_TEAM3);
1051         if(team4_score == tdm_max_score)
1052                 AddWinners(team, COLOR_TEAM4);
1053
1054         if(!cvar("g_runematch") && !cvar("g_domination"))
1055                 if(tdm_max_score != tdm_old_score)
1056                 {
1057                         if(tdm_max_score == fraglimit - 1)
1058                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.ogg", 1, ATTN_NONE);
1059                         else if(tdm_max_score == fraglimit - 2)
1060                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.ogg", 1, ATTN_NONE);
1061                         else if(tdm_max_score == fraglimit - 3)
1062                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.ogg", 1, ATTN_NONE);
1063                 }
1064
1065         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1066 }
1067
1068 // TDM winning condition: game terminates if a team's score sum reached the
1069 // fraglimit, unless the first two teams have the same total score. The latter
1070 // case also breaks the time limit.
1071 float(float fraglimit) WinningCondition_MaxTeamSum =
1072 {
1073         entity head;
1074
1075         team1_score = team2_score = team3_score = team4_score = 0;
1076
1077         head = findchain(classname, "player");
1078         while (head)
1079         {
1080                 if(head.team == COLOR_TEAM1)
1081                         team1_score += head.frags;
1082                 else if(head.team == COLOR_TEAM2)
1083                         team2_score += head.frags;
1084                 else if(head.team == COLOR_TEAM3)
1085                         team3_score += head.frags;
1086                 else if(head.team == COLOR_TEAM4)
1087                         team4_score += head.frags;
1088                 head = head.chain;
1089         }
1090
1091         return WinningConditionBase_Teamplay(fraglimit);
1092 }
1093
1094 // DOM/CTF winning condition: game terminates if the max of a team's players'
1095 // score reached the fraglimit, unless the first two teams have the same
1096 // maximum score. The latter case also breaks the time limit.
1097 float(float fraglimit) WinningCondition_MaxTeamMax =
1098 {
1099         entity head;
1100
1101         team1_score = team2_score = team3_score = team4_score = 0;
1102
1103         head = findchain(classname, "player");
1104         while (head)
1105         {
1106                 if(head.team == COLOR_TEAM1)
1107                 {
1108                         if(head.frags > team1_score)
1109                                 team1_score = head.frags;
1110                 }
1111                 else if(head.team == COLOR_TEAM2)
1112                 {
1113                         if(head.frags > team2_score)
1114                                 team2_score = head.frags;
1115                 }
1116                 else if(head.team == COLOR_TEAM3)
1117                 {
1118                         if(head.frags > team3_score)
1119                                 team3_score = head.frags;
1120                 }
1121                 else if(head.team == COLOR_TEAM4)
1122                 {
1123                         if(head.frags > team4_score)
1124                                 team4_score = head.frags;
1125                 }
1126                 head = head.chain;
1127         }
1128
1129         return WinningConditionBase_Teamplay(fraglimit);
1130 }
1131
1132 void PrintScoreboardFor(string name, string colorcode, float whichteam)
1133 {
1134         entity head;
1135         float fragtotal;
1136         string s;
1137         float found;
1138         found = FALSE;
1139         head = find(world, classname, "player");
1140         while(head)
1141         {
1142                 if(!whichteam || head.team == whichteam)
1143                 {
1144                         if(name != "")
1145                                 if(!found)
1146                                         ServerConsoleEcho(strcat(" ", colorcode, name, ":"), FALSE);
1147                         found = TRUE;
1148                         fragtotal = fragtotal + head.frags;
1149                         s = ftos(head.frags);
1150                         s = strcat(s, "/", ftos(head.deaths));
1151                         s = strcat(s, " @ ", ftos(head.ping));
1152                         if(clienttype(head) == CLIENTTYPE_BOT)
1153                                 s = strcat(s, "botms");
1154                         else
1155                                 s = strcat(s, "ms");
1156                         ServerConsoleEcho(strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"), TRUE);
1157                 }
1158                 head = find(head, classname, "player");
1159         }
1160         if(whichteam && found)
1161                 ServerConsoleEcho(strcat(colorcode, "  (total: ", ftos(fragtotal), ")"), FALSE);
1162 }
1163
1164 void PrintScoreboard()
1165 {
1166         ServerConsoleEcho("Scoreboard:", FALSE);
1167         if(teams_matter)
1168         {
1169                 PrintScoreboardFor("Red", "^1", COLOR_TEAM1);
1170                 PrintScoreboardFor("Blue", "^4", COLOR_TEAM2);
1171                 PrintScoreboardFor("Pink", "^6", COLOR_TEAM3);
1172                 PrintScoreboardFor("Yellow", "^3", COLOR_TEAM4);
1173         }
1174         else
1175         {
1176                 PrintScoreboardFor("", "^7", 0);
1177         }
1178         ServerConsoleEcho(".", FALSE);
1179 }
1180
1181
1182 /*
1183 ============
1184 CheckRules_World
1185
1186 Exit deathmatch games upon conditions
1187 ============
1188 */
1189 void() CheckRules_World =
1190 {
1191         local float status;
1192         local float timelimit;
1193         local float fraglimit;
1194
1195         VoteThink();
1196
1197         SetDefaultAlpha();
1198
1199         if (intermission_running)
1200                 if (time >= intermission_exittime + 60)
1201                 {
1202                         GotoNextMap();
1203                         return;
1204                 }
1205
1206         if (gameover)   // someone else quit the game already
1207                 return;
1208
1209         DumpStats();
1210
1211         if(cvar("_scoreboard"))
1212         {
1213                 cvar_set("_scoreboard", "0");
1214                 PrintScoreboard();
1215         }
1216
1217         timelimit = cvar("timelimit") * 60;
1218         fraglimit = cvar("fraglimit");
1219
1220         if (timelimit && time >= timelimit)
1221                 InitiateOvertime();
1222
1223         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1224         {
1225                 NextLevel();
1226                 return;
1227         }
1228
1229         if(!checkrules_overtimewarning && checkrules_overtimeend)
1230         {
1231                 checkrules_overtimewarning = TRUE;
1232                 //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1233                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1234         }
1235
1236         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1237         {
1238                 checkrules_oneminutewarning = TRUE;
1239                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.ogg", 1, ATTN_NONE);
1240         }
1241
1242         status = WINNING_NO;
1243         if(cvar("g_lms"))
1244         {
1245                 status = WinningCondition_LMS();
1246         }
1247         else
1248         {
1249                 if(teams_matter)
1250                 {
1251                         if(cvar("g_tdm") || cvar("g_runematch") || cvar("g_ctf") || cvar("g_domination"))
1252                                 status = WinningCondition_MaxTeamSum(fraglimit);
1253                         //else if()
1254                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1255                         else
1256                         {
1257                                 dprint("div0: How can this happen?\n");
1258                                 status = WinningCondition_MaxTeamMax(fraglimit);
1259                         }
1260                 }
1261                 else
1262                         status = WinningCondition_MaxIndividualScore(fraglimit);
1263         }
1264
1265         if(status == WINNING_STARTOVERTIME)
1266         {
1267                 status = WINNING_NEVER;
1268                 InitiateOvertime();
1269         }
1270
1271         if(checkrules_overtimeend)
1272                 if(status != WINNING_NEVER)
1273                 {
1274                         ClearWinners();
1275                         status = WINNING_YES;
1276                 }
1277
1278         if(status == WINNING_YES)
1279                 NextLevel();
1280 };