]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/miscfunctions.qc
cl_voice_directional (play all voices directioanlly)
[divverent/nexuiz.git] / data / qcsrc / server / miscfunctions.qc
1 var void remove(entity e);
2 void objerror(string s);
3 void droptofloor();
4 .vector dropped_origin;
5
6 void() spawnfunc_info_player_deathmatch; // needed for the other spawnpoints
7 void() spawnpoint_use;
8 string ColoredTeamName(float t);
9
10 float RandomSelection_totalweight;
11 float RandomSelection_best_priority;
12 entity RandomSelection_chosen_ent;
13 float RandomSelection_chosen_float;
14 void RandomSelection_Init()
15 {
16         RandomSelection_totalweight = 0;
17         RandomSelection_chosen_ent = world;
18         RandomSelection_chosen_float = 0;
19         RandomSelection_best_priority = -1;
20 }
21 void RandomSelection_Add(entity e, float f, float weight, float priority)
22 {
23         if(priority > RandomSelection_best_priority)
24         {
25                 RandomSelection_best_priority = priority;
26                 RandomSelection_chosen_ent = e;
27                 RandomSelection_chosen_float = f;
28                 RandomSelection_totalweight = weight;
29         }
30         else if(priority == RandomSelection_best_priority)
31         {
32                 RandomSelection_totalweight += weight;
33                 if(random() * RandomSelection_totalweight <= weight)
34                 {
35                         RandomSelection_chosen_ent = e;
36                         RandomSelection_chosen_float = f;
37                 }
38         }
39 }
40
41 float DistributeEvenly_amount;
42 float DistributeEvenly_totalweight;
43 void DistributeEvenly_Init(float amount, float totalweight)
44 {
45         if(DistributeEvenly_amount)
46         {
47                 dprint("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
48                 dprint(ftos(DistributeEvenly_totalweight), " left!)\n");
49         }
50         if(totalweight == 0)
51                 DistributeEvenly_amount = 0;
52         else
53                 DistributeEvenly_amount = amount;
54         DistributeEvenly_totalweight = totalweight;
55 }
56 float DistributeEvenly_Get(float weight)
57 {
58         float f;
59         if(weight <= 0)
60                 return 0;
61         f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
62         DistributeEvenly_totalweight -= weight;
63         DistributeEvenly_amount -= f;
64         return f;
65 }
66
67 void move_out_of_solid_expand(entity e, vector by)
68 {
69         float eps = 0.0625;
70         tracebox(e.origin, e.mins - '1 1 1' * eps, e.maxs + '1 1 1' * eps, e.origin + by, MOVE_WORLDONLY, e);
71         if(trace_startsolid)
72                 return;
73         if(trace_fraction < 1)
74         {
75                 // hit something
76                 // adjust origin in the other direction...
77                 e.origin = e.origin - by * (1 - trace_fraction);
78         }
79 }
80
81 float move_out_of_solid(entity e)
82 {
83         vector o, m0, m1;
84
85         o = e.origin;
86         traceline(o, o, MOVE_WORLDONLY, e);
87         if(trace_startsolid)
88                 return 0;
89
90         tracebox(o, e.mins, e.maxs, o, MOVE_WORLDONLY, e);
91         if(!trace_startsolid)
92                 return 1;
93
94         m0 = e.mins;
95         m1 = e.maxs;
96         e.mins = '0 0 0';
97         e.maxs = '0 0 0';
98         move_out_of_solid_expand(e, '1 0 0' * m0_x); e.mins_x = m0_x;
99         move_out_of_solid_expand(e, '1 0 0' * m1_x); e.maxs_x = m1_x;
100         move_out_of_solid_expand(e, '0 1 0' * m0_y); e.mins_y = m0_y;
101         move_out_of_solid_expand(e, '0 1 0' * m1_y); e.maxs_y = m1_y;
102         move_out_of_solid_expand(e, '0 0 1' * m0_z); e.mins_z = m0_z;
103         move_out_of_solid_expand(e, '0 0 1' * m1_z); e.maxs_z = m1_z;
104         setorigin(e, e.origin);
105
106         tracebox(e.origin, e.mins, e.maxs, e.origin, MOVE_WORLDONLY, e);
107         if(trace_startsolid)
108         {
109                 setorigin(e, o);
110                 return 0;
111         }
112
113         return 1;
114 }
115
116 string STR_PLAYER = "player";
117 string STR_SPECTATOR = "spectator";
118 string STR_OBSERVER = "observer";
119
120 #if 0
121 #define FOR_EACH_CLIENT(v) for(v = world; (v = findflags(v, flags, FL_CLIENT)) != world; )
122 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
123 #define FOR_EACH_PLAYER(v) for(v = world; (v = find(v, classname, STR_PLAYER)) != world; )
124 #define FOR_EACH_REALPLAYER(v) FOR_EACH_PLAYER(v) if(clienttype(v) == CLIENTTYPE_REAL)
125 #else
126 #define FOR_EACH_CLIENTSLOT(v) for(v = world; (v = nextent(v)) && (num_for_edict(v) <= maxclients); )
127 #define FOR_EACH_CLIENT(v) FOR_EACH_CLIENTSLOT(v) if(v.flags & FL_CLIENT)
128 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
129 #define FOR_EACH_PLAYER(v) FOR_EACH_CLIENT(v) if(v.classname == STR_PLAYER)
130 #define FOR_EACH_REALPLAYER(v) FOR_EACH_REALCLIENT(v) if(v.classname == STR_PLAYER)
131 #endif
132
133 // copies a string to a tempstring (so one can strunzone it)
134 string strcat1(string s) = #115; // FRIK_FILE
135
136 float logfile_open;
137 float logfile;
138
139 void bcenterprint(string s)
140 {
141         // TODO replace by MSG_ALL (would show it to spectators too, though)?
142         entity head;
143         FOR_EACH_PLAYER(head)
144                 if(clienttype(head) == CLIENTTYPE_REAL)
145                         centerprint(head, s);
146 }
147
148 void GameLogEcho(string s)
149 {
150         string fn;
151         float matches;
152
153         if(cvar("sv_eventlog_files"))
154         {
155                 if(!logfile_open)
156                 {
157                         logfile_open = TRUE;
158                         matches = cvar("sv_eventlog_files_counter") + 1;
159                         cvar_set("sv_eventlog_files_counter", ftos(matches));
160                         fn = ftos(matches);
161                         if(strlen(fn) < 8)
162                                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
163                         fn = strcat(cvar_string("sv_eventlog_files_nameprefix"), fn, cvar_string("sv_eventlog_files_namesuffix"));
164                         logfile = fopen(fn, FILE_APPEND);
165                         fputs(logfile, ":logversion:3\n");
166                 }
167                 if(logfile >= 0)
168                 {
169                         if(cvar("sv_eventlog_files_timestamps"))
170                                 fputs(logfile, strcat(":time:", strftime(TRUE, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
171                         else
172                                 fputs(logfile, strcat(s, "\n"));
173                 }
174         }
175         if(cvar("sv_eventlog_console"))
176         {
177                 print(s, "\n");
178         }
179 }
180
181 void GameLogInit()
182 {
183         logfile_open = 0;
184         // will be opened later
185 }
186
187 void GameLogClose()
188 {
189         if(logfile_open && logfile >= 0)
190         {
191                 fclose(logfile);
192                 logfile = -1;
193         }
194 }
195
196 float spawnpoint_nag;
197 void relocate_spawnpoint()
198 {
199         // nudge off the floor
200         setorigin(self, self.origin + '0 0 1');
201
202         tracebox(self.origin, PL_MIN, PL_MAX, self.origin, TRUE, self);
203         if (trace_startsolid)
204         {
205                 vector o;
206                 o = self.origin;
207                 self.mins = PL_MIN;
208                 self.maxs = PL_MAX;
209                 if(!move_out_of_solid(self))
210                         objerror("could not get out of solid at all!");
211                 print("^1NOTE: this map needs FIXING. Spawnpoint at ", vtos(o - '0 0 1'));
212                 print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
213                 print(" ", ftos(self.origin_y - o_y));
214                 print(" ", ftos(self.origin_z - o_z), "'\n");
215                 if(cvar("g_spawnpoints_auto_move_out_of_solid"))
216                 {
217                         if(!spawnpoint_nag)
218                                 print("\{1}^1NOTE: this map needs FIXING (it contains spawnpoints in solid, see server log)\n");
219                         spawnpoint_nag = 1;
220                 }
221                 else
222                 {
223                         self.origin = o;
224                         self.mins = self.maxs = '0 0 0';
225                         objerror("player spawn point in solid, mapper sucks!\n");
226                         return;
227                 }
228         }
229
230         if(cvar("g_spawnpoints_autodrop"))
231         {
232                 setsize(self, PL_MIN, PL_MAX);
233                 droptofloor();
234         }
235
236         self.use = spawnpoint_use;
237         self.team_saved = self.team;
238         if(!self.cnt)
239                 self.cnt = 1;
240
241         if(g_ctf || g_assault || g_onslaught || g_domination)
242         if(self.team)
243                 have_team_spawns = 1;
244
245         if(cvar("r_showbboxes"))
246         {
247                 // show where spawnpoints point at too
248                 makevectors(self.angles);
249                 entity e;
250                 e = spawn();
251                 e.classname = "info_player_foo";
252                 setorigin(e, self.origin + v_forward * 24);
253                 setsize(e, '-8 -8 -8', '8 8 8');
254                 e.solid = SOLID_TRIGGER;
255         }
256 }
257
258 #define strstr strstrofs
259 /*
260 // NOTE: DO NOT USE THIS FUNCTION TOO OFTEN.
261 // IT WILL MOST PROBABLY DESTROY _ALL_ OTHER TEMP
262 // STRINGS AND TAKE QUITE LONG. haystack and needle MUST
263 // BE CONSTANT OR strzoneD!
264 float strstr(string haystack, string needle, float offset)
265 {
266         float len, endpos;
267         string found;
268         len = strlen(needle);
269         endpos = strlen(haystack) - len;
270         while(offset <= endpos)
271         {
272                 found = substring(haystack, offset, len);
273                 if(found == needle)
274                         return offset;
275                 offset = offset + 1;
276         }
277         return -1;
278 }
279 */
280
281 float NUM_NEAREST_ENTITIES = 4;
282 entity nearest_entity[NUM_NEAREST_ENTITIES];
283 float nearest_length[NUM_NEAREST_ENTITIES];
284 entity findnearest(vector point, .string field, string value, vector axismod)
285 {
286         entity localhead;
287         float i;
288         float j;
289         float len;
290         vector dist;
291
292         float num_nearest;
293         num_nearest = 0;
294
295         localhead = find(world, field, value);
296         while(localhead)
297         {
298                 if((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
299                         dist = localhead.oldorigin;
300                 else
301                         dist = localhead.origin;
302                 dist = dist - point;
303                 dist = dist_x * axismod_x * '1 0 0' + dist_y * axismod_y * '0 1 0' + dist_z * axismod_z * '0 0 1';
304                 len = vlen(dist);
305
306                 for(i = 0; i < num_nearest; ++i)
307                 {
308                         if(len < nearest_length[i])
309                                 break;
310                 }
311
312                 // now i tells us where to insert at
313                 //   INSERTION SORT! YOU'VE SEEN IT! RUN!
314                 if(i < NUM_NEAREST_ENTITIES)
315                 {
316                         for(j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
317                         {
318                                 nearest_length[j + 1] = nearest_length[j];
319                                 nearest_entity[j + 1] = nearest_entity[j];
320                         }
321                         nearest_length[i] = len;
322                         nearest_entity[i] = localhead;
323                         if(num_nearest < NUM_NEAREST_ENTITIES)
324                                 num_nearest = num_nearest + 1;
325                 }
326
327                 localhead = find(localhead, field, value);
328         }
329
330         // now use the first one from our list that we can see
331         for(i = 0; i < num_nearest; ++i)
332         {
333                 traceline(point, nearest_entity[i].origin, TRUE, world);
334                 if(trace_fraction == 1)
335                 {
336                         if(i != 0)
337                         {
338                                 dprint("Nearest point (");
339                                 dprint(nearest_entity[0].netname);
340                                 dprint(") is not visible, using a visible one.\n");
341                         }
342                         return nearest_entity[i];
343                 }
344         }
345
346         if(num_nearest == 0)
347                 return world;
348
349         dprint("Not seeing any location point, using nearest as fallback.\n");
350         /* DEBUGGING CODE:
351         dprint("Candidates were: ");
352         for(j = 0; j < num_nearest; ++j)
353         {
354                 if(j != 0)
355                         dprint(", ");
356                 dprint(nearest_entity[j].netname);
357         }
358         dprint("\n");
359         */
360
361         return nearest_entity[0];
362 }
363
364 void spawnfunc_target_location()
365 {
366         self.classname = "target_location";
367         // location name in netname
368         // eventually support: count, teamgame selectors, line of sight?
369 };
370
371 void spawnfunc_info_location()
372 {
373         self.classname = "target_location";
374         self.message = self.netname;
375 };
376
377 string NearestLocation(vector p)
378 {
379         entity loc;
380         string ret;
381         ret = "somewhere";
382         loc = findnearest(p, classname, "target_location", '1 1 1');
383         if(loc)
384         {
385                 ret = loc.message;
386         }
387         else
388         {
389                 loc = findnearest(p, target, "###item###", '1 1 4');
390                 if(loc)
391                         ret = loc.netname;
392         }
393         return ret;
394 }
395
396 string formatmessage(string msg)
397 {
398         float p;
399         float n;
400         string msg_save;
401         string escape;
402         string replacement;
403         msg_save = strzone(msg);
404         p = 0;
405         n = 7;
406         while(1)
407         {
408                 if(n < 1)
409                         break; // too many replacements
410                 n = n - 1;
411                 p = strstr(msg_save, "%", p); // NOTE: this destroys msg as it's a tempstring!
412                 if(p < 0)
413                         break;
414                 replacement = substring(msg_save, p, 2);
415                 escape = substring(msg_save, p + 1, 1);
416                 if(escape == "%")
417                         replacement = "%";
418                 else if(escape == "a")
419                         replacement = ftos(floor(self.armorvalue));
420                 else if(escape == "h")
421                         replacement = ftos(floor(self.health));
422                 else if(escape == "l")
423                         replacement = NearestLocation(self.origin);
424                 else if(escape == "y")
425                         replacement = NearestLocation(self.cursor_trace_endpos);
426                 else if(escape == "d")
427                         replacement = NearestLocation(self.death_origin);
428                 else if(escape == "w")
429                 {
430                         float wep;
431                         wep = self.weapon;
432                         if(!wep)
433                                 wep = self.switchweapon;
434                         if(!wep)
435                                 wep = self.cnt;
436                         replacement = W_Name(wep);
437                 }
438                 else if(escape == "W")
439                 {
440                         if(self.items & IT_SHELLS) replacement = "shells";
441                         else if(self.items & IT_NAILS) replacement = "bullets";
442                         else if(self.items & IT_ROCKETS) replacement = "rockets";
443                         else if(self.items & IT_CELLS) replacement = "cells";
444                         else replacement = "batteries"; // ;)
445                 }
446                 else if(escape == "x")
447                 {
448                         replacement = self.cursor_trace_ent.netname;
449                         if(!replacement || !self.cursor_trace_ent)
450                                 replacement = "nothing";
451                 }
452                 else if(escape == "p")
453                 {
454                         if(self.last_selected_player)
455                                 replacement = self.last_selected_player.netname;
456                         else
457                                 replacement = "(nobody)";
458                 }
459                 msg = strcat(substring(msg_save, 0, p), replacement);
460                 msg = strcat(msg, substring(msg_save, p+2, strlen(msg_save) - (p+2)));
461                 strunzone(msg_save);
462                 msg_save = strzone(msg);
463                 p = p + 2;
464         }
465         msg = strcat(msg_save, "");
466         strunzone(msg_save);
467         return msg;
468 }
469
470 /*
471 =============
472 GetCvars
473 =============
474 Called with:
475   0:  sends the request
476   >0: receives a cvar from name=argv(f) value=argv(f+1)
477 */
478 void GetCvars_handleString(string thisname, float f, .string field, string name)
479 {
480         if(f < 0)
481         {
482                 if(self.field)
483                         strunzone(self.field);
484                 self.field = string_null;
485         }
486         else if(f > 0)
487         {
488                 if(thisname == name)
489                 {
490                         if(self.field)
491                                 strunzone(self.field);
492                         self.field = strzone(argv(f + 1));
493                 }
494         }
495         else
496                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
497 }
498 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
499 {
500         GetCvars_handleString(thisname, f, field, name);
501         if(f >= 0) // also initialize to the fitting value for "" when sending cvars out
502         if(thisname == name)
503         {
504                 string s;
505                 s = func(strcat1(self.field));
506                 if(s != self.field)
507                 {
508                         strunzone(self.field);
509                         self.field = strzone(s);
510                 }
511         }
512 }
513 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
514 {
515         if(f < 0)
516         {
517         }
518         else if(f > 0)
519         {
520                 if(thisname == name)
521                         self.field = stof(argv(f + 1));
522         }
523         else
524                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
525 }
526 string W_FixWeaponOrder_ForceComplete(string s);
527 string W_FixWeaponOrder_AllowIncomplete(string s);
528 float w_getbestweapon(entity e);
529 void GetCvars(float f)
530 {
531         string s;
532         if(f > 0)
533                 s = strcat1(argv(f));
534         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
535         GetCvars_handleFloat(s, f, cvar_cl_playerdetailreduction, "cl_playerdetailreduction");
536         GetCvars_handleFloat(s, f, cvar_cl_nogibs, "cl_nogibs");
537         GetCvars_handleFloat(s, f, cvar_scr_centertime, "scr_centertime");
538         GetCvars_handleFloat(s, f, cvar_cl_shownames, "cl_shownames");
539         GetCvars_handleString(s, f, cvar_g_nexuizversion, "g_nexuizversion");
540         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
541         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete);
542         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
543         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
544         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
545         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
546         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
547         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
548         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
549         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
550         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
551         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
552         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
553         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
554         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
555         GetCvars_handleFloat(s, f, cvar_cl_hitsound, "cl_hitsound");
556
557         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
558         if(f > 0)
559         {
560                 if(s == "cl_weaponpriority")
561                         self.switchweapon = w_getbestweapon(self);
562         }
563 }
564
565 float fexists(string f)
566 {
567         float fh;
568         fh = fopen(f, FILE_READ);
569         if(fh < 0)
570                 return FALSE;
571         fclose(fh);
572         return TRUE;
573 }
574
575 void backtrace(string msg)
576 {
577         float dev;
578         dev = cvar("developer");
579         cvar_set("developer", "1");
580         dprint("\n");
581         dprint("--- CUT HERE ---\nWARNING: ");
582         dprint(msg);
583         dprint("\n");
584         remove(world); // isn't there any better way to cause a backtrace?
585         dprint("\n--- CUT UNTIL HERE ---\n");
586         cvar_set("developer", ftos(dev));
587 }
588
589 string Team_ColorCode(float teamid)
590 {
591         if(teamid == COLOR_TEAM1)
592                 return "^1";
593         else if(teamid == COLOR_TEAM2)
594                 return "^4";
595         else if(teamid == COLOR_TEAM3)
596                 return "^3";
597         else if(teamid == COLOR_TEAM4)
598                 return "^6";
599         else
600                 return "^7";
601 }
602 string Team_ColorName(float t)
603 {
604         // fixme: Search for team entities and get their .netname's!
605         if(t == COLOR_TEAM1)
606                 return "Red";
607         if(t == COLOR_TEAM2)
608                 return "Blue";
609         if(t == COLOR_TEAM3)
610                 return "Yellow";
611         if(t == COLOR_TEAM4)
612                 return "Pink";
613         return "Neutral";
614 }
615 string Team_ColorNameLowerCase(float t)
616 {
617         // fixme: Search for team entities and get their .netname's!
618         if(t == COLOR_TEAM1)
619                 return "red";
620         if(t == COLOR_TEAM2)
621                 return "blue";
622         if(t == COLOR_TEAM3)
623                 return "yellow";
624         if(t == COLOR_TEAM4)
625                 return "pink";
626         return "neutral";
627 }
628
629 #define CENTERPRIO_POINT 1
630 #define CENTERPRIO_SPAM 2
631 #define CENTERPRIO_VOTE 4
632 #define CENTERPRIO_NORMAL 5
633 #define CENTERPRIO_SHIELDING 7
634 #define CENTERPRIO_MAPVOTE 9
635 #define CENTERPRIO_IDLEKICK 50
636 #define CENTERPRIO_ADMIN 99
637 .float centerprint_priority;
638 .float centerprint_expires;
639 void centerprint_atprio(entity e, float prio, string s)
640 {
641         if(intermission_running)
642                 if(prio < CENTERPRIO_MAPVOTE)
643                         return;
644         if(time > e.centerprint_expires)
645                 e.centerprint_priority = 0;
646         if(prio >= e.centerprint_priority)
647         {
648                 e.centerprint_priority = prio;
649                 if(timeoutStatus == 2)
650                         e.centerprint_expires = time + (e.cvar_scr_centertime * TIMEOUT_SLOWMO_VALUE);
651                 else
652                         e.centerprint_expires = time + e.cvar_scr_centertime;
653                 centerprint_builtin(e, s);
654         }
655 }
656 void centerprint_expire(entity e, float prio)
657 {
658         if(prio == e.centerprint_priority)
659         {
660                 e.centerprint_priority = 0;
661                 centerprint_builtin(e, "");
662         }
663 }
664 void centerprint(entity e, string s)
665 {
666         centerprint_atprio(e, CENTERPRIO_NORMAL, s);
667 }
668
669 // decolorizes and team colors the player name when needed
670 string playername(entity p)
671 {
672         string t;
673         if(teams_matter && !intermission_running && p.classname == "player")
674         {
675                 t = Team_ColorCode(p.team);
676                 return strcat(t, strdecolorize(p.netname));
677         }
678         else
679                 return p.netname;
680 }
681
682 vector randompos(vector m1, vector m2)
683 {
684         local vector v;
685         m2 = m2 - m1;
686         v_x = m2_x * random() + m1_x;
687         v_y = m2_y * random() + m1_y;
688         v_z = m2_z * random() + m1_z;
689         return  v;
690 };
691
692 // requires that m2>m1 in all coordinates, and that m4>m3
693 float boxesoverlap(vector m1, vector m2, vector m3, vector m4) {return m2_x >= m3_x && m1_x <= m4_x && m2_y >= m3_y && m1_y <= m4_y && m2_z >= m3_z && m1_z <= m4_z;};
694
695 // requires the same, but is a stronger condition
696 float boxinsidebox(vector smins, vector smaxs, vector bmins, vector bmaxs) {return smins_x >= bmins_x && smaxs_x <= bmaxs_x && smins_y >= bmins_y && smaxs_y <= bmaxs_y && smins_z >= bmins_z && smaxs_z <= bmaxs_z;};
697
698 float g_pickup_shells;
699 float g_pickup_shells_max;
700 float g_pickup_nails;
701 float g_pickup_nails_max;
702 float g_pickup_rockets;
703 float g_pickup_rockets_max;
704 float g_pickup_cells;
705 float g_pickup_cells_max;
706 float g_pickup_armorsmall;
707 float g_pickup_armorsmall_max;
708 float g_pickup_armormedium;
709 float g_pickup_armormedium_max;
710 float g_pickup_armorlarge;
711 float g_pickup_armorlarge_max;
712 float g_pickup_healthsmall;
713 float g_pickup_healthsmall_max;
714 float g_pickup_healthmedium;
715 float g_pickup_healthmedium_max;
716 float g_pickup_healthlarge;
717 float g_pickup_healthlarge_max;
718 float g_pickup_healthmega;
719 float g_pickup_healthmega_max;
720 float g_weaponarena;
721 string g_weaponarena_list;
722
723 float start_weapons;
724 float start_items;
725 float start_ammo_shells;
726 float start_ammo_nails;
727 float start_ammo_rockets;
728 float start_ammo_cells;
729 float start_health;
730 float start_armorvalue;
731 float warmup_start_weapons;
732 float warmup_start_ammo_shells;
733 float warmup_start_ammo_nails;
734 float warmup_start_ammo_rockets;
735 float warmup_start_ammo_cells;
736 float warmup_start_health;
737 float warmup_start_armorvalue;
738
739 entity get_weaponinfo(float w);
740
741 void readplayerstartcvars()
742 {
743         entity e;
744         float i, j, t;
745         string s;
746
747         // initialize starting values for players
748         start_weapons = 0;
749         start_items = 0;
750         start_ammo_shells = 0;
751         start_ammo_nails = 0;
752         start_ammo_rockets = 0;
753         start_ammo_cells = 0;
754         start_health = cvar("g_balance_health_start");
755         start_armorvalue = cvar("g_balance_armor_start");
756
757         g_weaponarena = 0;
758         s = cvar_string("g_weaponarena");
759         if(s == "0")
760         {
761         }
762         else if(s == "all")
763         {
764                 g_weaponarena_list = "All Weapons";
765                 for(j = WEP_FIRST; j <= WEP_LAST; ++j)
766                 {
767                         e = get_weaponinfo(j);
768                         g_weaponarena |= e.weapons;
769                         weapon_action(e.weapon, WR_PRECACHE);
770                 }
771         }
772         else if(s == "most")
773         {
774                 g_weaponarena_list = "Most Weapons";
775                 for(j = WEP_FIRST; j <= WEP_LAST; ++j)
776                 {
777                         e = get_weaponinfo(j);
778                         if(e.spawnflags & WEPSPAWNFLAG_NORMAL)
779                         {
780                                 g_weaponarena |= e.weapons;
781                                 weapon_action(e.weapon, WR_PRECACHE);
782                         }
783                 }
784         }
785         else
786         {
787                 t = tokenize_sane(s);
788                 g_weaponarena_list = "";
789                 for(i = 0; i < t; ++i)
790                 {
791                         s = argv(i);
792                         for(j = WEP_FIRST; j <= WEP_LAST; ++j)
793                         {
794                                 e = get_weaponinfo(j);
795                                 if(e.netname == s)
796                                 {
797                                         g_weaponarena |= e.weapons;
798                                         weapon_action(e.weapon, WR_PRECACHE);
799                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
800                                         break;
801                                 }
802                         }
803                         if(j > WEP_LAST)
804                         {
805                                 print("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
806                         }
807                 }
808                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
809         }
810
811         if(g_weaponarena)
812         {
813                 start_weapons = g_weaponarena;
814                 start_ammo_rockets = 999;
815                 start_ammo_shells = 999;
816                 start_ammo_cells = 999;
817                 start_ammo_nails = 999;
818                 start_items |= IT_UNLIMITED_AMMO;
819         }
820         else if(g_nixnex)
821         {
822                 start_weapons = 0;
823                 // will be done later
824                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
825                 {
826                         e = get_weaponinfo(i);
827                         if(!(e.weapon))
828                                 continue;
829                         weapon_action(e.weapon, WR_PRECACHE);
830                 }
831         }
832         else if(g_minstagib)
833         {
834                 start_health = 100;
835                 start_armorvalue = 0;
836                 start_weapons = WEPBIT_MINSTANEX;
837                 weapon_action(WEP_MINSTANEX, WR_PRECACHE);
838                 start_ammo_cells = cvar("g_minstagib_ammo_start");
839                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
840         }
841         else
842         {
843                 if(g_lms)
844                 {
845                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
846                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
847                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
848                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
849                         start_health = cvar("g_lms_start_health");
850                         start_armorvalue = cvar("g_lms_start_armor");
851                 } else if (cvar("g_use_ammunition")) {
852                         start_ammo_shells = cvar("g_start_ammo_shells");
853                         start_ammo_nails = cvar("g_start_ammo_nails");
854                         start_ammo_rockets = cvar("g_start_ammo_rockets");
855                         start_ammo_cells = cvar("g_start_ammo_cells");
856                 } else {
857                         start_ammo_shells = cvar("g_pickup_shells_max");
858                         start_ammo_nails = cvar("g_pickup_nails_max");
859                         start_ammo_rockets = cvar("g_pickup_rockets_max");
860                         start_ammo_cells = cvar("g_pickup_cells_max");
861                         start_items |= IT_UNLIMITED_AMMO;
862                 }
863
864                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
865                 {
866                         e = get_weaponinfo(i);
867                         if(!(e.weapon))
868                                 continue;
869                         if(((e.spawnflags & WEPSPAWNFLAG_NORMAL) && g_lms) || cvar(strcat("g_start_weapon_", e.netname)))
870                         {
871                                 start_weapons |= e.weapons;
872                                 weapon_action(e.weapon, WR_PRECACHE);
873                         }
874                 }
875         }
876
877         if(inWarmupStage)
878         {
879                 warmup_start_ammo_shells = start_ammo_shells;
880                 warmup_start_ammo_nails = start_ammo_nails;
881                 warmup_start_ammo_rockets = start_ammo_rockets;
882                 warmup_start_ammo_cells = start_ammo_cells;
883                 warmup_start_health = start_health;
884                 warmup_start_armorvalue = start_armorvalue;
885                 warmup_start_weapons = start_weapons;
886
887                 if(!g_weaponarena && !g_nixnex && !g_minstagib)
888                 {
889                         if(cvar("g_use_ammunition"))
890                         {
891                                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
892                                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
893                                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
894                                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
895                         }
896                         warmup_start_health = cvar("g_warmup_start_health");
897                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
898                         if(cvar("g_warmup_allguns"))
899                         {
900                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
901                                 {
902                                         e = get_weaponinfo(i);
903                                         if(!(e.weapon))
904                                                 continue;
905                                         if(e.spawnflags & WEPSPAWNFLAG_NORMAL)
906                                         {
907                                                 warmup_start_weapons |= e.weapons;
908                                                 weapon_action(e.weapon, WR_PRECACHE);
909                                         }
910                                 }
911                         }
912                 }
913         }
914
915         if(g_grappling_hook) // offhand hook
916         {
917                 start_weapons &~= WEPBIT_HOOK;
918                 warmup_start_weapons &~= WEPBIT_HOOK;
919         }
920 }
921
922 float g_bugrigs;
923 float g_bugrigs_planar_movement;
924 float g_bugrigs_planar_movement_car_jumping;
925 float g_bugrigs_reverse_spinning;
926 float g_bugrigs_reverse_speeding;
927 float g_bugrigs_reverse_stopping;
928 float g_bugrigs_air_steering;
929 float g_bugrigs_angle_smoothing;
930 float g_bugrigs_friction_floor;
931 float g_bugrigs_friction_brake;
932 float g_bugrigs_friction_air;
933 float g_bugrigs_accel;
934 float g_bugrigs_speed_ref;
935 float g_bugrigs_speed_pow;
936 float g_bugrigs_steer;
937
938 float g_touchexplode;
939 float g_touchexplode_radius;
940 float g_touchexplode_damage;
941 float g_touchexplode_edgedamage;
942 float g_touchexplode_force;
943
944 void readlevelcvars(void)
945 {
946         g_bugrigs = cvar("g_bugrigs");
947         g_bugrigs_planar_movement = cvar("g_bugrigs_planar_movement");
948         g_bugrigs_planar_movement_car_jumping = cvar("g_bugrigs_planar_movement_car_jumping");
949         g_bugrigs_reverse_spinning = cvar("g_bugrigs_reverse_spinning");
950         g_bugrigs_reverse_speeding = cvar("g_bugrigs_reverse_speeding");
951         g_bugrigs_reverse_stopping = cvar("g_bugrigs_reverse_stopping");
952         g_bugrigs_air_steering = cvar("g_bugrigs_air_steering");
953         g_bugrigs_angle_smoothing = cvar("g_bugrigs_angle_smoothing");
954         g_bugrigs_friction_floor = cvar("g_bugrigs_friction_floor");
955         g_bugrigs_friction_brake = cvar("g_bugrigs_friction_brake");
956         g_bugrigs_friction_air = cvar("g_bugrigs_friction_air");
957         g_bugrigs_accel = cvar("g_bugrigs_accel");
958         g_bugrigs_speed_ref = cvar("g_bugrigs_speed_ref");
959         g_bugrigs_speed_pow = cvar("g_bugrigs_speed_pow");
960         g_bugrigs_steer = cvar("g_bugrigs_steer");
961
962         g_touchexplode = cvar("g_touchexplode");
963         g_touchexplode_radius = cvar("g_touchexplode_radius");
964         g_touchexplode_damage = cvar("g_touchexplode_damage");
965         g_touchexplode_edgedamage = cvar("g_touchexplode_edgedamage");
966         g_touchexplode_force = cvar("g_touchexplode_force");
967
968         sv_clones = cvar("sv_clones");
969         sv_cheats = cvar("sv_cheats");
970         sv_gentle = cvar("sv_gentle");
971         sv_foginterval = cvar("sv_foginterval");
972         g_cloaked = cvar("g_cloaked");
973         g_jump_grunt = cvar("g_jump_grunt");
974         g_footsteps = cvar("g_footsteps");
975         g_grappling_hook = cvar("g_grappling_hook");
976         g_laserguided_missile = cvar("g_laserguided_missile");
977         g_midair = cvar("g_midair");
978         g_minstagib = cvar("g_minstagib");
979         g_nixnex = cvar("g_nixnex");
980         g_nixnex_with_laser = cvar("g_nixnex_with_laser");
981         g_norecoil = cvar("g_norecoil");
982         g_vampire = cvar("g_vampire");
983         sv_maxidle = cvar("sv_maxidle");
984         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
985         sv_pogostick = cvar("sv_pogostick");
986         sv_doublejump = cvar("sv_doublejump");
987         g_maplist_allow_hidden = cvar("g_maplist_allow_hidden");
988         g_ctf_reverse = cvar("g_ctf_reverse");
989
990         inWarmupStage = cvar("g_warmup");
991         g_warmup_limit = cvar("g_warmup_limit");
992         g_warmup_allguns = cvar("g_warmup_allguns");
993         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
994
995         if(g_race && g_race_qualifying == 2 || g_arena || g_assault || cvar("g_campaign"))
996                 inWarmupStage = 0; // these modes cannot work together, sorry
997
998         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
999         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
1000         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
1001         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
1002         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
1003         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
1004
1005         if(g_minstagib) g_nixnex = g_weaponarena = 0;
1006         if(g_nixnex) g_weaponarena = 0;
1007         g_weaponarena = 0;
1008
1009         g_pickup_shells                    = cvar("g_pickup_shells");
1010         g_pickup_shells_max                = cvar("g_pickup_shells_max");
1011         g_pickup_nails                     = cvar("g_pickup_nails");
1012         g_pickup_nails_max                 = cvar("g_pickup_nails_max");
1013         g_pickup_rockets                   = cvar("g_pickup_rockets");
1014         g_pickup_rockets_max               = cvar("g_pickup_rockets_max");
1015         g_pickup_cells                     = cvar("g_pickup_cells");
1016         g_pickup_cells_max                 = cvar("g_pickup_cells_max");
1017         g_pickup_armorsmall                = cvar("g_pickup_armorsmall");
1018         g_pickup_armorsmall_max            = cvar("g_pickup_armorsmall_max");
1019         g_pickup_armormedium               = cvar("g_pickup_armormedium");
1020         g_pickup_armormedium_max           = cvar("g_pickup_armormedium_max");
1021         g_pickup_armorlarge                = cvar("g_pickup_armorlarge");
1022         g_pickup_armorlarge_max            = cvar("g_pickup_armorlarge_max");
1023         g_pickup_healthsmall               = cvar("g_pickup_healthsmall");
1024         g_pickup_healthsmall_max           = cvar("g_pickup_healthsmall_max");
1025         g_pickup_healthmedium              = cvar("g_pickup_healthmedium");
1026         g_pickup_healthmedium_max          = cvar("g_pickup_healthmedium_max");
1027         g_pickup_healthlarge               = cvar("g_pickup_healthlarge");
1028         g_pickup_healthlarge_max           = cvar("g_pickup_healthlarge_max");
1029         g_pickup_healthmega                = cvar("g_pickup_healthmega");
1030         g_pickup_healthmega_max            = cvar("g_pickup_healthmega_max");
1031
1032         if not(inWarmupStage)
1033         {
1034                 game_starttime                 = cvar("g_start_delay");
1035                 if(game_starttime)
1036                 {
1037                         restartAnnouncer = spawn();
1038                         restartAnnouncer.think = restartAnnouncer_Think;
1039                         restartAnnouncer.nextthink = time + 0.1;
1040                         restartAnnouncer.spawnflags = 0;
1041                 }
1042         }
1043
1044         readplayerstartcvars();
1045 }
1046
1047 /*
1048 // TODO sound pack system
1049 string soundpack;
1050
1051 string precache_sound_builtin (string s) = #19;
1052 void(entity e, float chan, string samp, float vol, float atten) sound_builtin = #8;
1053 string precache_sound(string s)
1054 {
1055         return precache_sound_builtin(strcat(soundpack, s));
1056 }
1057 void play2(entity e, string filename)
1058 {
1059         stuffcmd(e, strcat("play2 ", soundpack, filename, "\n"));
1060 }
1061 void sound(entity e, float chan, string samp, float vol, float atten)
1062 {
1063         sound_builtin(e, chan, strcat(soundpack, samp), vol, atten);
1064 }
1065 */
1066
1067 // Sound functions
1068 string precache_sound (string s) = #19;
1069 void(entity e, float chan, string samp, float vol, float atten) sound = #8;
1070 float precache_sound_index (string s) = #19;
1071
1072 #define SND_VOLUME      1
1073 #define SND_ATTENUATION 2
1074 #define SND_LARGEENTITY 8
1075 #define SND_LARGESOUND  16
1076
1077 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
1078 {
1079         float entno, idx;
1080         entno = num_for_edict(e);
1081         idx = precache_sound_index(samp);
1082
1083         float sflags;
1084         sflags = 0;
1085
1086         atten = floor(atten * 64);
1087         vol = floor(vol * 255);
1088
1089         if(vol != 255)
1090                 sflags |= SND_VOLUME;
1091         if(atten != 64)
1092                 sflags |= SND_ATTENUATION;
1093         if(entno >= 8192)
1094                 sflags |= SND_LARGEENTITY;
1095         if(idx >= 256)
1096                 sflags |= SND_LARGESOUND;
1097
1098         WriteByte(dest, SVC_SOUND);
1099         WriteByte(dest, sflags);
1100         if(sflags & SND_VOLUME)
1101                 WriteByte(dest, vol * 255);
1102         if(sflags & SND_ATTENUATION)
1103                 WriteByte(dest, atten);
1104         if(sflags & SND_LARGEENTITY)
1105         {
1106                 WriteShort(dest, entno);
1107                 WriteByte(dest, chan);
1108         }
1109         else
1110         {
1111                 WriteShort(dest, entno * 8 + chan);
1112         }
1113         if(sflags & SND_LARGESOUND)
1114                 WriteShort(dest, idx);
1115         else
1116                 WriteByte(dest, idx);
1117
1118         WriteCoord(dest, o_x);
1119         WriteCoord(dest, o_y);
1120         WriteCoord(dest, o_z);
1121 }
1122 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1123 {
1124         vector o;
1125         o = e.origin + 0.5 * (e.mins + e.maxs);
1126         soundtoat(dest, e, o, chan, samp, vol, atten);
1127 }
1128 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1129 {
1130         soundtoat(MSG_BROADCAST, e, o, chan, samp, vol, atten);
1131 }
1132 void stopsoundto(float dest, entity e, float chan)
1133 {
1134         float entno;
1135         entno = num_for_edict(e);
1136
1137         if(entno >= 8192)
1138         {
1139                 float idx, sflags;
1140                 idx = precache_sound_index("misc/null.wav");
1141                 sflags = SND_LARGEENTITY;
1142                 if(idx >= 256)
1143                         sflags |= SND_LARGESOUND;
1144                 WriteByte(dest, SVC_SOUND);
1145                 WriteByte(dest, sflags);
1146                 WriteShort(dest, entno);
1147                 WriteByte(dest, chan);
1148                 if(sflags & SND_LARGESOUND)
1149                         WriteShort(dest, idx);
1150                 else
1151                         WriteByte(dest, idx);
1152                 WriteCoord(dest, e.origin_x);
1153                 WriteCoord(dest, e.origin_y);
1154                 WriteCoord(dest, e.origin_z);
1155         }
1156         else
1157         {
1158                 WriteByte(dest, SVC_STOPSOUND);
1159                 WriteShort(dest, entno * 8 + chan);
1160         }
1161 }
1162 void stopsound(entity e, float chan)
1163 {
1164         stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
1165         stopsoundto(MSG_ALL, e, chan); // in case of packet loss
1166 }
1167
1168 void play2(entity e, string filename)
1169 {
1170         //stuffcmd(e, strcat("play2 ", filename, "\n"));
1171         msg_entity = e;
1172         soundtoat(MSG_ONE, world, '0 0 0', CHAN_AUTO, filename, VOL_BASE, ATTN_NONE);
1173 }
1174
1175 .float announcetime;
1176 float announce(entity player, string msg)
1177 {
1178         if(time > player.announcetime)
1179         if(clienttype(player) == CLIENTTYPE_REAL)
1180         {
1181                 player.announcetime = time + 0.3;
1182                 play2(player, msg);
1183                 return TRUE;
1184         }
1185         return FALSE;
1186 }
1187
1188 void play2team(float t, string filename)
1189 {
1190         local entity head;
1191         FOR_EACH_REALPLAYER(head)
1192         {
1193                 if (head.team == t)
1194                         play2(head, filename);
1195         }
1196 }
1197
1198 void play2all(string samp)
1199 {
1200         sound(world, CHAN_AUTO, samp, VOL_BASE, ATTN_NONE);
1201 }
1202
1203 void PrecachePlayerSounds(string f);
1204 void precache_all_models(string pattern)
1205 {
1206         float globhandle, i, n;
1207         string f;
1208
1209         globhandle = search_begin(pattern, TRUE, FALSE);
1210         if(globhandle < 0)
1211                 return;
1212         n = search_getsize(globhandle);
1213         for(i = 0; i < n; ++i)
1214         {
1215                 //print(search_getfilename(globhandle, i), "\n");
1216                 f = search_getfilename(globhandle, i);
1217                 precache_model(f);
1218                 PrecachePlayerSounds(strcat(f, ".sounds"));
1219         }
1220         search_end(globhandle);
1221 }
1222
1223 void precache()
1224 {
1225         // gamemode related things
1226         precache_model ("null");
1227         precache_model ("models/misc/chatbubble.spr");
1228         precache_model ("models/misc/teambubble.spr");
1229         if (g_runematch)
1230         {
1231                 precache_model ("models/runematch/curse.mdl");
1232                 precache_model ("models/runematch/rune.mdl");
1233         }
1234
1235 #ifdef TTURRETS_ENABLED
1236     if(cvar("g_turrets"))
1237         turrets_precash();
1238 #endif
1239
1240         // Precache all player models if desired
1241         if (cvar("sv_precacheplayermodels"))
1242         {
1243                 PrecachePlayerSounds("sound/player/default.sounds");
1244                 precache_all_models("models/player/*.zym");
1245                 precache_all_models("models/player/*.dpm");
1246                 precache_all_models("models/player/*.md3");
1247                 precache_all_models("models/player/*.psk");
1248                 //precache_model("models/player/carni.zym");
1249                 //precache_model("models/player/crash.zym");
1250                 //precache_model("models/player/grunt.zym");
1251                 //precache_model("models/player/headhunter.zym");
1252                 //precache_model("models/player/insurrectionist.zym");
1253                 //precache_model("models/player/jeandarc.zym");
1254                 //precache_model("models/player/lurk.zym");
1255                 //precache_model("models/player/lycanthrope.zym");
1256                 //precache_model("models/player/marine.zym");
1257                 //precache_model("models/player/nexus.zym");
1258                 //precache_model("models/player/pyria.zym");
1259                 //precache_model("models/player/shock.zym");
1260                 //precache_model("models/player/skadi.zym");
1261                 //precache_model("models/player/specop.zym");
1262                 //precache_model("models/player/visitant.zym");
1263         }
1264
1265         if(cvar("sv_defaultcharacter"))
1266         {
1267                 string s;
1268                 s = cvar_string("sv_defaultplayermodel_red");
1269                 if(s != "")
1270                 {
1271                         precache_model(s);
1272                         PrecachePlayerSounds(strcat(s, ".sounds"));
1273                 }
1274                 s = cvar_string("sv_defaultplayermodel_blue");
1275                 if(s != "")
1276                 {
1277                         precache_model(s);
1278                         PrecachePlayerSounds(strcat(s, ".sounds"));
1279                 }
1280                 s = cvar_string("sv_defaultplayermodel_yellow");
1281                 if(s != "")
1282                 {
1283                         precache_model(s);
1284                         PrecachePlayerSounds(strcat(s, ".sounds"));
1285                 }
1286                 s = cvar_string("sv_defaultplayermodel_pink");
1287                 if(s != "")
1288                 {
1289                         precache_model(s);
1290                         PrecachePlayerSounds(strcat(s, ".sounds"));
1291                 }
1292                 s = cvar_string("sv_defaultplayermodel");
1293                 if(s != "")
1294                 {
1295                         precache_model(s);
1296                         PrecachePlayerSounds(strcat(s, ".sounds"));
1297                 }
1298         }
1299
1300         if (g_footsteps)
1301         {
1302                 PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1303                 PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1304         }
1305
1306         // gore and miscellaneous sounds
1307         //precache_sound ("misc/h2ohit.wav");
1308         precache_model ("models/gibs/bloodyskull.md3");
1309         precache_model ("models/gibs/chunk.mdl");
1310         precache_model ("models/gibs/eye.md3");
1311         precache_model ("models/gibs/gib1.md3");
1312         precache_model ("models/gibs/gib2.md3");
1313         precache_model ("models/gibs/gib3.md3");
1314         precache_model ("models/gibs/gib4.md3");
1315         precache_model ("models/gibs/gib5.md3");
1316         precache_model ("models/gibs/gib6.md3");
1317         precache_model ("models/gibs/smallchest.md3");
1318         precache_model ("models/gibs/chest.md3");
1319         precache_model ("models/gibs/arm.md3");
1320         precache_model ("models/gibs/leg1.md3");
1321         precache_model ("models/gibs/leg2.md3");
1322         precache_model ("models/hook.md3");
1323         precache_sound ("misc/armorimpact.wav");
1324         precache_sound ("misc/bodyimpact1.wav");
1325         precache_sound ("misc/bodyimpact2.wav");
1326         precache_sound ("misc/gib.wav");
1327         precache_sound ("misc/gib_splat01.wav");
1328         precache_sound ("misc/gib_splat02.wav");
1329         precache_sound ("misc/gib_splat03.wav");
1330         precache_sound ("misc/gib_splat04.wav");
1331         precache_sound ("misc/hit.wav");
1332         PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1333         PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1334         precache_sound ("misc/null.wav");
1335         precache_sound ("misc/spawn.wav");
1336         precache_sound ("misc/talk.wav");
1337         precache_sound ("misc/teleport.wav");
1338         precache_sound ("player/lava.wav");
1339         precache_sound ("player/slime.wav");
1340
1341         // announcer sounds - male
1342         precache_sound ("announcer/male/electrobitch.wav");
1343         precache_sound ("announcer/male/airshot.wav");
1344         precache_sound ("announcer/male/03kills.wav");
1345         precache_sound ("announcer/male/05kills.wav");
1346         precache_sound ("announcer/male/10kills.wav");
1347         precache_sound ("announcer/male/15kills.wav");
1348         precache_sound ("announcer/male/20kills.wav");
1349         precache_sound ("announcer/male/25kills.wav");
1350         precache_sound ("announcer/male/30kills.wav");
1351         precache_sound ("announcer/male/botlike.wav");
1352         precache_sound ("announcer/male/yoda.wav");
1353         precache_sound ("announcer/male/headshot.wav");
1354         precache_sound ("announcer/male/impressive.wav");
1355
1356         // announcer sounds - robotic
1357         precache_sound ("announcer/robotic/prepareforbattle.wav");
1358         precache_sound ("announcer/robotic/begin.wav");
1359         precache_sound ("announcer/robotic/timeoutcalled.wav");
1360         precache_sound ("announcer/robotic/1fragleft.wav");
1361         precache_sound ("announcer/robotic/1minuteremains.wav");
1362         precache_sound ("announcer/robotic/2fragsleft.wav");
1363         precache_sound ("announcer/robotic/3fragsleft.wav");
1364         if (g_minstagib)
1365         {
1366                 precache_sound ("announcer/robotic/lastsecond.wav");
1367                 precache_sound ("announcer/robotic/narrowly.wav");
1368         }
1369
1370         precache_model ("models/sprites/1.spr32");
1371         precache_model ("models/sprites/2.spr32");
1372         precache_model ("models/sprites/3.spr32");
1373         precache_model ("models/sprites/4.spr32");
1374         precache_model ("models/sprites/5.spr32");
1375         precache_model ("models/sprites/6.spr32");
1376         precache_model ("models/sprites/7.spr32");
1377         precache_model ("models/sprites/8.spr32");
1378         precache_model ("models/sprites/9.spr32");
1379         precache_model ("models/sprites/10.spr32");
1380         precache_sound ("announcer/robotic/1.wav");
1381         precache_sound ("announcer/robotic/2.wav");
1382         precache_sound ("announcer/robotic/3.wav");
1383         precache_sound ("announcer/robotic/4.wav");
1384         precache_sound ("announcer/robotic/5.wav");
1385         precache_sound ("announcer/robotic/6.wav");
1386         precache_sound ("announcer/robotic/7.wav");
1387         precache_sound ("announcer/robotic/8.wav");
1388         precache_sound ("announcer/robotic/9.wav");
1389         precache_sound ("announcer/robotic/10.wav");
1390
1391         // common weapon precaches
1392         precache_sound ("weapons/weapon_switch.wav");
1393         precache_sound ("weapons/weaponpickup.wav");
1394         if (cvar("g_grappling_hook"))
1395         {
1396                 precache_sound ("weapons/hook_fire.wav"); // hook
1397                 precache_sound ("weapons/hook_impact.wav"); // hook
1398         }
1399
1400         if (cvar("sv_precacheweapons") || g_nixnex)
1401         {
1402                 //precache weapon models/sounds
1403                 local float wep;
1404                 wep = WEP_FIRST;
1405                 while (wep <= WEP_LAST)
1406                 {
1407                         weapon_action(wep, WR_PRECACHE);
1408                         wep = wep + 1;
1409                 }
1410         }
1411
1412 #if 0
1413         // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1414
1415         if (!self.noise && self.music) // quake 3 uses the music field
1416                 self.noise = self.music;
1417
1418         // plays music for the level if there is any
1419         if (self.noise)
1420         {
1421                 precache_sound (self.noise);
1422                 ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1423         }
1424 #endif
1425 }
1426
1427 // sorry, but using \ in macros breaks line numbers
1428 #define WRITESPECTATABLE_MSG_ONE_VARNAME(varname,statement) entity varname; varname = msg_entity; FOR_EACH_REALCLIENT(msg_entity) if(msg_entity == varname || (msg_entity.classname == STR_SPECTATOR && msg_entity.enemy == varname)) statement msg_entity = varname
1429 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1430 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1431
1432 vector ExactTriggerHit_mins;
1433 vector ExactTriggerHit_maxs;
1434 float ExactTriggerHit_Recurse()
1435 {
1436         float s;
1437         entity se;
1438         float f;
1439
1440         tracebox('0 0 0', ExactTriggerHit_mins, ExactTriggerHit_maxs, '0 0 0', MOVE_NORMAL, other);
1441         if not(trace_ent)
1442                 return 0;
1443         if(trace_ent == self)
1444                 return 1;
1445
1446         se = trace_ent;
1447         s = se.solid;
1448         se.solid = SOLID_NOT;
1449         f = ExactTriggerHit_Recurse();
1450         se.solid = s;
1451
1452         return f;
1453 }
1454
1455 float ExactTriggerHit()
1456 {
1457         float f, s;
1458
1459         if not(self.modelindex)
1460                 return 1;
1461
1462         s = self.solid;
1463         self.solid = SOLID_BSP;
1464         ExactTriggerHit_mins = other.absmin;
1465         ExactTriggerHit_maxs = other.absmax;
1466         f = ExactTriggerHit_Recurse();
1467         self.solid = s;
1468
1469         return f;
1470 }
1471
1472 // WARNING: this kills the trace globals
1473 #define EXACTTRIGGER_TOUCH if not(ExactTriggerHit()) return
1474 #define EXACTTRIGGER_INIT  InitSolidBSPTrigger(); self.solid = SOLID_TRIGGER
1475
1476 #define INITPRIO_FIRST              0
1477 #define INITPRIO_GAMETYPE           0
1478 #define INITPRIO_GAMETYPE_FALLBACK  1
1479 #define INITPRIO_CVARS              5
1480 #define INITPRIO_FINDTARGET        10
1481 #define INITPRIO_DROPTOFLOOR       20
1482 #define INITPRIO_SETLOCATION       90
1483 #define INITPRIO_LINKDOORS         91
1484 #define INITPRIO_LAST              99
1485
1486 .void(void) initialize_entity;
1487 .float initialize_entity_order;
1488 .entity initialize_entity_next;
1489 entity initialize_entity_first;
1490
1491 void make_safe_for_remove(entity e)
1492 {
1493         if(e.initialize_entity)
1494         {
1495                 entity ent, prev;
1496                 for(ent = initialize_entity_first; ent; )
1497                 {
1498                         if((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1499                         {
1500                                 print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1501                                 // skip it in linked list
1502                                 if(prev)
1503                                 {
1504                                         prev.initialize_entity_next = ent.initialize_entity_next;
1505                                         ent = prev.initialize_entity_next;
1506                                 }
1507                                 else
1508                                 {
1509                                         initialize_entity_first = ent.initialize_entity_next;
1510                                         ent = initialize_entity_first;
1511                                 }
1512                         }
1513                         else
1514                         {
1515                                 prev = ent;
1516                                 ent = ent.initialize_entity_next;
1517                         }
1518                 }
1519         }
1520 }
1521
1522 void objerror(string s)
1523 {
1524         make_safe_for_remove(self);
1525         objerror_builtin(s);
1526 }
1527
1528 void remove_unsafely(entity e)
1529
1530         remove_builtin(e);
1531 }
1532
1533 void remove_safely(entity e)
1534 {
1535         make_safe_for_remove(e);
1536         remove_builtin(e);
1537 }
1538
1539 void InitializeEntity(entity e, void(void) func, float order)
1540 {
1541         entity prev, cur;
1542
1543         if(!e || e.initialize_entity)
1544         {
1545                 // make a proxy initializer entity
1546                 entity e_old;
1547                 e_old = e;
1548                 e = spawn();
1549                 e.classname = "initialize_entity";
1550                 e.enemy = e_old;
1551         }
1552
1553         e.initialize_entity = func;
1554         e.initialize_entity_order = order;
1555
1556         cur = initialize_entity_first;
1557         for(;;)
1558         {
1559                 if(!cur || cur.initialize_entity_order > order)
1560                 {
1561                         // insert between prev and cur
1562                         if(prev)
1563                                 prev.initialize_entity_next = e;
1564                         else
1565                                 initialize_entity_first = e;
1566                         e.initialize_entity_next = cur;
1567                         return;
1568                 }
1569                 prev = cur;
1570                 cur = cur.initialize_entity_next;
1571         }
1572 }
1573 void InitializeEntitiesRun()
1574 {
1575         entity startoflist;
1576         startoflist = initialize_entity_first;
1577         initialize_entity_first = world;
1578         for(self = startoflist; self; )
1579         {
1580                 entity e;
1581                 var void(void) func;
1582                 e = self.initialize_entity_next;
1583                 func = self.initialize_entity;
1584                 self.initialize_entity_order = 0;
1585                 self.initialize_entity = func_null;
1586                 self.initialize_entity_next = world;
1587                 if(self.classname == "initialize_entity")
1588                 {
1589                         entity e_old;
1590                         e_old = self.enemy;
1591                         remove_builtin(self);
1592                         self = e_old;
1593                 }
1594                 //dprint("Delayed initialization: ", self.classname, "\n");
1595                 func();
1596                 self = e;
1597         }
1598 }
1599
1600 .float uncustomizeentityforclient_set;
1601 .void(void) uncustomizeentityforclient;
1602 void(void) SUB_Nullpointer = #0;
1603 void UncustomizeEntitiesRun()
1604 {
1605         entity oldself;
1606         oldself = self;
1607         for(self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1608                 self.uncustomizeentityforclient();
1609         self = oldself;
1610 }
1611 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1612 {
1613         e.customizeentityforclient = customizer;
1614         e.uncustomizeentityforclient = uncustomizer;
1615         e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1616 }
1617
1618 .float nottargeted;
1619 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1620
1621 void Net_LinkEntity(entity e)
1622 {
1623         setmodel(e, "null");
1624         e.effects = EF_NODEPTHTEST | EF_LOWPRECISION;
1625 }
1626
1627 void adaptor_think2touch()
1628 {
1629         entity o;
1630         o = other;
1631         other = world;
1632         self.touch();
1633         other = o;
1634 }
1635
1636 void adaptor_think2use()
1637 {
1638         entity o, a;
1639         o = other;
1640         a = activator;
1641         activator = world;
1642         other = world;
1643         self.use();
1644         other = o;
1645         activator = a;
1646 }
1647
1648 // deferred dropping
1649 void DropToFloor_Handler()
1650 {
1651         droptofloor_builtin();
1652         self.dropped_origin = self.origin;
1653 }
1654
1655 void droptofloor()
1656 {
1657         InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1658 }
1659
1660
1661
1662 float trace_hits_box_a0, trace_hits_box_a1;
1663
1664 float trace_hits_box_1d(float end, float thmi, float thma)
1665 {
1666         if(end == 0)
1667         {
1668                 // just check if x is in range
1669                 if(0 < thmi)
1670                         return FALSE;
1671                 if(0 > thma)
1672                         return FALSE;
1673         }
1674         else
1675         {
1676                 // do the trace with respect to x
1677                 // 0 -> end has to stay in thmi -> thma
1678                 trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1679                 trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1680                 if(trace_hits_box_a0 > trace_hits_box_a1)
1681                         return FALSE;
1682         }
1683         return TRUE;
1684 }
1685
1686 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1687 {
1688         end -= start;
1689         thmi -= start;
1690         thma -= start;
1691         // now it is a trace from 0 to end
1692
1693         trace_hits_box_a0 = 0;
1694         trace_hits_box_a1 = 1;
1695
1696         if(!trace_hits_box_1d(end_x, thmi_x, thma_x))
1697                 return FALSE;
1698         if(!trace_hits_box_1d(end_y, thmi_y, thma_y))
1699                 return FALSE;
1700         if(!trace_hits_box_1d(end_z, thmi_z, thma_z))
1701                 return FALSE;
1702
1703         return TRUE;
1704 }
1705
1706 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1707 {
1708         return trace_hits_box(start, end, thmi - ma, thma - mi);
1709 }
1710
1711 float SUB_NoImpactCheck()
1712 {
1713         if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1714                 return 1;
1715         if(other == world && self.size != '0 0 0')
1716         {
1717                 vector tic;
1718                 tic = self.velocity * sys_ticrate;
1719                 tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1720                 traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1721                 if(trace_fraction >= 1)
1722                 {
1723                         dprint("Odd... did not hit...?\n");
1724                 }
1725                 else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1726                 {
1727                         dprint("Detected and prevented the sky-grapple bug.\n");
1728                         return 1;
1729                 }
1730         }
1731
1732         return 0;
1733 }
1734
1735 #define SUB_OwnerCheck() (other && (other == self.owner))
1736
1737 #define PROJECTILE_TOUCH do { if(SUB_OwnerCheck()) return; if(SUB_NoImpactCheck()) { remove(self); return; } } while(0)
1738 #define PROJECTILE_TOUCH_NOSOUND do { if(SUB_OwnerCheck()) return; if(SUB_NoImpactCheck()) { stopsound(self, CHAN_PAIN); remove(self); return; } } while(0)
1739
1740 float MAX_IPBAN_URIS = 16;
1741
1742 float URI_GET_DISCARD   = 0;
1743 float URI_GET_IPBAN     = 1;
1744 float URI_GET_IPBAN_END = 16;
1745
1746 void URI_Get_Callback(float id, float status, string data)
1747 {
1748         dprint("Received HTTP request data for id ", ftos(id), "; status is ", ftos(status), "\nData is\n:");
1749         dprint(data);
1750         dprint("\nEnd of data.\n");
1751
1752         if(id == URI_GET_DISCARD)
1753         {
1754                 // discard
1755         }
1756         else if(id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1757         {
1758                 // online ban list
1759                 OnlineBanList_URI_Get_Callback(id, status, data);
1760         }
1761         else
1762         {
1763                 print("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1764         }
1765 }
1766
1767 void print_to(entity e, string s)
1768 {
1769         if(e)
1770                 sprint(e, strcat(s, "\n"));
1771         else
1772                 print(s, "\n");
1773 }
1774
1775 string getrecords()
1776 {
1777         float rec;
1778         string h;
1779         float r;
1780         float i;
1781         string s;
1782
1783         rec = 0;
1784         
1785         s = "";
1786
1787         if(g_ctf)
1788         {
1789                 for(i = 0; i < MapInfo_count; ++i)
1790                 {
1791                         if(MapInfo_Get_ByID(i))
1792                         {
1793                                 r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/time")));
1794                                 if(r == 0)
1795                                         continue;
1796                                 h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/netname"));
1797                                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-6, ftos_decimals(r, 2)), " ", h, "\n");
1798                                 ++rec;
1799                         }
1800                 }
1801         }
1802
1803         if(g_race)
1804         {
1805                 for(i = 0; i < MapInfo_count; ++i)
1806                 {
1807                         if(MapInfo_Get_ByID(i))
1808                         {
1809                                 r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/racerecord/time")));
1810                                 if(r == 0)
1811                                         continue;
1812                                 h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/racerecord/netname"));
1813                                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, mmsss(r)), " ", h, "\n");
1814                                 ++rec;
1815                         }
1816                 }
1817         }
1818
1819         if(s == "")
1820                 return "No records are available on this server.\n";
1821         else
1822                 return strcat("Records on this server:\n", s);
1823 }