]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/miscfunctions.qc
sv_clones party
[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:2\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
553         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
554         if(f > 0)
555         {
556                 if(s == "cl_weaponpriority")
557                         self.switchweapon = w_getbestweapon(self);
558         }
559 }
560
561 float fexists(string f)
562 {
563         float fh;
564         fh = fopen(f, FILE_READ);
565         if(fh < 0)
566                 return FALSE;
567         fclose(fh);
568         return TRUE;
569 }
570
571 void backtrace(string msg)
572 {
573         float dev;
574         dev = cvar("developer");
575         cvar_set("developer", "1");
576         dprint("\n");
577         dprint("--- CUT HERE ---\nWARNING: ");
578         dprint(msg);
579         dprint("\n");
580         remove(world); // isn't there any better way to cause a backtrace?
581         dprint("\n--- CUT UNTIL HERE ---\n");
582         cvar_set("developer", ftos(dev));
583 }
584
585 string Team_ColorCode(float teamid)
586 {
587         if(teamid == COLOR_TEAM1)
588                 return "^1";
589         else if(teamid == COLOR_TEAM2)
590                 return "^4";
591         else if(teamid == COLOR_TEAM3)
592                 return "^3";
593         else if(teamid == COLOR_TEAM4)
594                 return "^6";
595         else
596                 return "^7";
597 }
598 string Team_ColorName(float t)
599 {
600         // fixme: Search for team entities and get their .netname's!
601         if(t == COLOR_TEAM1)
602                 return "Red";
603         if(t == COLOR_TEAM2)
604                 return "Blue";
605         if(t == COLOR_TEAM3)
606                 return "Yellow";
607         if(t == COLOR_TEAM4)
608                 return "Pink";
609         return "Neutral";
610 }
611 string Team_ColorNameLowerCase(float t)
612 {
613         // fixme: Search for team entities and get their .netname's!
614         if(t == COLOR_TEAM1)
615                 return "red";
616         if(t == COLOR_TEAM2)
617                 return "blue";
618         if(t == COLOR_TEAM3)
619                 return "yellow";
620         if(t == COLOR_TEAM4)
621                 return "pink";
622         return "neutral";
623 }
624
625 #define CENTERPRIO_POINT 1
626 #define CENTERPRIO_SPAM 2
627 #define CENTERPRIO_REBALANCE 2
628 #define CENTERPRIO_VOTE 4
629 #define CENTERPRIO_NORMAL 5
630 #define CENTERPRIO_MAPVOTE 9
631 #define CENTERPRIO_IDLEKICK 50
632 #define CENTERPRIO_ADMIN 99
633 .float centerprint_priority;
634 .float centerprint_expires;
635 void centerprint_atprio(entity e, float prio, string s)
636 {
637         if(intermission_running)
638                 if(prio < CENTERPRIO_MAPVOTE)
639                         return;
640         if(time > e.centerprint_expires)
641                 e.centerprint_priority = 0;
642         if(prio >= e.centerprint_priority)
643         {
644                 e.centerprint_priority = prio;
645                 if(timeoutStatus == 2)
646                         e.centerprint_expires = time + (e.cvar_scr_centertime * TIMEOUT_SLOWMO_VALUE);
647                 else
648                         e.centerprint_expires = time + e.cvar_scr_centertime;
649                 centerprint_builtin(e, s);
650         }
651 }
652 void centerprint_expire(entity e, float prio)
653 {
654         if(prio == e.centerprint_priority)
655         {
656                 e.centerprint_priority = 0;
657                 centerprint_builtin(e, "");
658         }
659 }
660 void centerprint(entity e, string s)
661 {
662         centerprint_atprio(e, CENTERPRIO_NORMAL, s);
663 }
664
665 // decolorizes and team colors the player name when needed
666 string playername(entity p)
667 {
668         string t;
669         if(teams_matter && !intermission_running && p.classname == "player")
670         {
671                 t = Team_ColorCode(p.team);
672                 return strcat(t, strdecolorize(p.netname));
673         }
674         else
675                 return p.netname;
676 }
677
678 vector randompos(vector m1, vector m2)
679 {
680         local vector v;
681         m2 = m2 - m1;
682         v_x = m2_x * random() + m1_x;
683         v_y = m2_y * random() + m1_y;
684         v_z = m2_z * random() + m1_z;
685         return  v;
686 };
687
688 // requires that m2>m1 in all coordinates, and that m4>m3
689 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;};
690
691 // requires the same, but is a stronger condition
692 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;};
693
694 float g_pickup_shells;
695 float g_pickup_shells_max;
696 float g_pickup_nails;
697 float g_pickup_nails_max;
698 float g_pickup_rockets;
699 float g_pickup_rockets_max;
700 float g_pickup_cells;
701 float g_pickup_cells_max;
702 float g_pickup_armorsmall;
703 float g_pickup_armorsmall_max;
704 float g_pickup_armormedium;
705 float g_pickup_armormedium_max;
706 float g_pickup_armorlarge;
707 float g_pickup_armorlarge_max;
708 float g_pickup_healthsmall;
709 float g_pickup_healthsmall_max;
710 float g_pickup_healthmedium;
711 float g_pickup_healthmedium_max;
712 float g_pickup_healthlarge;
713 float g_pickup_healthlarge_max;
714 float g_pickup_healthmega;
715 float g_pickup_healthmega_max;
716 float g_weaponarena;
717 string g_weaponarena_list;
718
719 float start_weapons;
720 float start_items;
721 float start_ammo_shells;
722 float start_ammo_nails;
723 float start_ammo_rockets;
724 float start_ammo_cells;
725 float start_health;
726 float start_armorvalue;
727 float warmup_start_weapons;
728 float warmup_start_ammo_shells;
729 float warmup_start_ammo_nails;
730 float warmup_start_ammo_rockets;
731 float warmup_start_ammo_cells;
732 float warmup_start_health;
733 float warmup_start_armorvalue;
734
735 entity get_weaponinfo(float w);
736
737 void readplayerstartcvars()
738 {
739         entity e;
740         float i, j, t;
741         string s;
742
743         // initialize starting values for players
744         start_weapons = 0;
745         start_items = 0;
746         start_ammo_shells = 0;
747         start_ammo_nails = 0;
748         start_ammo_rockets = 0;
749         start_ammo_cells = 0;
750         start_health = cvar("g_balance_health_start");
751         start_armorvalue = cvar("g_balance_armor_start");
752
753         g_weaponarena = 0;
754         s = cvar_string("g_weaponarena");
755         if(s != "0")
756         {
757                 t = tokenize_sane(s);
758                 g_weaponarena_list = "";
759                 for(i = 0; i < t; ++i)
760                 {
761                         s = argv(i);
762                         for(j = WEP_FIRST; j <= WEP_LAST; ++j)
763                         {
764                                 e = get_weaponinfo(j);
765                                 if(e.netname == s)
766                                 {
767                                         g_weaponarena |= e.weapons;
768                                         weapon_action(e.weapon, WR_PRECACHE);
769                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
770                                         break;
771                                 }
772                         }
773                         if(j > WEP_LAST)
774                         {
775                                 print("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
776                         }
777                 }
778                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
779         }
780
781         if(g_weaponarena)
782         {
783                 start_weapons = g_weaponarena;
784                 start_ammo_rockets = 999;
785                 start_ammo_shells = 999;
786                 start_ammo_cells = 999;
787                 start_ammo_nails = 999;
788                 start_items |= IT_UNLIMITED_AMMO;
789         }
790         else if(g_nixnex)
791         {
792                 start_weapons = 0;
793                 // will be done later
794                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
795                 {
796                         e = get_weaponinfo(i);
797                         if(!(e.weapon))
798                                 continue;
799                         weapon_action(e.weapon, WR_PRECACHE);
800                 }
801         }
802         else if(g_minstagib)
803         {
804                 start_health = 100;
805                 start_armorvalue = 0;
806                 start_weapons = WEPBIT_MINSTANEX;
807                 weapon_action(WEP_MINSTANEX, WR_PRECACHE);
808                 start_ammo_cells = cvar("g_minstagib_ammo_start");
809                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
810         }
811         else
812         {
813                 if(g_lms)
814                 {
815                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
816                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
817                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
818                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
819                         start_health = cvar("g_lms_start_health");
820                         start_armorvalue = cvar("g_lms_start_armor");
821                 } else if (cvar("g_use_ammunition")) {
822                         start_ammo_shells = cvar("g_start_ammo_shells");
823                         start_ammo_nails = cvar("g_start_ammo_nails");
824                         start_ammo_rockets = cvar("g_start_ammo_rockets");
825                         start_ammo_cells = cvar("g_start_ammo_cells");
826                 } else {
827                         start_ammo_shells = cvar("g_pickup_shells_max");
828                         start_ammo_nails = cvar("g_pickup_nails_max");
829                         start_ammo_rockets = cvar("g_pickup_rockets_max");
830                         start_ammo_cells = cvar("g_pickup_cells_max");
831                         start_items |= IT_UNLIMITED_AMMO;
832                 }
833
834                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
835                 {
836                         e = get_weaponinfo(i);
837                         if(!(e.weapon))
838                                 continue;
839                         if(((e.spawnflags & 1) && g_lms) || cvar(strcat("g_start_weapon_", e.netname)))
840                         {
841                                 start_weapons |= e.weapons;
842                                 weapon_action(e.weapon, WR_PRECACHE);
843                         }
844                 }
845         }
846
847         if(inWarmupStage)
848         {
849                 warmup_start_ammo_shells = start_ammo_shells;
850                 warmup_start_ammo_nails = start_ammo_nails;
851                 warmup_start_ammo_rockets = start_ammo_rockets;
852                 warmup_start_ammo_cells = start_ammo_cells;
853                 warmup_start_health = start_health;
854                 warmup_start_armorvalue = start_armorvalue;
855                 warmup_start_weapons = start_weapons;
856
857                 if(!g_weaponarena && !g_nixnex && !g_minstagib)
858                 {
859                         if(cvar("g_use_ammunition"))
860                         {
861                                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
862                                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
863                                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
864                                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
865                         }
866                         warmup_start_health = cvar("g_warmup_start_health");
867                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
868                         if(cvar("g_warmup_allguns"))
869                         {
870                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
871                                 {
872                                         e = get_weaponinfo(i);
873                                         if(!(e.weapon))
874                                                 continue;
875                                         if(e.spawnflags & 1)
876                                         {
877                                                 warmup_start_weapons |= e.weapons;
878                                                 weapon_action(e.weapon, WR_PRECACHE);
879                                         }
880                                 }
881                         }
882                 }
883         }
884
885         if(g_grappling_hook) // offhand hook
886         {
887                 start_weapons (-) WEPBIT_HOOK;
888                 warmup_start_weapons (-) WEPBIT_HOOK;
889         }
890 }
891
892 void readlevelcvars(void)
893 {
894         sv_clones = cvar("sv_clones");
895         sv_cheats = cvar("sv_cheats");
896         sv_gentle = cvar("sv_gentle");
897         sv_foginterval = cvar("sv_foginterval");
898         g_cloaked = cvar("g_cloaked");
899         g_jump_grunt = cvar("g_jump_grunt");
900         g_footsteps = cvar("g_footsteps");
901         g_grappling_hook = cvar("g_grappling_hook");
902         g_laserguided_missile = cvar("g_laserguided_missile");
903         g_midair = cvar("g_midair");
904         g_minstagib = cvar("g_minstagib");
905         g_nixnex = cvar("g_nixnex");
906         g_nixnex_with_laser = cvar("g_nixnex_with_laser");
907         g_norecoil = cvar("g_norecoil");
908         g_vampire = cvar("g_vampire");
909         sv_maxidle = cvar("sv_maxidle");
910         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
911         sv_pogostick = cvar("sv_pogostick");
912         sv_doublejump = cvar("sv_doublejump");
913         g_maplist_allow_hidden = cvar("g_maplist_allow_hidden");
914         g_ctf_reverse = cvar("g_ctf_reverse");
915
916         inWarmupStage = cvar("g_warmup");
917         g_warmup_limit = cvar("g_warmup_limit");
918         g_warmup_allguns = cvar("g_warmup_allguns");
919         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
920
921         if(g_race && g_race_qualifying == 2 || g_arena || g_assault || cvar("g_campaign"))
922                 inWarmupStage = 0; // these modes cannot work together, sorry
923
924         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
925         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
926         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
927         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
928
929         if(g_minstagib) g_nixnex = g_weaponarena = 0;
930         if(g_nixnex) g_weaponarena = 0;
931         g_weaponarena = 0;
932
933         g_pickup_shells                    = cvar("g_pickup_shells");
934         g_pickup_shells_max                = cvar("g_pickup_shells_max");
935         g_pickup_nails                     = cvar("g_pickup_nails");
936         g_pickup_nails_max                 = cvar("g_pickup_nails_max");
937         g_pickup_rockets                   = cvar("g_pickup_rockets");
938         g_pickup_rockets_max               = cvar("g_pickup_rockets_max");
939         g_pickup_cells                     = cvar("g_pickup_cells");
940         g_pickup_cells_max                 = cvar("g_pickup_cells_max");
941         g_pickup_armorsmall                = cvar("g_pickup_armorsmall");
942         g_pickup_armorsmall_max            = cvar("g_pickup_armorsmall_max");
943         g_pickup_armormedium               = cvar("g_pickup_armormedium");
944         g_pickup_armormedium_max           = cvar("g_pickup_armormedium_max");
945         g_pickup_armorlarge                = cvar("g_pickup_armorlarge");
946         g_pickup_armorlarge_max            = cvar("g_pickup_armorlarge_max");
947         g_pickup_healthsmall               = cvar("g_pickup_healthsmall");
948         g_pickup_healthsmall_max           = cvar("g_pickup_healthsmall_max");
949         g_pickup_healthmedium              = cvar("g_pickup_healthmedium");
950         g_pickup_healthmedium_max          = cvar("g_pickup_healthmedium_max");
951         g_pickup_healthlarge               = cvar("g_pickup_healthlarge");
952         g_pickup_healthlarge_max           = cvar("g_pickup_healthlarge_max");
953         g_pickup_healthmega                = cvar("g_pickup_healthmega");
954         g_pickup_healthmega_max            = cvar("g_pickup_healthmega_max");
955
956         if not(inWarmupStage)
957         {
958                 game_starttime                 = cvar("g_start_delay");
959                 if(game_starttime)
960                 {
961                         restartAnnouncer = spawn();
962                         restartAnnouncer.think = restartAnnouncer_Think;
963                         restartAnnouncer.nextthink = time + 0.1;
964                         restartAnnouncer.spawnflags = 0;
965                 }
966         }
967
968         readplayerstartcvars();
969 }
970
971 /*
972 // TODO sound pack system
973 string soundpack;
974
975 string precache_sound_builtin (string s) = #19;
976 void(entity e, float chan, string samp, float vol, float atten) sound_builtin = #8;
977 string precache_sound(string s)
978 {
979         return precache_sound_builtin(strcat(soundpack, s));
980 }
981 void play2(entity e, string filename)
982 {
983         stuffcmd(e, strcat("play2 ", soundpack, filename, "\n"));
984 }
985 void sound(entity e, float chan, string samp, float vol, float atten)
986 {
987         sound_builtin(e, chan, strcat(soundpack, samp), vol, atten);
988 }
989 */
990
991 // Sound functions
992 string precache_sound (string s) = #19;
993 void(entity e, float chan, string samp, float vol, float atten) sound = #8;
994 float precache_sound_index (string s) = #19;
995
996 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
997 {
998         WriteByte(dest, 6);
999         WriteByte(dest, 27); // all bits except SND_LOOPING
1000         WriteByte(dest, vol * 255);
1001         WriteByte(dest, atten * 64);
1002         WriteEntity(dest, e);
1003         WriteByte(dest, chan);
1004         WriteShort(dest, precache_sound_index(samp));
1005         WriteCoord(dest, o_x);
1006         WriteCoord(dest, o_y);
1007         WriteCoord(dest, o_z);
1008 }
1009 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1010 {
1011         vector o;
1012         o = e.origin + 0.5 * (e.mins + e.maxs);
1013         soundtoat(dest, e, o, chan, samp, vol, atten);
1014 }
1015 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1016 {
1017         soundtoat(MSG_BROADCAST, e, o, chan, samp, vol, atten);
1018 }
1019
1020 void play2(entity e, string filename)
1021 {
1022         //stuffcmd(e, strcat("play2 ", filename, "\n"));
1023         msg_entity = e;
1024         soundtoat(MSG_ONE, world, '0 0 0', CHAN_AUTO, filename, VOL_BASE, ATTN_NONE);
1025 }
1026
1027 .float announcetime;
1028 float announce(entity player, string msg)
1029 {
1030         if(time > player.announcetime)
1031         if(clienttype(player) == CLIENTTYPE_REAL)
1032         {
1033                 player.announcetime = time + 0.3;
1034                 play2(player, msg);
1035                 return TRUE;
1036         }
1037         return FALSE;
1038 }
1039
1040 void play2team(float t, string filename)
1041 {
1042         local entity head;
1043         FOR_EACH_REALPLAYER(head)
1044         {
1045                 if (head.team == t)
1046                         play2(head, filename);
1047         }
1048 }
1049
1050 void play2all(string samp)
1051 {
1052         sound(world, CHAN_AUTO, samp, VOL_BASE, ATTN_NONE);
1053 }
1054
1055 void PrecachePlayerSounds(string f);
1056 void precache_all_models(string pattern)
1057 {
1058         float globhandle, i, n;
1059         string f;
1060
1061         globhandle = search_begin(pattern, TRUE, FALSE);
1062         if(globhandle < 0)
1063                 return;
1064         n = search_getsize(globhandle);
1065         for(i = 0; i < n; ++i)
1066         {
1067                 //print(search_getfilename(globhandle, i), "\n");
1068                 f = search_getfilename(globhandle, i);
1069                 precache_model(f);
1070                 PrecachePlayerSounds(strcat(f, ".sounds"));
1071         }
1072         search_end(globhandle);
1073 }
1074
1075 void precache()
1076 {
1077         // gamemode related things
1078         precache_model ("models/misc/chatbubble.spr");
1079         precache_model ("models/misc/teambubble.spr");
1080         if (g_runematch)
1081         {
1082                 precache_model ("models/runematch/curse.mdl");
1083                 precache_model ("models/runematch/rune.mdl");
1084         }
1085
1086 #ifdef TTURRETS_ENABLED
1087     if(cvar("g_turrets"))
1088         turrets_precash();
1089 #endif
1090
1091         // Precache all player models if desired
1092         if (cvar("sv_precacheplayermodels"))
1093         {
1094                 PrecachePlayerSounds("sound/player/default.sounds");
1095                 precache_all_models("models/player/*.zym");
1096                 precache_all_models("models/player/*.dpm");
1097                 precache_all_models("models/player/*.md3");
1098                 precache_all_models("models/player/*.psk");
1099                 //precache_model("models/player/carni.zym");
1100                 //precache_model("models/player/crash.zym");
1101                 //precache_model("models/player/grunt.zym");
1102                 //precache_model("models/player/headhunter.zym");
1103                 //precache_model("models/player/insurrectionist.zym");
1104                 //precache_model("models/player/jeandarc.zym");
1105                 //precache_model("models/player/lurk.zym");
1106                 //precache_model("models/player/lycanthrope.zym");
1107                 //precache_model("models/player/marine.zym");
1108                 //precache_model("models/player/nexus.zym");
1109                 //precache_model("models/player/pyria.zym");
1110                 //precache_model("models/player/shock.zym");
1111                 //precache_model("models/player/skadi.zym");
1112                 //precache_model("models/player/specop.zym");
1113                 //precache_model("models/player/visitant.zym");
1114         }
1115
1116         if (g_footsteps)
1117         {
1118                 PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1119                 PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1120         }
1121
1122         // gore and miscellaneous sounds
1123         //precache_sound ("misc/h2ohit.wav");
1124         precache_model ("models/gibs/bloodyskull.md3");
1125         precache_model ("models/gibs/chunk.mdl");
1126         precache_model ("models/gibs/eye.md3");
1127         precache_model ("models/gibs/gib1.md3");
1128         precache_model ("models/gibs/gib2.md3");
1129         precache_model ("models/gibs/gib3.md3");
1130         precache_model ("models/gibs/gib4.md3");
1131         precache_model ("models/gibs/gib5.md3");
1132         precache_model ("models/gibs/gib6.md3");
1133         precache_model ("models/gibs/smallchest.md3");
1134         precache_model ("models/gibs/chest.md3");
1135         precache_model ("models/gibs/arm.md3");
1136         precache_model ("models/gibs/leg1.md3");
1137         precache_model ("models/gibs/leg2.md3");
1138         precache_model ("models/hook.md3");
1139         precache_sound ("misc/armorimpact.wav");
1140         precache_sound ("misc/bodyimpact1.wav");
1141         precache_sound ("misc/bodyimpact2.wav");
1142         precache_sound ("misc/gib.wav");
1143         precache_sound ("misc/gib_splat01.wav");
1144         precache_sound ("misc/gib_splat02.wav");
1145         precache_sound ("misc/gib_splat03.wav");
1146         precache_sound ("misc/gib_splat04.wav");
1147         precache_sound ("misc/hit.wav");
1148         PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1149         PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1150         precache_sound ("misc/null.wav");
1151         precache_sound ("misc/spawn.wav");
1152         precache_sound ("misc/talk.wav");
1153         precache_sound ("misc/teleport.wav");
1154         precache_sound ("player/lava.wav");
1155         precache_sound ("player/slime.wav");
1156
1157         // announcer sounds - male
1158         precache_sound ("announcer/male/electrobitch.wav");
1159         precache_sound ("announcer/male/airshot.wav");
1160         precache_sound ("announcer/male/03kills.wav");
1161         precache_sound ("announcer/male/05kills.wav");
1162         precache_sound ("announcer/male/10kills.wav");
1163         precache_sound ("announcer/male/15kills.wav");
1164         precache_sound ("announcer/male/20kills.wav");
1165         precache_sound ("announcer/male/25kills.wav");
1166         precache_sound ("announcer/male/30kills.wav");
1167         precache_sound ("announcer/male/botlike.wav");
1168         precache_sound ("announcer/male/yoda.ogg");
1169         precache_sound ("announcer/male/headshot.ogg");
1170         precache_sound ("announcer/male/impressive.ogg");
1171
1172         // announcer sounds - robotic
1173         precache_sound ("announcer/robotic/prepareforbattle.wav");
1174         precache_sound ("announcer/robotic/begin.wav");
1175         precache_sound ("announcer/robotic/timeoutcalled.wav");
1176         precache_sound ("announcer/robotic/1fragleft.wav");
1177         precache_sound ("announcer/robotic/1minuteremains.wav");
1178         precache_sound ("announcer/robotic/2fragsleft.wav");
1179         precache_sound ("announcer/robotic/3fragsleft.wav");
1180         if (g_minstagib)
1181         {
1182                 precache_sound ("announcer/robotic/lastsecond.wav");
1183                 precache_sound ("announcer/robotic/narrowly.wav");
1184         }
1185
1186         precache_model ("models/sprites/1.spr32");
1187         precache_model ("models/sprites/2.spr32");
1188         precache_model ("models/sprites/3.spr32");
1189         precache_model ("models/sprites/4.spr32");
1190         precache_model ("models/sprites/5.spr32");
1191         precache_model ("models/sprites/6.spr32");
1192         precache_model ("models/sprites/7.spr32");
1193         precache_model ("models/sprites/8.spr32");
1194         precache_model ("models/sprites/9.spr32");
1195         precache_model ("models/sprites/10.spr32");
1196         precache_sound ("announcer/robotic/1.ogg");
1197         precache_sound ("announcer/robotic/2.ogg");
1198         precache_sound ("announcer/robotic/3.ogg");
1199         precache_sound ("announcer/robotic/4.ogg");
1200         precache_sound ("announcer/robotic/5.ogg");
1201         precache_sound ("announcer/robotic/6.ogg");
1202         precache_sound ("announcer/robotic/7.ogg");
1203         precache_sound ("announcer/robotic/8.ogg");
1204         precache_sound ("announcer/robotic/9.ogg");
1205         precache_sound ("announcer/robotic/10.ogg");
1206
1207         // common weapon precaches
1208         precache_sound ("weapons/weapon_switch.wav");
1209         precache_sound ("weapons/weaponpickup.wav");
1210         if (cvar("g_grappling_hook"))
1211         {
1212                 precache_sound ("weapons/hook_fire.wav"); // hook
1213                 precache_sound ("weapons/hook_impact.wav"); // hook
1214         }
1215
1216         if (cvar("sv_precacheweapons") || g_nixnex)
1217         {
1218                 //precache weapon models/sounds
1219                 local float wep;
1220                 wep = WEP_FIRST;
1221                 while (wep <= WEP_LAST)
1222                 {
1223                         weapon_action(wep, WR_PRECACHE);
1224                         wep = wep + 1;
1225                 }
1226         }
1227
1228         // plays music for the level if there is any
1229         if (self.noise)
1230         {
1231                 precache_sound (self.noise);
1232                 ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1233         }
1234 }
1235
1236 // sorry, but using \ in macros breaks line numbers
1237 #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
1238 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1239 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1240
1241 vector ExactTriggerHit_mins;
1242 vector ExactTriggerHit_maxs;
1243 float ExactTriggerHit_Recurse()
1244 {
1245         float s;
1246         entity se;
1247         float f;
1248
1249         tracebox('0 0 0', ExactTriggerHit_mins, ExactTriggerHit_maxs, '0 0 0', MOVE_NORMAL, other);
1250         if not(trace_ent)
1251                 return 0;
1252         if(trace_ent == self)
1253                 return 1;
1254
1255         se = trace_ent;
1256         s = se.solid;
1257         se.solid = SOLID_NOT;
1258         f = ExactTriggerHit_Recurse();
1259         se.solid = s;
1260
1261         return f;
1262 }
1263
1264 float ExactTriggerHit()
1265 {
1266         float f, s;
1267
1268         if not(self.modelindex)
1269                 return 1;
1270
1271         s = self.solid;
1272         self.solid = SOLID_BSP;
1273         ExactTriggerHit_mins = other.absmin;
1274         ExactTriggerHit_maxs = other.absmax;
1275         f = ExactTriggerHit_Recurse();
1276         self.solid = s;
1277
1278         return f;
1279 }
1280
1281 // WARNING: this kills the trace globals
1282 #define EXACTTRIGGER_TOUCH if not(ExactTriggerHit()) return
1283 #define EXACTTRIGGER_INIT  InitSolidBSPTrigger(); self.solid = SOLID_TRIGGER
1284
1285 #define INITPRIO_FIRST              0
1286 #define INITPRIO_GAMETYPE           0
1287 #define INITPRIO_GAMETYPE_FALLBACK  1
1288 #define INITPRIO_CVARS              5
1289 #define INITPRIO_FINDTARGET        10
1290 #define INITPRIO_DROPTOFLOOR       20
1291 #define INITPRIO_SETLOCATION       90
1292 #define INITPRIO_LINKDOORS         91
1293 #define INITPRIO_LAST              99
1294
1295 .void(void) initialize_entity;
1296 .float initialize_entity_order;
1297 .entity initialize_entity_next;
1298 entity initialize_entity_first;
1299
1300 void make_safe_for_remove(entity e)
1301 {
1302         if(e.initialize_entity)
1303         {
1304                 entity ent, prev;
1305                 for(ent = initialize_entity_first; ent; )
1306                 {
1307                         if((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1308                         {
1309                                 print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1310                                 // skip it in linked list
1311                                 if(prev)
1312                                 {
1313                                         prev.initialize_entity_next = ent.initialize_entity_next;
1314                                         ent = prev.initialize_entity_next;
1315                                 }
1316                                 else
1317                                 {
1318                                         initialize_entity_first = ent.initialize_entity_next;
1319                                         ent = initialize_entity_first;
1320                                 }
1321                         }
1322                         else
1323                         {
1324                                 prev = ent;
1325                                 ent = ent.initialize_entity_next;
1326                         }
1327                 }
1328         }
1329 }
1330
1331 void objerror(string s)
1332 {
1333         make_safe_for_remove(self);
1334         objerror_builtin(s);
1335 }
1336
1337 void remove_unsafely(entity e)
1338
1339         remove_builtin(e);
1340 }
1341
1342 void remove_safely(entity e)
1343 {
1344         make_safe_for_remove(e);
1345         remove_builtin(e);
1346 }
1347
1348 void InitializeEntity(entity e, void(void) func, float order)
1349 {
1350         entity prev, cur;
1351
1352         if(!e || e.initialize_entity)
1353         {
1354                 // make a proxy initializer entity
1355                 entity e_old;
1356                 e_old = e;
1357                 e = spawn();
1358                 e.classname = "initialize_entity";
1359                 e.enemy = e_old;
1360         }
1361
1362         e.initialize_entity = func;
1363         e.initialize_entity_order = order;
1364
1365         cur = initialize_entity_first;
1366         for(;;)
1367         {
1368                 if(!cur || cur.initialize_entity_order > order)
1369                 {
1370                         // insert between prev and cur
1371                         if(prev)
1372                                 prev.initialize_entity_next = e;
1373                         else
1374                                 initialize_entity_first = e;
1375                         e.initialize_entity_next = cur;
1376                         return;
1377                 }
1378                 prev = cur;
1379                 cur = cur.initialize_entity_next;
1380         }
1381 }
1382 void InitializeEntitiesRun()
1383 {
1384         entity startoflist;
1385         startoflist = initialize_entity_first;
1386         initialize_entity_first = world;
1387         for(self = startoflist; self; )
1388         {
1389                 entity e;
1390                 var void(void) func;
1391                 e = self.initialize_entity_next;
1392                 func = self.initialize_entity;
1393                 self.initialize_entity_order = 0;
1394                 self.initialize_entity = func_null;
1395                 self.initialize_entity_next = world;
1396                 if(self.classname == "initialize_entity")
1397                 {
1398                         entity e_old;
1399                         e_old = self.enemy;
1400                         remove_builtin(self);
1401                         self = e_old;
1402                 }
1403                 dprint("Delayed initialization: ", self.classname, "\n");
1404                 func();
1405                 self = e;
1406         }
1407 }
1408
1409 .float uncustomizeentityforclient_set;
1410 .void(void) uncustomizeentityforclient;
1411 void(void) SUB_Nullpointer = #0;
1412 void UncustomizeEntitiesRun()
1413 {
1414         entity oldself;
1415         oldself = self;
1416         for(self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1417                 self.uncustomizeentityforclient();
1418         self = oldself;
1419 }
1420 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1421 {
1422         e.customizeentityforclient = customizer;
1423         e.uncustomizeentityforclient = uncustomizer;
1424         e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1425 }
1426
1427 .float nottargeted;
1428 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1429
1430 float power2of(float e)
1431 {
1432         return pow(2, e);
1433 }
1434 float log2of(float x)
1435 {
1436         // NOTE: generated code
1437         if(x > 2048)
1438                 if(x > 131072)
1439                         if(x > 1048576)
1440                                 if(x > 4194304)
1441                                         return 23;
1442                                 else
1443                                         if(x > 2097152)
1444                                                 return 22;
1445                                         else
1446                                                 return 21;
1447                         else
1448                                 if(x > 524288)
1449                                         return 20;
1450                                 else
1451                                         if(x > 262144)
1452                                                 return 19;
1453                                         else
1454                                                 return 18;
1455                 else
1456                         if(x > 16384)
1457                                 if(x > 65536)
1458                                         return 17;
1459                                 else
1460                                         if(x > 32768)
1461                                                 return 16;
1462                                         else
1463                                                 return 15;
1464                         else
1465                                 if(x > 8192)
1466                                         return 14;
1467                                 else
1468                                         if(x > 4096)
1469                                                 return 13;
1470                                         else
1471                                                 return 12;
1472         else
1473                 if(x > 32)
1474                         if(x > 256)
1475                                 if(x > 1024)
1476                                         return 11;
1477                                 else
1478                                         if(x > 512)
1479                                                 return 10;
1480                                         else
1481                                                 return 9;
1482                         else
1483                                 if(x > 128)
1484                                         return 8;
1485                                 else
1486                                         if(x > 64)
1487                                                 return 7;
1488                                         else
1489                                                 return 6;
1490                 else
1491                         if(x > 4)
1492                                 if(x > 16)
1493                                         return 5;
1494                                 else
1495                                         if(x > 8)
1496                                                 return 4;
1497                                         else
1498                                                 return 3;
1499                         else
1500                                 if(x > 2)
1501                                         return 2;
1502                                 else
1503                                         if(x > 1)
1504                                                 return 1;
1505                                         else
1506                                                 return 0;
1507 }
1508
1509 void Net_LinkEntity(entity e)
1510 {
1511         e.model = "net_entity";
1512         e.modelindex = 1;
1513         e.effects = EF_NODEPTHTEST | EF_LOWPRECISION;
1514 }
1515
1516 void adaptor_think2touch()
1517 {
1518         entity o;
1519         o = other;
1520         other = world;
1521         self.touch();
1522         other = o;
1523 }
1524
1525 void adaptor_think2use()
1526 {
1527         entity o, a;
1528         o = other;
1529         a = activator;
1530         activator = world;
1531         other = world;
1532         self.use();
1533         other = o;
1534         activator = a;
1535 }
1536
1537 // deferred dropping
1538 void DropToFloor_Handler()
1539 {
1540         droptofloor_builtin();
1541         self.dropped_origin = self.origin;
1542 }
1543
1544 void droptofloor()
1545 {
1546         InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1547 }
1548
1549
1550
1551 float trace_hits_box_a0, trace_hits_box_a1;
1552
1553 float trace_hits_box_1d(float end, float thmi, float thma)
1554 {
1555         if(end == 0)
1556         {
1557                 // just check if x is in range
1558                 if(0 < thmi)
1559                         return FALSE;
1560                 if(0 > thma)
1561                         return FALSE;
1562         }
1563         else
1564         {
1565                 // do the trace with respect to x
1566                 // 0 -> end has to stay in thmi -> thma
1567                 trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1568                 trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1569                 if(trace_hits_box_a0 > trace_hits_box_a1)
1570                         return FALSE;
1571         }
1572         return TRUE;
1573 }
1574
1575 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1576 {
1577         end -= start;
1578         thmi -= start;
1579         thma -= start;
1580         // now it is a trace from 0 to end
1581
1582         trace_hits_box_a0 = 0;
1583         trace_hits_box_a1 = 1;
1584
1585         if(!trace_hits_box_1d(end_x, thmi_x, thma_x))
1586                 return FALSE;
1587         if(!trace_hits_box_1d(end_y, thmi_y, thma_y))
1588                 return FALSE;
1589         if(!trace_hits_box_1d(end_z, thmi_z, thma_z))
1590                 return FALSE;
1591
1592         return TRUE;
1593 }
1594
1595 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1596 {
1597         return trace_hits_box(start, end, thmi - ma, thma - mi);
1598 }
1599
1600 float SUB_NoImpactCheck()
1601 {
1602         if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1603                 return 1;
1604         if(other == world && self.size != '0 0 0')
1605         {
1606                 vector tic;
1607                 tic = self.velocity * sys_ticrate;
1608                 tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1609                 traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1610                 if(trace_fraction >= 1)
1611                 {
1612                         dprint("Odd... did not hit...?\n");
1613                 }
1614                 else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1615                 {
1616                         dprint("Detected and prevented the sky-grapple bug.\n");
1617                         return 1;
1618                 }
1619         }
1620
1621         return 0;
1622 }
1623
1624 #define SUB_OwnerCheck() (other && (other == self.owner))
1625
1626 #define PROJECTILE_TOUCH do { if(SUB_OwnerCheck()) return; if(SUB_NoImpactCheck()) { remove(self); return; } } while(0)
1627 const string STR_MISC_NULL_WAV = "misc/null.wav";
1628 #define PROJECTILE_TOUCH_NOSOUND do { if(SUB_OwnerCheck()) return; if(SUB_NoImpactCheck()) { sound (self, CHAN_PROJECTILE, STR_MISC_NULL_WAV, VOL_BASE, ATTN_NORM); remove(self); return; } } while(0)