]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
jetpack: move sound to client
[xonotic/xonotic-data.pk3dir.git] / 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 traceline_antilag (entity source, vector v1, vector v2, float nomonst, entity forent, float lag);
7 void crosshair_trace(entity pl)
8 {
9         traceline_antilag(pl, pl.cursor_trace_start, pl.cursor_trace_start + normalize(pl.cursor_trace_endpos - pl.cursor_trace_start) * MAX_SHOT_DISTANCE, MOVE_NORMAL, pl, ANTILAG_LATENCY(pl));
10 }
11 void crosshair_trace_plusvisibletriggers(entity pl)
12 {
13         entity first;
14         entity e;
15         first = findchainfloat(solid, SOLID_TRIGGER);
16
17         for (e = first; e; e = e.chain)
18                 if (e.model != "")
19                         e.solid = SOLID_BSP;
20
21         crosshair_trace(pl);
22
23         for (e = first; e; e = e.chain)
24                 e.solid = SOLID_TRIGGER;
25 }
26 void WarpZone_traceline_antilag (entity source, vector v1, vector v2, float nomonst, entity forent, float lag);
27 void WarpZone_crosshair_trace(entity pl)
28 {
29         WarpZone_traceline_antilag(pl, pl.cursor_trace_start, pl.cursor_trace_start + normalize(pl.cursor_trace_endpos - pl.cursor_trace_start) * MAX_SHOT_DISTANCE, MOVE_NORMAL, pl, ANTILAG_LATENCY(pl));
30 }
31
32 void() spawnfunc_info_player_deathmatch; // needed for the other spawnpoints
33 void() spawnpoint_use;
34 string GetMapname();
35 string ColoredTeamName(float t);
36
37 string admin_name(void)
38 {
39         if(autocvar_sv_adminnick != "")
40                 return autocvar_sv_adminnick;
41         else
42                 return "SERVER ADMIN";
43 }
44
45 float DistributeEvenly_amount;
46 float DistributeEvenly_totalweight;
47 void DistributeEvenly_Init(float amount, float totalweight)
48 {
49     if (DistributeEvenly_amount)
50     {
51         dprint("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
52         dprint(ftos(DistributeEvenly_totalweight), " left!)\n");
53     }
54     if (totalweight == 0)
55         DistributeEvenly_amount = 0;
56     else
57         DistributeEvenly_amount = amount;
58     DistributeEvenly_totalweight = totalweight;
59 }
60 float DistributeEvenly_Get(float weight)
61 {
62     float f;
63     if (weight <= 0)
64         return 0;
65     f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
66     DistributeEvenly_totalweight -= weight;
67     DistributeEvenly_amount -= f;
68     return f;
69 }
70 float DistributeEvenly_GetRandomized(float weight)
71 {
72     float f;
73     if (weight <= 0)
74         return 0;
75     f = floor(random() + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
76     DistributeEvenly_totalweight -= weight;
77     DistributeEvenly_amount -= f;
78     return f;
79 }
80
81 #define move_out_of_solid(e) WarpZoneLib_MoveOutOfSolid(e)
82
83
84 string STR_PLAYER = "player";
85 string STR_SPECTATOR = "spectator";
86 string STR_OBSERVER = "observer";
87
88 #if 0
89 #define FOR_EACH_CLIENT(v) for(v = world; (v = findflags(v, flags, FL_CLIENT)) != world; )
90 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
91 #define FOR_EACH_PLAYER(v) for(v = world; (v = find(v, classname, STR_PLAYER)) != world; )
92 #define FOR_EACH_REALPLAYER(v) FOR_EACH_PLAYER(v) if(clienttype(v) == CLIENTTYPE_REAL)
93 #else
94 #define FOR_EACH_CLIENTSLOT(v) for(v = world; (v = nextent(v)) && (num_for_edict(v) <= maxclients); )
95 #define FOR_EACH_CLIENT(v) FOR_EACH_CLIENTSLOT(v) if(v.flags & FL_CLIENT)
96 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
97 #define FOR_EACH_PLAYER(v) FOR_EACH_CLIENT(v) if(v.classname == STR_PLAYER)
98 #define FOR_EACH_SPEC(v) FOR_EACH_CLIENT(v) if(v.classname != STR_PLAYER)
99 #define FOR_EACH_REALPLAYER(v) FOR_EACH_REALCLIENT(v) if(v.classname == STR_PLAYER)
100 #endif
101
102 #define CENTER_OR_VIEWOFS(ent) (ent.origin + ((ent.classname == STR_PLAYER) ? ent.view_ofs : ((ent.mins + ent.maxs) * 0.5)))
103
104 // copies a string to a tempstring (so one can strunzone it)
105 string strcat1(string s) = #115; // FRIK_FILE
106
107 float logfile_open;
108 float logfile;
109
110 void bcenterprint(string s)
111 {
112     // TODO replace by MSG_ALL (would show it to spectators too, though)?
113     entity head;
114     FOR_EACH_PLAYER(head)
115     if (clienttype(head) == CLIENTTYPE_REAL)
116         centerprint(head, s);
117 }
118
119 void GameLogEcho(string s)
120 {
121     string fn;
122     float matches;
123
124     if (autocvar_sv_eventlog_files)
125     {
126         if (!logfile_open)
127         {
128             logfile_open = TRUE;
129             matches = autocvar_sv_eventlog_files_counter + 1;
130             cvar_set("sv_eventlog_files_counter", ftos(matches));
131             fn = ftos(matches);
132             if (strlen(fn) < 8)
133                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
134             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
135             logfile = fopen(fn, FILE_APPEND);
136             fputs(logfile, ":logversion:3\n");
137         }
138         if (logfile >= 0)
139         {
140             if (autocvar_sv_eventlog_files_timestamps)
141                 fputs(logfile, strcat(":time:", strftime(TRUE, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
142             else
143                 fputs(logfile, strcat(s, "\n"));
144         }
145     }
146     if (autocvar_sv_eventlog_console)
147     {
148         print(s, "\n");
149     }
150 }
151
152 void GameLogInit()
153 {
154     logfile_open = 0;
155     // will be opened later
156 }
157
158 void GameLogClose()
159 {
160     if (logfile_open && logfile >= 0)
161     {
162         fclose(logfile);
163         logfile = -1;
164     }
165 }
166
167 float spawnpoint_nag;
168 void relocate_spawnpoint()
169 {
170     // nudge off the floor
171     setorigin(self, self.origin + '0 0 1');
172
173     tracebox(self.origin, PL_MIN, PL_MAX, self.origin, TRUE, self);
174     if (trace_startsolid)
175     {
176         vector o;
177         o = self.origin;
178         self.mins = PL_MIN;
179         self.maxs = PL_MAX;
180         if (!move_out_of_solid(self))
181             objerror("could not get out of solid at all!");
182         print("^1NOTE: this map needs FIXING. Spawnpoint at ", vtos(o - '0 0 1'));
183         print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
184         print(" ", ftos(self.origin_y - o_y));
185         print(" ", ftos(self.origin_z - o_z), "'\n");
186         if (autocvar_g_spawnpoints_auto_move_out_of_solid)
187         {
188             if (!spawnpoint_nag)
189                 print("\{1}^1NOTE: this map needs FIXING (it contains spawnpoints in solid, see server log)\n");
190             spawnpoint_nag = 1;
191         }
192         else
193         {
194             setorigin(self, o);
195             self.mins = self.maxs = '0 0 0';
196             objerror("player spawn point in solid, mapper sucks!\n");
197             return;
198         }
199     }
200
201     self.use = spawnpoint_use;
202     self.team_saved = self.team;
203     if (!self.cnt)
204         self.cnt = 1;
205
206     if (have_team_spawns != 0)
207         if (self.team)
208             have_team_spawns = 1;
209     have_team_spawns_forteam[self.team] = 1;
210
211     if (autocvar_r_showbboxes)
212     {
213         // show where spawnpoints point at too
214         makevectors(self.angles);
215         entity e;
216         e = spawn();
217         e.classname = "info_player_foo";
218         setorigin(e, self.origin + v_forward * 24);
219         setsize(e, '-8 -8 -8', '8 8 8');
220         e.solid = SOLID_TRIGGER;
221     }
222 }
223
224 #define strstr strstrofs
225 /*
226 // NOTE: DO NOT USE THIS FUNCTION TOO OFTEN.
227 // IT WILL MOST PROBABLY DESTROY _ALL_ OTHER TEMP
228 // STRINGS AND TAKE QUITE LONG. haystack and needle MUST
229 // BE CONSTANT OR strzoneD!
230 float strstr(string haystack, string needle, float offset)
231 {
232         float len, endpos;
233         string found;
234         len = strlen(needle);
235         endpos = strlen(haystack) - len;
236         while(offset <= endpos)
237         {
238                 found = substring(haystack, offset, len);
239                 if(found == needle)
240                         return offset;
241                 offset = offset + 1;
242         }
243         return -1;
244 }
245 */
246
247 float NUM_NEAREST_ENTITIES = 4;
248 entity nearest_entity[NUM_NEAREST_ENTITIES];
249 float nearest_length[NUM_NEAREST_ENTITIES];
250 entity findnearest(vector point, .string field, string value, vector axismod)
251 {
252     entity localhead;
253     float i;
254     float j;
255     float len;
256     vector dist;
257
258     float num_nearest;
259     num_nearest = 0;
260
261     localhead = find(world, field, value);
262     while (localhead)
263     {
264         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
265             dist = localhead.oldorigin;
266         else
267             dist = localhead.origin;
268         dist = dist - point;
269         dist = dist_x * axismod_x * '1 0 0' + dist_y * axismod_y * '0 1 0' + dist_z * axismod_z * '0 0 1';
270         len = vlen(dist);
271
272         for (i = 0; i < num_nearest; ++i)
273         {
274             if (len < nearest_length[i])
275                 break;
276         }
277
278         // now i tells us where to insert at
279         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
280         if (i < NUM_NEAREST_ENTITIES)
281         {
282             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
283             {
284                 nearest_length[j + 1] = nearest_length[j];
285                 nearest_entity[j + 1] = nearest_entity[j];
286             }
287             nearest_length[i] = len;
288             nearest_entity[i] = localhead;
289             if (num_nearest < NUM_NEAREST_ENTITIES)
290                 num_nearest = num_nearest + 1;
291         }
292
293         localhead = find(localhead, field, value);
294     }
295
296     // now use the first one from our list that we can see
297     for (i = 0; i < num_nearest; ++i)
298     {
299         traceline(point, nearest_entity[i].origin, TRUE, world);
300         if (trace_fraction == 1)
301         {
302             if (i != 0)
303             {
304                 dprint("Nearest point (");
305                 dprint(nearest_entity[0].netname);
306                 dprint(") is not visible, using a visible one.\n");
307             }
308             return nearest_entity[i];
309         }
310     }
311
312     if (num_nearest == 0)
313         return world;
314
315     dprint("Not seeing any location point, using nearest as fallback.\n");
316     /* DEBUGGING CODE:
317     dprint("Candidates were: ");
318     for(j = 0; j < num_nearest; ++j)
319     {
320         if(j != 0)
321                 dprint(", ");
322         dprint(nearest_entity[j].netname);
323     }
324     dprint("\n");
325     */
326
327     return nearest_entity[0];
328 }
329
330 void spawnfunc_target_location()
331 {
332     self.classname = "target_location";
333     // location name in netname
334     // eventually support: count, teamgame selectors, line of sight?
335 }
336
337 void spawnfunc_info_location()
338 {
339     self.classname = "target_location";
340     self.message = self.netname;
341 }
342
343 string NearestLocation(vector p)
344 {
345     entity loc;
346     string ret;
347     ret = "somewhere";
348     loc = findnearest(p, classname, "target_location", '1 1 1');
349     if (loc)
350     {
351         ret = loc.message;
352     }
353     else
354     {
355         loc = findnearest(p, target, "###item###", '1 1 4');
356         if (loc)
357             ret = loc.netname;
358     }
359     return ret;
360 }
361
362 string formatmessage(string msg)
363 {
364         float p, p1, p2;
365         float n;
366         vector cursor;
367         entity cursor_ent;
368         string escape;
369         string replacement;
370         p = 0;
371         n = 7;
372
373         WarpZone_crosshair_trace(self);
374         cursor = trace_endpos;
375         cursor_ent = trace_ent;
376
377         while (1) {
378                 if (n < 1)
379                         break; // too many replacements
380
381                 n = n - 1;
382                 p1 = strstr(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
383                 p2 = strstr(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
384
385                 if (p1 < 0)
386                         p1 = p2;
387
388                 if (p2 < 0)
389                         p2 = p1;
390
391                 p = min(p1, p2);
392
393                 if (p < 0)
394                         break;
395
396                 replacement = substring(msg, p, 2);
397                 escape = substring(msg, p + 1, 1);
398
399                 if (escape == "%")
400                         replacement = "%";
401                 else if (escape == "\\")
402                         replacement = "\\";
403                 else if (escape == "n")
404                         replacement = "\n";
405                 else if (escape == "a")
406                         replacement = ftos(floor(self.armorvalue));
407                 else if (escape == "h")
408                         replacement = ftos(floor(self.health));
409                 else if (escape == "l")
410                         replacement = NearestLocation(self.origin);
411                 else if (escape == "y")
412                         replacement = NearestLocation(cursor);
413                 else if (escape == "d")
414                         replacement = NearestLocation(self.death_origin);
415                 else if (escape == "w") {
416                         float wep;
417                         wep = self.weapon;
418                         if (!wep)
419                                 wep = self.switchweapon;
420                         if (!wep)
421                                 wep = self.cnt;
422                         replacement = W_Name(wep);
423                 } else if (escape == "W") {
424                         if (self.items & IT_SHELLS) replacement = "shells";
425                         else if (self.items & IT_NAILS) replacement = "bullets";
426                         else if (self.items & IT_ROCKETS) replacement = "rockets";
427                         else if (self.items & IT_CELLS) replacement = "cells";
428                         else replacement = "batteries"; // ;)
429                 } else if (escape == "x") {
430                         replacement = cursor_ent.netname;
431                         if (!replacement || !cursor_ent)
432                                 replacement = "nothing";
433                 } else if (escape == "s")
434                         replacement = ftos(vlen(self.velocity - self.velocity_z * '0 0 1'));
435                 else if (escape == "S")
436                         replacement = ftos(vlen(self.velocity));
437
438                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
439                 p = p + strlen(replacement);
440         }
441         return msg;
442 }
443
444 float boolean(float value) { // if value is 0 return FALSE (0), otherwise return TRUE (1)
445         return (value == 0) ? FALSE : TRUE;
446 }
447
448 /*
449 =============
450 GetCvars
451 =============
452 Called with:
453   0:  sends the request
454   >0: receives a cvar from name=argv(f) value=argv(f+1)
455 */
456 void GetCvars_handleString(string thisname, float f, .string field, string name)
457 {
458         if (f < 0)
459         {
460                 if (self.field)
461                         strunzone(self.field);
462                 self.field = string_null;
463         }
464         else if (f > 0)
465         {
466                 if (thisname == name)
467                 {
468                         if (self.field)
469                                 strunzone(self.field);
470                         self.field = strzone(argv(f + 1));
471                 }
472         }
473         else
474                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
475 }
476 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
477 {
478         GetCvars_handleString(thisname, f, field, name);
479         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
480                 if (thisname == name)
481                 {
482                         string s;
483                         s = func(strcat1(self.field));
484                         if (s != self.field)
485                         {
486                                 strunzone(self.field);
487                                 self.field = strzone(s);
488                         }
489                 }
490 }
491 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
492 {
493         if (f < 0)
494         {
495         }
496         else if (f > 0)
497         {
498                 if (thisname == name)
499                         self.field = stof(argv(f + 1));
500         }
501         else
502                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
503 }
504 void GetCvars_handleFloatOnce(string thisname, float f, .float field, string name)
505 {
506         if (f < 0)
507         {
508         }
509         else if (f > 0)
510         {
511                 if (thisname == name)
512                 {
513                         if(!self.field)
514                         {
515                                 self.field = stof(argv(f + 1));
516                                 if(!self.field)
517                                         self.field = -1;
518                         }
519                 }
520         }
521         else
522         {
523                 if(!self.field)
524                         stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
525         }
526 }
527 float w_getbestweapon(entity e);
528 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(string wo)
529 {
530         string o;
531         o = W_FixWeaponOrder_ForceComplete(wo);
532         if(self.weaponorder_byimpulse)
533         {
534                 strunzone(self.weaponorder_byimpulse);
535                 self.weaponorder_byimpulse = string_null;
536         }
537         self.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
538         return o;
539 }
540 void GetCvars(float f)
541 {
542         string s = string_null;
543
544         if (f > 0)
545                 s = strcat1(argv(f));
546
547         get_cvars_f = f;
548         get_cvars_s = s;
549         MUTATOR_CALLHOOK(GetCvars);
550         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
551         GetCvars_handleFloat(s, f, cvar_cl_autoscreenshot, "cl_autoscreenshot");
552         GetCvars_handleString(s, f, cvar_g_xonoticversion, "g_xonoticversion");
553         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
554         GetCvars_handleFloat(s, f, cvar_cl_clippedspectating, "cl_clippedspectating");
555         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
556         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
557         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
558         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
559         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
560         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
561         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
562         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
563         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
564         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
565         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
566         GetCvars_handleFloat(s, f, cvar_cl_weaponimpulsemode, "cl_weaponimpulsemode");
567         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
568         GetCvars_handleFloat(s, f, cvar_cl_noantilag, "cl_noantilag");
569         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
570         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
571         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_share, "cl_accuracy_data_share");
572         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_receive, "cl_accuracy_data_receive");
573
574         self.cvar_cl_accuracy_data_share = boolean(self.cvar_cl_accuracy_data_share);
575         self.cvar_cl_accuracy_data_receive = boolean(self.cvar_cl_accuracy_data_receive);
576
577 #ifdef ALLOW_FORCEMODELS
578         GetCvars_handleFloat(s, f, cvar_cl_forceplayermodels, "cl_forceplayermodels");
579         GetCvars_handleFloat(s, f, cvar_cl_forceplayermodelsfromxonotic, "cl_forceplayermodelsfromxonotic");
580 #endif
581         GetCvars_handleFloatOnce(s, f, cvar_cl_gunalign, "cl_gunalign");
582         GetCvars_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
583         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
584         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
585         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
586
587         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
588         if (f > 0)
589         {
590                 if (s == "cl_weaponpriority")
591                         self.switchweapon = w_getbestweapon(self);
592                 if (s == "cl_allow_uidtracking")
593                         PlayerStats_AddPlayer(self);
594         }
595 }
596
597 void backtrace(string msg)
598 {
599     float dev, war;
600     dev = autocvar_developer;
601     war = autocvar_prvm_backtraceforwarnings;
602     cvar_set("developer", "1");
603     cvar_set("prvm_backtraceforwarnings", "1");
604     print("\n");
605     print("--- CUT HERE ---\nWARNING: ");
606     print(msg);
607     print("\n");
608     remove(world); // isn't there any better way to cause a backtrace?
609     print("\n--- CUT UNTIL HERE ---\n");
610     cvar_set("developer", ftos(dev));
611     cvar_set("prvm_backtraceforwarnings", ftos(war));
612 }
613
614 string Team_ColorCode(float teamid)
615 {
616     if (teamid == COLOR_TEAM1)
617         return "^1";
618     else if (teamid == COLOR_TEAM2)
619         return "^4";
620     else if (teamid == COLOR_TEAM3)
621         return "^3";
622     else if (teamid == COLOR_TEAM4)
623         return "^6";
624     else
625         return "^7";
626 }
627
628 string Team_ColorName(float t)
629 {
630     // fixme: Search for team entities and get their .netname's!
631     if (t == COLOR_TEAM1)
632         return "Red";
633     if (t == COLOR_TEAM2)
634         return "Blue";
635     if (t == COLOR_TEAM3)
636         return "Yellow";
637     if (t == COLOR_TEAM4)
638         return "Pink";
639     return "Neutral";
640 }
641
642 string Team_ColorNameLowerCase(float t)
643 {
644     // fixme: Search for team entities and get their .netname's!
645     if (t == COLOR_TEAM1)
646         return "red";
647     if (t == COLOR_TEAM2)
648         return "blue";
649     if (t == COLOR_TEAM3)
650         return "yellow";
651     if (t == COLOR_TEAM4)
652         return "pink";
653     return "neutral";
654 }
655
656 float ColourToNumber(string team_colour)
657 {
658         if (team_colour == "red")
659                 return COLOR_TEAM1;
660
661         if (team_colour == "blue")
662                 return COLOR_TEAM2;
663
664         if (team_colour == "yellow")
665                 return COLOR_TEAM3;
666
667         if (team_colour == "pink")
668                 return COLOR_TEAM4;
669
670         if (team_colour == "auto")
671                 return 0;
672
673         return -1;
674 }
675
676 float NumberToTeamNumber(float number)
677 {
678         if (number == 1)
679                 return COLOR_TEAM1;
680
681         if (number == 2)
682                 return COLOR_TEAM2;
683
684         if (number == 3)
685                 return COLOR_TEAM3;
686
687         if (number == 4)
688                 return COLOR_TEAM4;
689
690         return -1;
691 }
692
693 // decolorizes and team colors the player name when needed
694 string playername(entity p)
695 {
696     string t;
697     if (teamplay && !intermission_running && p.classname == "player")
698     {
699         t = Team_ColorCode(p.team);
700         return strcat(t, strdecolorize(p.netname));
701     }
702     else
703         return p.netname;
704 }
705
706 vector randompos(vector m1, vector m2)
707 {
708     vector v;
709     m2 = m2 - m1;
710     v_x = m2_x * random() + m1_x;
711     v_y = m2_y * random() + m1_y;
712     v_z = m2_z * random() + m1_z;
713     return  v;
714 }
715
716 //#NO AUTOCVARS START
717
718 float g_pickup_shells;
719 float g_pickup_shells_max;
720 float g_pickup_nails;
721 float g_pickup_nails_max;
722 float g_pickup_rockets;
723 float g_pickup_rockets_max;
724 float g_pickup_cells;
725 float g_pickup_cells_max;
726 float g_pickup_fuel;
727 float g_pickup_fuel_jetpack;
728 float g_pickup_fuel_max;
729 float g_pickup_armorsmall;
730 float g_pickup_armorsmall_max;
731 float g_pickup_armorsmall_anyway;
732 float g_pickup_armormedium;
733 float g_pickup_armormedium_max;
734 float g_pickup_armormedium_anyway;
735 float g_pickup_armorbig;
736 float g_pickup_armorbig_max;
737 float g_pickup_armorbig_anyway;
738 float g_pickup_armorlarge;
739 float g_pickup_armorlarge_max;
740 float g_pickup_armorlarge_anyway;
741 float g_pickup_healthsmall;
742 float g_pickup_healthsmall_max;
743 float g_pickup_healthsmall_anyway;
744 float g_pickup_healthmedium;
745 float g_pickup_healthmedium_max;
746 float g_pickup_healthmedium_anyway;
747 float g_pickup_healthlarge;
748 float g_pickup_healthlarge_max;
749 float g_pickup_healthlarge_anyway;
750 float g_pickup_healthmega;
751 float g_pickup_healthmega_max;
752 float g_pickup_healthmega_anyway;
753 float g_pickup_ammo_anyway;
754 float g_pickup_weapons_anyway;
755 float g_weaponarena;
756 WEPSET_DECLARE_A(g_weaponarena_weapons);
757 float g_weaponarena_random;
758 float g_weaponarena_random_with_laser;
759 string g_weaponarena_list;
760 float g_weaponspeedfactor;
761 float g_weaponratefactor;
762 float g_weapondamagefactor;
763 float g_weaponforcefactor;
764 float g_weaponspreadfactor;
765
766 WEPSET_DECLARE_A(start_weapons);
767 WEPSET_DECLARE_A(start_weapons_default);
768 WEPSET_DECLARE_A(start_weapons_defaultmask);
769 float start_items;
770 float start_ammo_shells;
771 float start_ammo_nails;
772 float start_ammo_rockets;
773 float start_ammo_cells;
774 float start_ammo_fuel;
775 float start_health;
776 float start_armorvalue;
777 WEPSET_DECLARE_A(warmup_start_weapons);
778 WEPSET_DECLARE_A(warmup_start_weapons_default);
779 WEPSET_DECLARE_A(warmup_start_weapons_defaultmask);
780 float warmup_start_ammo_shells;
781 float warmup_start_ammo_nails;
782 float warmup_start_ammo_rockets;
783 float warmup_start_ammo_cells;
784 float warmup_start_ammo_fuel;
785 float warmup_start_health;
786 float warmup_start_armorvalue;
787 float g_weapon_stay;
788
789 entity get_weaponinfo(float w);
790
791 float want_weapon(string cvarprefix, entity weaponinfo, float allguns)
792 {
793         var float i = weaponinfo.weapon;
794         var float d = 0;
795
796         if (!i)
797                 return 0;
798
799         if (g_lms || g_ca || allguns)
800         {
801                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
802                         d = TRUE;
803                 else
804                         d = FALSE;
805         }
806         else if (g_cts)
807                 d = (i == WEP_SHOTGUN);
808         else if (g_nexball)
809                 d = 0; // weapon is set a few lines later
810         else
811                 d = (i == WEP_LASER || i == WEP_SHOTGUN);
812                 
813         if(g_grappling_hook) // if possible, redirect off-hand hook to on-hand hook
814                 d |= (i == WEP_HOOK);
815         if(weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED) // never default mutator blocked guns
816                 d = 0;
817
818         var float t = cvar(strcat(cvarprefix, weaponinfo.netname));
819         
820         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
821         
822         // bit order in t:
823         // 1: want or not
824         // 2: is default?
825         // 4: is set by default?
826         if(t < 0)
827                 t = 4 | (3 * d);
828         else
829                 t |= (2 * d);
830
831         return t;
832 }
833
834 void readplayerstartcvars()
835 {
836         entity e;
837         float i, j, t;
838         string s;
839
840         // initialize starting values for players
841         WEPSET_CLEAR_A(start_weapons);
842         WEPSET_CLEAR_A(start_weapons_default);
843         WEPSET_CLEAR_A(start_weapons_defaultmask);
844         start_items = 0;
845         start_ammo_shells = 0;
846         start_ammo_nails = 0;
847         start_ammo_rockets = 0;
848         start_ammo_cells = 0;
849         start_health = cvar("g_balance_health_start");
850         start_armorvalue = cvar("g_balance_armor_start");
851
852         g_weaponarena = 0;
853         WEPSET_CLEAR_A(g_weaponarena_weapons);
854
855         s = cvar_string("g_weaponarena");
856         if (s == "0" || s == "")
857         {
858                 if(g_lms || g_ca)
859                         s = "most";
860         }
861
862         if (s == "0" || s == "")
863         {
864                 // no arena
865         }
866         else if (s == "off")
867         {
868                 // forcibly turn off weaponarena
869         }
870         else if (s == "all")
871         {
872                 g_weaponarena = 1;
873                 g_weaponarena_list = "All Weapons";
874                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
875                 {
876                         e = get_weaponinfo(j);
877                         if not(e.spawnflags & WEP_FLAG_MUTATORBLOCKED)
878                                 WEPSET_OR_AW(g_weaponarena_weapons, j);
879                 }
880         }
881         else if (s == "most")
882         {
883                 g_weaponarena = 1;
884                 g_weaponarena_list = "Most Weapons";
885                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
886                 {
887                         e = get_weaponinfo(j);
888                         if not(e.spawnflags & WEP_FLAG_MUTATORBLOCKED)
889                                 if (e.spawnflags & WEP_FLAG_NORMAL)
890                                         WEPSET_OR_AW(g_weaponarena_weapons, j);
891                 }
892         }
893         else if (s == "none")
894         {
895                 g_weaponarena = 1;
896                 g_weaponarena_list = "No Weapons";
897         }
898         else
899         {
900                 g_weaponarena = 1;
901                 t = tokenize_console(s);
902                 g_weaponarena_list = "";
903                 for (i = 0; i < t; ++i)
904                 {
905                         s = argv(i);
906                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
907                         {
908                                 e = get_weaponinfo(j);
909                                 if (e.netname == s)
910                                 {
911                                         WEPSET_OR_AW(g_weaponarena_weapons, j);
912                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
913                                         break;
914                                 }
915                         }
916                         if (j > WEP_LAST)
917                         {
918                                 print("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
919                         }
920                 }
921                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
922         }
923
924         if(g_weaponarena)
925                 g_weaponarena_random = cvar("g_weaponarena_random");
926         else
927                 g_weaponarena_random = 0;
928         g_weaponarena_random_with_laser = cvar("g_weaponarena_random_with_laser");
929
930         if (g_weaponarena)
931         {
932                 g_minstagib = 0; // incompatible
933                 g_pinata = 0; // incompatible
934                 g_weapon_stay = 0; // incompatible
935                 WEPSET_COPY_AA(start_weapons, g_weaponarena_weapons);
936                 if(!(g_lms || g_ca))
937                         start_items |= IT_UNLIMITED_AMMO;
938         }
939         else if (g_minstagib)
940         {
941                 g_pinata = 0; // incompatible
942                 g_weapon_stay = 0; // incompatible
943                 g_bloodloss = 0; // incompatible
944                 start_health = 100;
945                 start_armorvalue = 0;
946                 WEPSET_COPY_AW(start_weapons, WEP_MINSTANEX);
947                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
948                 start_items |= IT_UNLIMITED_SUPERWEAPONS;
949
950                 if (g_minstagib_invis_alpha <= 0)
951                         g_minstagib_invis_alpha = -1;
952         }
953         else
954         {
955                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
956                 {
957                         e = get_weaponinfo(i);
958                         float w = want_weapon("g_start_weapon_", e, FALSE);
959                         if(w & 1)
960                                 WEPSET_OR_AW(start_weapons, i);
961                         if(w & 2)
962                                 WEPSET_OR_AW(start_weapons_default, i);
963                         if(w & 4)
964                                 WEPSET_OR_AW(start_weapons_defaultmask, i);
965                 }
966         }
967
968         if(!cvar("g_use_ammunition"))
969                 start_items |= IT_UNLIMITED_AMMO;
970
971         if(cvar("g_nexball"))
972                 start_items |= IT_UNLIMITED_SUPERWEAPONS; // FIXME BAD BAD BAD BAD HACK, NEXBALL SHOULDN'T ABUSE PORTO'S WEAPON SLOT
973
974         if(g_minstagib)
975         {
976                 start_ammo_cells = cvar("g_minstagib_ammo_start");
977                 start_ammo_fuel = cvar("g_start_ammo_fuel");
978         }
979         else if(start_items & IT_UNLIMITED_WEAPON_AMMO)
980         {
981                 start_ammo_rockets = 999;
982                 start_ammo_shells = 999;
983                 start_ammo_cells = 999;
984                 start_ammo_nails = 999;
985                 start_ammo_fuel = 999;
986         }
987         else
988         {
989                 if(g_lms || g_ca)
990                 {
991                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
992                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
993                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
994                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
995                         start_ammo_fuel = cvar("g_lms_start_ammo_fuel");
996                 }
997                 else
998                 {
999                         start_ammo_shells = cvar("g_start_ammo_shells");
1000                         start_ammo_nails = cvar("g_start_ammo_nails");
1001                         start_ammo_rockets = cvar("g_start_ammo_rockets");
1002                         start_ammo_cells = cvar("g_start_ammo_cells");
1003                         start_ammo_fuel = cvar("g_start_ammo_fuel");
1004                 }
1005         }
1006
1007         if (g_lms || g_ca)
1008         {
1009                 start_health = cvar("g_lms_start_health");
1010                 start_armorvalue = cvar("g_lms_start_armor");
1011         }
1012
1013         if (inWarmupStage)
1014         {
1015                 warmup_start_ammo_shells = start_ammo_shells;
1016                 warmup_start_ammo_nails = start_ammo_nails;
1017                 warmup_start_ammo_rockets = start_ammo_rockets;
1018                 warmup_start_ammo_cells = start_ammo_cells;
1019                 warmup_start_ammo_fuel = start_ammo_fuel;
1020                 warmup_start_health = start_health;
1021                 warmup_start_armorvalue = start_armorvalue;
1022                 WEPSET_COPY_AA(warmup_start_weapons, start_weapons);
1023                 WEPSET_COPY_AA(warmup_start_weapons_default, start_weapons_default);
1024                 WEPSET_COPY_AA(warmup_start_weapons_defaultmask, start_weapons_defaultmask);
1025
1026                 if (!g_weaponarena && !g_minstagib && !g_ca)
1027                 {
1028                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
1029                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
1030                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
1031                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
1032                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
1033                         warmup_start_health = cvar("g_warmup_start_health");
1034                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
1035                         WEPSET_CLEAR_A(warmup_start_weapons);
1036                         WEPSET_CLEAR_A(warmup_start_weapons_default);
1037                         WEPSET_CLEAR_A(warmup_start_weapons_defaultmask);
1038                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
1039                         {
1040                                 e = get_weaponinfo(i);
1041                                 float w = want_weapon("g_start_weapon_", e, cvar("g_warmup_allguns"));
1042                                 if(w & 1)
1043                                         WEPSET_OR_AW(warmup_start_weapons, i);
1044                                 if(w & 2)
1045                                         WEPSET_OR_AW(warmup_start_weapons_default, i);
1046                                 if(w & 4)
1047                                         WEPSET_OR_AW(warmup_start_weapons_defaultmask, i);
1048                         }
1049                 }
1050         }
1051
1052         if (g_jetpack)
1053                 start_items |= IT_JETPACK;
1054
1055         MUTATOR_CALLHOOK(SetStartItems);
1056
1057         if ((start_items & IT_JETPACK) || (g_grappling_hook && WEPSET_CONTAINS_AW(start_weapons, WEP_HOOK)))
1058         {
1059                 g_grappling_hook = 0; // these two can't coexist, as they use the same button
1060                 start_items |= IT_FUEL_REGEN;
1061                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
1062                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
1063         }
1064
1065         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
1066         {
1067                 e = get_weaponinfo(i);
1068                 if(WEPSET_CONTAINS_AW(start_weapons, i) || WEPSET_CONTAINS_AW(warmup_start_weapons, i))
1069                         weapon_action(i, WR_PRECACHE);
1070         }
1071
1072         start_ammo_shells = max(0, start_ammo_shells);
1073         start_ammo_nails = max(0, start_ammo_nails);
1074         start_ammo_cells = max(0, start_ammo_cells);
1075         start_ammo_rockets = max(0, start_ammo_rockets);
1076         start_ammo_fuel = max(0, start_ammo_fuel);
1077
1078         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
1079         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
1080         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
1081         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
1082         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
1083 }
1084
1085 float g_bugrigs;
1086 float g_bugrigs_planar_movement;
1087 float g_bugrigs_planar_movement_car_jumping;
1088 float g_bugrigs_reverse_spinning;
1089 float g_bugrigs_reverse_speeding;
1090 float g_bugrigs_reverse_stopping;
1091 float g_bugrigs_air_steering;
1092 float g_bugrigs_angle_smoothing;
1093 float g_bugrigs_friction_floor;
1094 float g_bugrigs_friction_brake;
1095 float g_bugrigs_friction_air;
1096 float g_bugrigs_accel;
1097 float g_bugrigs_speed_ref;
1098 float g_bugrigs_speed_pow;
1099 float g_bugrigs_steer;
1100
1101 float g_touchexplode;
1102 float g_touchexplode_radius;
1103 float g_touchexplode_damage;
1104 float g_touchexplode_edgedamage;
1105 float g_touchexplode_force;
1106
1107 float sv_autotaunt;
1108 float sv_taunt;
1109
1110 float sv_pitch_min;
1111 float sv_pitch_max;
1112 float sv_pitch_fixyaw;
1113
1114 string GetGametype(); // g_world.qc
1115 void readlevelcvars(void)
1116 {
1117         g_minstagib = cvar("g_minstagib");
1118
1119         // load ALL the mutators
1120         if(cvar("g_dodging"))
1121                 MUTATOR_ADD(mutator_dodging);
1122         if(cvar("g_spawn_near_teammate"))
1123                 MUTATOR_ADD(mutator_spawn_near_teammate);
1124         if(!g_minstagib)
1125         {
1126                 if(cvar("g_invincible_projectiles"))
1127                         MUTATOR_ADD(mutator_invincibleprojectiles);
1128                 if(cvar("g_new_toys"))
1129                         MUTATOR_ADD(mutator_new_toys);
1130                 if(cvar("g_nix"))
1131                         MUTATOR_ADD(mutator_nix);
1132                 if(cvar("g_rocket_flying"))
1133                         MUTATOR_ADD(mutator_rocketflying);
1134                 if(cvar("g_vampire"))
1135                         MUTATOR_ADD(mutator_vampire);           
1136                 if(cvar("g_superspectate"))
1137                         MUTATOR_ADD(mutator_superspec);
1138         }
1139
1140         // is this a mutator? is this a mode?
1141         if(cvar("g_sandbox"))
1142                 MUTATOR_ADD(sandbox);
1143
1144         if(cvar("sv_allow_fullbright"))
1145                 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
1146
1147     g_bugrigs = cvar("g_bugrigs");
1148     g_bugrigs_planar_movement = cvar("g_bugrigs_planar_movement");
1149     g_bugrigs_planar_movement_car_jumping = cvar("g_bugrigs_planar_movement_car_jumping");
1150     g_bugrigs_reverse_spinning = cvar("g_bugrigs_reverse_spinning");
1151     g_bugrigs_reverse_speeding = cvar("g_bugrigs_reverse_speeding");
1152     g_bugrigs_reverse_stopping = cvar("g_bugrigs_reverse_stopping");
1153     g_bugrigs_air_steering = cvar("g_bugrigs_air_steering");
1154     g_bugrigs_angle_smoothing = cvar("g_bugrigs_angle_smoothing");
1155     g_bugrigs_friction_floor = cvar("g_bugrigs_friction_floor");
1156     g_bugrigs_friction_brake = cvar("g_bugrigs_friction_brake");
1157     g_bugrigs_friction_air = cvar("g_bugrigs_friction_air");
1158     g_bugrigs_accel = cvar("g_bugrigs_accel");
1159     g_bugrigs_speed_ref = cvar("g_bugrigs_speed_ref");
1160     g_bugrigs_speed_pow = cvar("g_bugrigs_speed_pow");
1161     g_bugrigs_steer = cvar("g_bugrigs_steer");
1162
1163     g_touchexplode = cvar("g_touchexplode");
1164     g_touchexplode_radius = cvar("g_touchexplode_radius");
1165     g_touchexplode_damage = cvar("g_touchexplode_damage");
1166     g_touchexplode_edgedamage = cvar("g_touchexplode_edgedamage");
1167     g_touchexplode_force = cvar("g_touchexplode_force");
1168
1169 #ifdef ALLOW_FORCEMODELS
1170         sv_clforceplayermodels = cvar("sv_clforceplayermodels");
1171 #endif
1172
1173         sv_clones = cvar("sv_clones");
1174         sv_gentle = cvar("sv_gentle");
1175         sv_foginterval = cvar("sv_foginterval");
1176         g_cloaked = cvar("g_cloaked");
1177     if(g_cts)
1178         g_cloaked = 1; // always enable cloak in CTS
1179         g_jump_grunt = cvar("g_jump_grunt");
1180         g_footsteps = cvar("g_footsteps");
1181         g_grappling_hook = cvar("g_grappling_hook");
1182         g_jetpack = cvar("g_jetpack");
1183         g_midair = cvar("g_midair");
1184         g_norecoil = cvar("g_norecoil");
1185         g_bloodloss = cvar("g_bloodloss");
1186         sv_maxidle = cvar("sv_maxidle");
1187         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
1188         sv_autotaunt = cvar("sv_autotaunt");
1189         sv_taunt = cvar("sv_taunt");
1190
1191         inWarmupStage = cvar("g_warmup");
1192         g_warmup_limit = cvar("g_warmup_limit");
1193         g_warmup_allguns = cvar("g_warmup_allguns");
1194         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
1195
1196         if ((g_race && g_race_qualifying == 2) || g_runematch || g_arena || g_assault || cvar("g_campaign"))
1197                 inWarmupStage = 0; // these modes cannot work together, sorry
1198
1199         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
1200         g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
1201         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
1202         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
1203         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
1204         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
1205         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
1206         g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
1207         g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
1208         g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
1209         g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
1210         g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
1211         g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
1212         g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
1213
1214         g_weaponspeedfactor = cvar("g_weaponspeedfactor");
1215         g_weaponratefactor = cvar("g_weaponratefactor");
1216         g_weapondamagefactor = cvar("g_weapondamagefactor");
1217         g_weaponforcefactor = cvar("g_weaponforcefactor");
1218         g_weaponspreadfactor = cvar("g_weaponspreadfactor");
1219
1220         g_pickup_shells = cvar("g_pickup_shells");
1221         g_pickup_shells_max = cvar("g_pickup_shells_max");
1222         g_pickup_nails = cvar("g_pickup_nails");
1223         g_pickup_nails_max = cvar("g_pickup_nails_max");
1224         g_pickup_rockets = cvar("g_pickup_rockets");
1225         g_pickup_rockets_max = cvar("g_pickup_rockets_max");
1226         g_pickup_cells = cvar("g_pickup_cells");
1227         g_pickup_cells_max = cvar("g_pickup_cells_max");
1228         g_pickup_fuel = cvar("g_pickup_fuel");
1229         g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
1230         g_pickup_fuel_max = cvar("g_pickup_fuel_max");
1231         g_pickup_armorsmall = cvar("g_pickup_armorsmall");
1232         g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
1233         g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
1234         g_pickup_armormedium = cvar("g_pickup_armormedium");
1235         g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
1236         g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
1237         g_pickup_armorbig = cvar("g_pickup_armorbig");
1238         g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
1239         g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
1240         g_pickup_armorlarge = cvar("g_pickup_armorlarge");
1241         g_pickup_armorlarge_max = cvar("g_pickup_armorlarge_max");
1242         g_pickup_armorlarge_anyway = cvar("g_pickup_armorlarge_anyway");
1243         g_pickup_healthsmall = cvar("g_pickup_healthsmall");
1244         g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
1245         g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
1246         g_pickup_healthmedium = cvar("g_pickup_healthmedium");
1247         g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
1248         g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
1249         g_pickup_healthlarge = cvar("g_pickup_healthlarge");
1250         g_pickup_healthlarge_max = cvar("g_pickup_healthlarge_max");
1251         g_pickup_healthlarge_anyway = cvar("g_pickup_healthlarge_anyway");
1252         g_pickup_healthmega = cvar("g_pickup_healthmega");
1253         g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
1254         g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
1255
1256         g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
1257         g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
1258
1259         g_pinata = cvar("g_pinata");
1260
1261     g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
1262     if(!g_weapon_stay)
1263         g_weapon_stay = cvar("g_weapon_stay");
1264
1265         if not(inWarmupStage && !g_ca)
1266                 game_starttime = cvar("g_start_delay");
1267
1268         sv_pitch_min = cvar("sv_pitch_min");
1269         sv_pitch_max = cvar("sv_pitch_max");
1270         sv_pitch_fixyaw = cvar("sv_pitch_fixyaw");
1271
1272         readplayerstartcvars();
1273 }
1274
1275 //#NO AUTOCVARS END
1276
1277 // Sound functions
1278 string precache_sound (string s) = #19;
1279 float precache_sound_index (string s) = #19;
1280
1281 #define SND_VOLUME      1
1282 #define SND_ATTENUATION 2
1283 #define SND_LARGEENTITY 8
1284 #define SND_LARGESOUND  16
1285
1286 float sound_allowed(float dest, entity e)
1287 {
1288     // sounds from world may always pass
1289     for (;;)
1290     {
1291         if (e.classname == "body")
1292             e = e.enemy;
1293         else if (e.realowner && e.realowner != e)
1294             e = e.realowner;
1295         else if (e.owner && e.owner != e)
1296             e = e.owner;
1297         else
1298             break;
1299     }
1300     // sounds to self may always pass
1301     if (dest == MSG_ONE)
1302         if (e == msg_entity)
1303             return TRUE;
1304     // sounds by players can be removed
1305     if (autocvar_bot_sound_monopoly)
1306         if (clienttype(e) == CLIENTTYPE_REAL)
1307             return FALSE;
1308     // anything else may pass
1309     return TRUE;
1310 }
1311
1312 #ifdef COMPAT_XON010_CHANNELS
1313 void(entity e, float chan, string samp, float vol, float atten) builtin_sound = #8;
1314 void sound(entity e, float chan, string samp, float vol, float atten)
1315 {
1316     if (!sound_allowed(MSG_BROADCAST, e))
1317         return;
1318     builtin_sound(e, chan, samp, vol, atten);
1319 }
1320 #else
1321 #undef sound
1322 void sound(entity e, float chan, string samp, float vol, float atten)
1323 {
1324     if (!sound_allowed(MSG_BROADCAST, e))
1325         return;
1326     sound7(e, chan, samp, vol, atten, 0, 0);
1327 }
1328 #endif
1329
1330 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
1331 {
1332     float entno, idx;
1333
1334     if (!sound_allowed(dest, e))
1335         return;
1336
1337     entno = num_for_edict(e);
1338     idx = precache_sound_index(samp);
1339
1340     float sflags;
1341     sflags = 0;
1342
1343     atten = floor(atten * 64);
1344     vol = floor(vol * 255);
1345
1346     if (vol != 255)
1347         sflags |= SND_VOLUME;
1348     if (atten != 64)
1349         sflags |= SND_ATTENUATION;
1350     if (entno >= 8192 || chan < 0 || chan > 7)
1351         sflags |= SND_LARGEENTITY;
1352     if (idx >= 256)
1353         sflags |= SND_LARGESOUND;
1354
1355     WriteByte(dest, SVC_SOUND);
1356     WriteByte(dest, sflags);
1357     if (sflags & SND_VOLUME)
1358         WriteByte(dest, vol);
1359     if (sflags & SND_ATTENUATION)
1360         WriteByte(dest, atten);
1361     if (sflags & SND_LARGEENTITY)
1362     {
1363         WriteShort(dest, entno);
1364         WriteByte(dest, chan);
1365     }
1366     else
1367     {
1368         WriteShort(dest, entno * 8 + chan);
1369     }
1370     if (sflags & SND_LARGESOUND)
1371         WriteShort(dest, idx);
1372     else
1373         WriteByte(dest, idx);
1374
1375     WriteCoord(dest, o_x);
1376     WriteCoord(dest, o_y);
1377     WriteCoord(dest, o_z);
1378 }
1379 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1380 {
1381     vector o;
1382
1383     if (!sound_allowed(dest, e))
1384         return;
1385
1386     o = e.origin + 0.5 * (e.mins + e.maxs);
1387     soundtoat(dest, e, o, chan, samp, vol, atten);
1388 }
1389 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1390 {
1391     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, atten);
1392 }
1393 void stopsoundto(float dest, entity e, float chan)
1394 {
1395     float entno;
1396
1397     if (!sound_allowed(dest, e))
1398         return;
1399
1400     entno = num_for_edict(e);
1401
1402     if (entno >= 8192 || chan < 0 || chan > 7)
1403     {
1404         float idx, sflags;
1405         idx = precache_sound_index("misc/null.wav");
1406         sflags = SND_LARGEENTITY;
1407         if (idx >= 256)
1408             sflags |= SND_LARGESOUND;
1409         WriteByte(dest, SVC_SOUND);
1410         WriteByte(dest, sflags);
1411         WriteShort(dest, entno);
1412         WriteByte(dest, chan);
1413         if (sflags & SND_LARGESOUND)
1414             WriteShort(dest, idx);
1415         else
1416             WriteByte(dest, idx);
1417         WriteCoord(dest, e.origin_x);
1418         WriteCoord(dest, e.origin_y);
1419         WriteCoord(dest, e.origin_z);
1420     }
1421     else
1422     {
1423         WriteByte(dest, SVC_STOPSOUND);
1424         WriteShort(dest, entno * 8 + chan);
1425     }
1426 }
1427 void stopsound(entity e, float chan)
1428 {
1429     if (!sound_allowed(MSG_BROADCAST, e))
1430         return;
1431
1432     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
1433     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
1434 }
1435
1436 void play2(entity e, string filename)
1437 {
1438     //stuffcmd(e, strcat("play2 ", filename, "\n"));
1439     msg_entity = e;
1440     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTN_NONE);
1441 }
1442
1443 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
1444 .float spamtime;
1445 float spamsound(entity e, float chan, string samp, float vol, float atten)
1446 {
1447     if (!sound_allowed(MSG_BROADCAST, e))
1448         return FALSE;
1449
1450     if (time > e.spamtime)
1451     {
1452         e.spamtime = time;
1453         sound(e, chan, samp, vol, atten);
1454         return TRUE;
1455     }
1456     return FALSE;
1457 }
1458
1459 void play2team(float t, string filename)
1460 {
1461     entity head;
1462
1463     if (autocvar_bot_sound_monopoly)
1464         return;
1465
1466     FOR_EACH_REALPLAYER(head)
1467     {
1468         if (head.team == t)
1469             play2(head, filename);
1470     }
1471 }
1472
1473 void play2all(string samp)
1474 {
1475     if (autocvar_bot_sound_monopoly)
1476         return;
1477
1478     sound(world, CH_INFO, samp, VOL_BASE, ATTN_NONE);
1479 }
1480
1481 void PrecachePlayerSounds(string f);
1482 void precache_playermodel(string m)
1483 {
1484         float globhandle, i, n;
1485         string f;
1486
1487         if(substring(m, -9,5) == "_lod1")
1488                 return;
1489         if(substring(m, -9,5) == "_lod2")
1490                 return;
1491         precache_model(m);
1492         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
1493         if(fexists(f))
1494                 precache_model(f);
1495         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
1496         if(fexists(f))
1497                 precache_model(f);
1498
1499         globhandle = search_begin(strcat(m, "_*.sounds"), TRUE, FALSE);
1500         if (globhandle < 0)
1501                 return;
1502         n = search_getsize(globhandle);
1503         for (i = 0; i < n; ++i)
1504         {
1505                 //print(search_getfilename(globhandle, i), "\n");
1506                 f = search_getfilename(globhandle, i);
1507                 PrecachePlayerSounds(f);
1508         }
1509         search_end(globhandle);
1510 }
1511 void precache_all_playermodels(string pattern)
1512 {
1513         float globhandle, i, n;
1514         string f;
1515
1516         globhandle = search_begin(pattern, TRUE, FALSE);
1517         if (globhandle < 0)
1518                 return;
1519         n = search_getsize(globhandle);
1520         for (i = 0; i < n; ++i)
1521         {
1522                 //print(search_getfilename(globhandle, i), "\n");
1523                 f = search_getfilename(globhandle, i);
1524                 precache_playermodel(f);
1525         }
1526         search_end(globhandle);
1527 }
1528
1529 void precache()
1530 {
1531     // gamemode related things
1532     precache_model ("models/misc/chatbubble.spr");
1533     if (g_runematch)
1534     {
1535         precache_model ("models/runematch/curse.mdl");
1536         precache_model ("models/runematch/rune.mdl");
1537     }
1538
1539 #ifdef TTURRETS_ENABLED
1540     if (autocvar_g_turrets)
1541         turrets_precash();
1542 #endif
1543
1544     // Precache all player models if desired
1545     if (autocvar_sv_precacheplayermodels)
1546     {
1547         PrecachePlayerSounds("sound/player/default.sounds");
1548         precache_all_playermodels("models/player/*.zym");
1549         precache_all_playermodels("models/player/*.dpm");
1550         precache_all_playermodels("models/player/*.md3");
1551         precache_all_playermodels("models/player/*.psk");
1552         precache_all_playermodels("models/player/*.iqm");
1553     }
1554
1555     if (autocvar_sv_defaultcharacter)
1556     {
1557         string s;
1558         s = autocvar_sv_defaultplayermodel_red;
1559         if (s != "")
1560             precache_playermodel(s);
1561         s = autocvar_sv_defaultplayermodel_blue;
1562         if (s != "")
1563             precache_playermodel(s);
1564         s = autocvar_sv_defaultplayermodel_yellow;
1565         if (s != "")
1566             precache_playermodel(s);
1567         s = autocvar_sv_defaultplayermodel_pink;
1568         if (s != "")
1569             precache_playermodel(s);
1570         s = autocvar_sv_defaultplayermodel;
1571         if (s != "")
1572             precache_playermodel(s);
1573     }
1574
1575     if (g_footsteps)
1576     {
1577         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1578         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1579     }
1580
1581     // gore and miscellaneous sounds
1582     //precache_sound ("misc/h2ohit.wav");
1583     precache_model ("models/hook.md3");
1584     precache_sound ("misc/armorimpact.wav");
1585     precache_sound ("misc/bodyimpact1.wav");
1586     precache_sound ("misc/bodyimpact2.wav");
1587     precache_sound ("misc/gib.wav");
1588     precache_sound ("misc/gib_splat01.wav");
1589     precache_sound ("misc/gib_splat02.wav");
1590     precache_sound ("misc/gib_splat03.wav");
1591     precache_sound ("misc/gib_splat04.wav");
1592     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1593     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1594     precache_sound ("misc/null.wav");
1595     precache_sound ("misc/spawn.wav");
1596     precache_sound ("misc/talk.wav");
1597     precache_sound ("misc/teleport.wav");
1598     precache_sound ("misc/poweroff.wav");
1599     precache_sound ("player/lava.wav");
1600     precache_sound ("player/slime.wav");
1601
1602     precache_model ("models/sprites/0.spr32");
1603     precache_model ("models/sprites/1.spr32");
1604     precache_model ("models/sprites/2.spr32");
1605     precache_model ("models/sprites/3.spr32");
1606     precache_model ("models/sprites/4.spr32");
1607     precache_model ("models/sprites/5.spr32");
1608     precache_model ("models/sprites/6.spr32");
1609     precache_model ("models/sprites/7.spr32");
1610     precache_model ("models/sprites/8.spr32");
1611     precache_model ("models/sprites/9.spr32");
1612     precache_model ("models/sprites/10.spr32");
1613
1614     // common weapon precaches
1615         precache_sound ("weapons/reload.wav"); // until weapons have individual reload sounds, precache the reload sound here
1616     precache_sound ("weapons/weapon_switch.wav");
1617     precache_sound ("weapons/weaponpickup.wav");
1618     precache_sound ("weapons/unavailable.wav");
1619     precache_sound ("weapons/dryfire.wav");
1620     if (g_grappling_hook)
1621     {
1622         precache_sound ("weapons/hook_fire.wav"); // hook
1623         precache_sound ("weapons/hook_impact.wav"); // hook
1624     }
1625
1626     if(autocvar_sv_precacheweapons)
1627     {
1628         //precache weapon models/sounds
1629         float wep;
1630         wep = WEP_FIRST;
1631         while (wep <= WEP_LAST)
1632         {
1633             weapon_action(wep, WR_PRECACHE);
1634             wep = wep + 1;
1635         }
1636     }
1637
1638     precache_model("models/elaser.mdl");
1639     precache_model("models/laser.mdl");
1640     precache_model("models/ebomb.mdl");
1641
1642 #if 0
1643     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1644
1645     if (!self.noise && self.music) // quake 3 uses the music field
1646         self.noise = self.music;
1647
1648     // plays music for the level if there is any
1649     if (self.noise)
1650     {
1651         precache_sound (self.noise);
1652         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1653     }
1654 #endif
1655 }
1656
1657 // sorry, but using \ in macros breaks line numbers
1658 #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
1659 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1660 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1661
1662
1663 void Send_CSQC_Centerprint_Generic(entity e, float id, string s, float duration, float countdown_num)
1664 {
1665         if ((clienttype(e) == CLIENTTYPE_REAL) && (e.flags & FL_CLIENT))
1666         {
1667                 msg_entity = e;
1668                 WRITESPECTATABLE_MSG_ONE({
1669                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1670                         WriteByte(MSG_ONE, TE_CSQC_CENTERPRINT_GENERIC);
1671                         WriteByte(MSG_ONE, id);
1672                         WriteString(MSG_ONE, s);
1673                         if (id != 0 && s != "")
1674                         {
1675                                 WriteByte(MSG_ONE, duration);
1676                                 WriteByte(MSG_ONE, countdown_num);
1677                         }
1678                 });
1679         }
1680 }
1681 void Send_CSQC_Centerprint_Generic_Expire(entity e, float id)
1682 {
1683         Send_CSQC_Centerprint_Generic(e, id, "", 1, 0);
1684 }
1685 // WARNING: this kills the trace globals
1686 #define EXACTTRIGGER_TOUCH if(WarpZoneLib_ExactTrigger_Touch()) return
1687 #define EXACTTRIGGER_INIT  WarpZoneLib_ExactTrigger_Init()
1688
1689 #define INITPRIO_FIRST              0
1690 #define INITPRIO_GAMETYPE           0
1691 #define INITPRIO_GAMETYPE_FALLBACK  1
1692 #define INITPRIO_FINDTARGET        10
1693 #define INITPRIO_DROPTOFLOOR       20
1694 #define INITPRIO_SETLOCATION       90
1695 #define INITPRIO_LINKDOORS         91
1696 #define INITPRIO_LAST              99
1697
1698 .void(void) initialize_entity;
1699 .float initialize_entity_order;
1700 .entity initialize_entity_next;
1701 entity initialize_entity_first;
1702
1703 void make_safe_for_remove(entity e)
1704 {
1705     if (e.initialize_entity)
1706     {
1707         entity ent, prev = world;
1708         for (ent = initialize_entity_first; ent; )
1709         {
1710             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1711             {
1712                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1713                 // skip it in linked list
1714                 if (prev)
1715                 {
1716                     prev.initialize_entity_next = ent.initialize_entity_next;
1717                     ent = prev.initialize_entity_next;
1718                 }
1719                 else
1720                 {
1721                     initialize_entity_first = ent.initialize_entity_next;
1722                     ent = initialize_entity_first;
1723                 }
1724             }
1725             else
1726             {
1727                 prev = ent;
1728                 ent = ent.initialize_entity_next;
1729             }
1730         }
1731     }
1732 }
1733
1734 void objerror(string s)
1735 {
1736     make_safe_for_remove(self);
1737     builtin_objerror(s);
1738 }
1739
1740 .float remove_except_protected_forbidden;
1741 void remove_except_protected(entity e)
1742 {
1743         if(e.remove_except_protected_forbidden)
1744                 error("not allowed to remove this at this point");
1745         builtin_remove(e);
1746 }
1747
1748 void remove_unsafely(entity e)
1749 {
1750     if(e.classname == "spike")
1751         error("Removing spikes is forbidden (crylink bug), please report");
1752     builtin_remove(e);
1753 }
1754
1755 void remove_safely(entity e)
1756 {
1757     make_safe_for_remove(e);
1758     builtin_remove(e);
1759 }
1760
1761 void InitializeEntity(entity e, void(void) func, float order)
1762 {
1763     entity prev, cur;
1764
1765     if (!e || e.initialize_entity)
1766     {
1767         // make a proxy initializer entity
1768         entity e_old;
1769         e_old = e;
1770         e = spawn();
1771         e.classname = "initialize_entity";
1772         e.enemy = e_old;
1773     }
1774
1775     e.initialize_entity = func;
1776     e.initialize_entity_order = order;
1777
1778     cur = initialize_entity_first;
1779     prev = world;
1780     for (;;)
1781     {
1782         if (!cur || cur.initialize_entity_order > order)
1783         {
1784             // insert between prev and cur
1785             if (prev)
1786                 prev.initialize_entity_next = e;
1787             else
1788                 initialize_entity_first = e;
1789             e.initialize_entity_next = cur;
1790             return;
1791         }
1792         prev = cur;
1793         cur = cur.initialize_entity_next;
1794     }
1795 }
1796 void InitializeEntitiesRun()
1797 {
1798     entity startoflist;
1799     startoflist = initialize_entity_first;
1800     initialize_entity_first = world;
1801     remove = remove_except_protected;
1802     for (self = startoflist; self; self = self.initialize_entity_next)
1803     {
1804         self.remove_except_protected_forbidden = 1;
1805     }
1806     for (self = startoflist; self; )
1807     {
1808         entity e;
1809         var void(void) func;
1810         e = self.initialize_entity_next;
1811         func = self.initialize_entity;
1812         self.initialize_entity_order = 0;
1813         self.initialize_entity = func_null;
1814         self.initialize_entity_next = world;
1815         self.remove_except_protected_forbidden = 0;
1816         if (self.classname == "initialize_entity")
1817         {
1818             entity e_old;
1819             e_old = self.enemy;
1820             builtin_remove(self);
1821             self = e_old;
1822         }
1823         //dprint("Delayed initialization: ", self.classname, "\n");
1824         if(func)
1825             func();
1826         else
1827         {
1828             eprint(self);
1829             backtrace(strcat("Null function in: ", self.classname, "\n"));
1830         }
1831         self = e;
1832     }
1833     remove = remove_unsafely;
1834 }
1835
1836 .float uncustomizeentityforclient_set;
1837 .void(void) uncustomizeentityforclient;
1838 void UncustomizeEntitiesRun()
1839 {
1840     entity oldself;
1841     oldself = self;
1842     for (self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1843         self.uncustomizeentityforclient();
1844     self = oldself;
1845 }
1846 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1847 {
1848     e.customizeentityforclient = customizer;
1849     e.uncustomizeentityforclient = uncustomizer;
1850     e.uncustomizeentityforclient_set = !!uncustomizer;
1851 }
1852
1853 .float nottargeted;
1854 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1855
1856 void() SUB_Remove;
1857 void Net_LinkEntity(entity e, float docull, float dt, float(entity, float) sendfunc)
1858 {
1859     vector mi, ma;
1860
1861     if (e.classname == "")
1862         e.classname = "net_linked";
1863
1864     if (e.model == "" || self.modelindex == 0)
1865     {
1866         mi = e.mins;
1867         ma = e.maxs;
1868         setmodel(e, "null");
1869         setsize(e, mi, ma);
1870     }
1871
1872     e.SendEntity = sendfunc;
1873     e.SendFlags = 0xFFFFFF;
1874
1875     if (!docull)
1876         e.effects |= EF_NODEPTHTEST;
1877
1878     if (dt)
1879     {
1880         e.nextthink = time + dt;
1881         e.think = SUB_Remove;
1882     }
1883 }
1884
1885 void adaptor_think2touch()
1886 {
1887     entity o;
1888     o = other;
1889     other = world;
1890     self.touch();
1891     other = o;
1892 }
1893
1894 void adaptor_think2use()
1895 {
1896     entity o, a;
1897     o = other;
1898     a = activator;
1899     activator = world;
1900     other = world;
1901     self.use();
1902     other = o;
1903     activator = a;
1904 }
1905
1906 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1907 {
1908         if not(self.flags & FL_ONGROUND) // if onground, we ARE touching something, but HITTYPE_SPLASH is to be networked if the damage causing projectile is not touching ANYTHING
1909                 self.projectiledeathtype |= HITTYPE_SPLASH;
1910         adaptor_think2use();
1911 }
1912
1913 // deferred dropping
1914 void DropToFloor_Handler()
1915 {
1916     builtin_droptofloor();
1917     self.dropped_origin = self.origin;
1918 }
1919
1920 void droptofloor()
1921 {
1922     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1923 }
1924
1925
1926
1927 float trace_hits_box_a0, trace_hits_box_a1;
1928
1929 float trace_hits_box_1d(float end, float thmi, float thma)
1930 {
1931     if (end == 0)
1932     {
1933         // just check if x is in range
1934         if (0 < thmi)
1935             return FALSE;
1936         if (0 > thma)
1937             return FALSE;
1938     }
1939     else
1940     {
1941         // do the trace with respect to x
1942         // 0 -> end has to stay in thmi -> thma
1943         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1944         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1945         if (trace_hits_box_a0 > trace_hits_box_a1)
1946             return FALSE;
1947     }
1948     return TRUE;
1949 }
1950
1951 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1952 {
1953     end -= start;
1954     thmi -= start;
1955     thma -= start;
1956     // now it is a trace from 0 to end
1957
1958     trace_hits_box_a0 = 0;
1959     trace_hits_box_a1 = 1;
1960
1961     if (!trace_hits_box_1d(end_x, thmi_x, thma_x))
1962         return FALSE;
1963     if (!trace_hits_box_1d(end_y, thmi_y, thma_y))
1964         return FALSE;
1965     if (!trace_hits_box_1d(end_z, thmi_z, thma_z))
1966         return FALSE;
1967
1968     return TRUE;
1969 }
1970
1971 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1972 {
1973     return trace_hits_box(start, end, thmi - ma, thma - mi);
1974 }
1975
1976 float SUB_NoImpactCheck()
1977 {
1978         // zero hitcontents = this is not the real impact, but either the
1979         // mirror-impact of something hitting the projectile instead of the
1980         // projectile hitting the something, or a touchareagrid one. Neither of
1981         // these stop the projectile from moving, so...
1982         if(trace_dphitcontents == 0)
1983         {
1984                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1985                 dprint(sprintf(_("A hit from a projectile happened with no hit contents! DEBUG THIS, this should never happen for projectiles! Profectile will self-destruct. (edict: %d, classname: %s, origin: %s)\n"), num_for_edict(self), self.classname, vtos(self.origin)));
1986                 checkclient();
1987         }
1988     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1989         return 1;
1990     if (other == world && self.size != '0 0 0')
1991     {
1992         vector tic;
1993         tic = self.velocity * sys_frametime;
1994         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1995         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1996         if (trace_fraction >= 1)
1997         {
1998             dprint("Odd... did not hit...?\n");
1999         }
2000         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
2001         {
2002             dprint("Detected and prevented the sky-grapple bug.\n");
2003             return 1;
2004         }
2005     }
2006
2007     return 0;
2008 }
2009
2010 #define SUB_OwnerCheck() (other && (other == self.owner))
2011
2012 void RemoveGrapplingHook(entity pl);
2013 void W_Crylink_Dequeue(entity e);
2014 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
2015 {
2016         if(SUB_OwnerCheck())
2017                 return TRUE;
2018         if(SUB_NoImpactCheck())
2019         {
2020                 if(self.classname == "grapplinghook")
2021                         RemoveGrapplingHook(self.realowner);
2022                 else if(self.classname == "spike")
2023                 {
2024                         W_Crylink_Dequeue(self);
2025                         remove(self);
2026                 }
2027                 else
2028                         remove(self);
2029                 return TRUE;
2030         }
2031         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
2032                 UpdateCSQCProjectile(self);
2033         return FALSE;
2034 }
2035 #define PROJECTILE_TOUCH if(WarpZone_Projectile_Touch()) return
2036
2037 #define ITEM_TOUCH_NEEDKILL() (((trace_dpstartcontents | trace_dphitcontents) & DPCONTENTS_NODROP) || (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY))
2038 #define ITEM_DAMAGE_NEEDKILL(dt) (((dt) == DEATH_HURTTRIGGER) || ((dt) == DEATH_SLIME) || ((dt) == DEATH_LAVA) || ((dt) == DEATH_SWAMP))
2039
2040 void URI_Get_Callback(float id, float status, string data)
2041 {
2042         if(url_URI_Get_Callback(id, status, data))
2043         {
2044                 // handled
2045         }
2046         else if (id == URI_GET_DISCARD)
2047         {
2048                 // discard
2049         }
2050         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
2051         {
2052                 // sv_cmd curl
2053                 Curl_URI_Get_Callback(id, status, data);
2054         }
2055         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
2056         {
2057                 // online ban list
2058                 OnlineBanList_URI_Get_Callback(id, status, data);
2059         }
2060         else
2061         {
2062                 print("Received HTTP request data for an invalid id ", ftos(id), ".\n");
2063         }
2064 }
2065
2066 string uid2name(string myuid) {
2067         string s;
2068         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
2069
2070         // FIXME remove this later after 0.6 release
2071         // convert old style broken records to correct style
2072         if(s == "")
2073         {
2074                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
2075                 if(s != "")
2076                 {
2077                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
2078                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
2079                 }
2080         }
2081         
2082         if(s == "")
2083                 s = "^1Unregistered Player";
2084         return s;
2085 }
2086
2087 float race_readTime(string map, float pos)
2088 {
2089         string rr;
2090         if(g_cts)
2091                 rr = CTS_RECORD;
2092         else
2093                 rr = RACE_RECORD;
2094
2095         return stof(db_get(ServerProgsDB, strcat(map, rr, "time", ftos(pos))));
2096 }
2097
2098 string race_readUID(string map, float pos)
2099 {
2100         string rr;
2101         if(g_cts)
2102                 rr = CTS_RECORD;
2103         else
2104                 rr = RACE_RECORD;
2105
2106         return db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos)));
2107 }
2108
2109 float race_readPos(string map, float t) {
2110         float i;
2111         for (i = 1; i <= RANKINGS_CNT; ++i)
2112                 if (race_readTime(map, i) == 0 || race_readTime(map, i) > t)
2113                         return i;
2114
2115         return 0; // pos is zero if unranked
2116 }
2117
2118 void race_writeTime(string map, float t, string myuid)
2119 {
2120         string rr;
2121         if(g_cts)
2122                 rr = CTS_RECORD;
2123         else
2124                 rr = RACE_RECORD;
2125
2126         float newpos;
2127         newpos = race_readPos(map, t);
2128
2129         float i, prevpos = 0;
2130         for(i = 1; i <= RANKINGS_CNT; ++i)
2131         {
2132                 if(race_readUID(map, i) == myuid)
2133                         prevpos = i;
2134         }
2135         if (prevpos) { // player improved his existing record, only have to iterate on ranks between new and old recs
2136                 for (i = prevpos; i > newpos; --i) {
2137                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2138                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2139                 }
2140         } else { // player has no ranked record yet
2141                 for (i = RANKINGS_CNT; i > newpos; --i) {
2142                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2143                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2144                 }
2145         }
2146
2147         // store new time itself
2148         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(newpos)), ftos(t));
2149         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(newpos)), myuid);
2150 }
2151
2152 string race_readName(string map, float pos)
2153 {
2154         string rr;
2155         if(g_cts)
2156                 rr = CTS_RECORD;
2157         else
2158                 rr = RACE_RECORD;
2159
2160         return uid2name(db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos))));
2161 }
2162
2163 string race_placeName(float pos) {
2164         if(floor((mod(pos, 100))/10) * 10 != 10) // examples: 12th, 111th, 213th will not execute this block
2165         {
2166                 if(mod(pos, 10) == 1)
2167                         return strcat(ftos(pos), "st");
2168                 else if(mod(pos, 10) == 2)
2169                         return strcat(ftos(pos), "nd");
2170                 else if(mod(pos, 10) == 3)
2171                         return strcat(ftos(pos), "rd");
2172                 else
2173                         return strcat(ftos(pos), "th");
2174         }
2175         else
2176                 return strcat(ftos(pos), "th");
2177 }
2178
2179 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
2180 {
2181     float m, i;
2182     vector start, org, delta, end, enddown, mstart;
2183     entity sp;
2184
2185     m = e.dphitcontentsmask;
2186     e.dphitcontentsmask = goodcontents | badcontents;
2187
2188     org = world.mins;
2189     delta = world.maxs - world.mins;
2190
2191     start = end = org;
2192
2193     for (i = 0; i < attempts; ++i)
2194     {
2195         start_x = org_x + random() * delta_x;
2196         start_y = org_y + random() * delta_y;
2197         start_z = org_z + random() * delta_z;
2198
2199         // rule 1: start inside world bounds, and outside
2200         // solid, and don't start from somewhere where you can
2201         // fall down to evil
2202         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta_z, MOVE_NORMAL, e);
2203         if (trace_fraction >= 1)
2204             continue;
2205         if (trace_startsolid)
2206             continue;
2207         if (trace_dphitcontents & badcontents)
2208             continue;
2209         if (trace_dphitq3surfaceflags & badsurfaceflags)
2210             continue;
2211
2212         // rule 2: if we are too high, lower the point
2213         if (trace_fraction * delta_z > maxaboveground)
2214             start = trace_endpos + '0 0 1' * maxaboveground;
2215         enddown = trace_endpos;
2216
2217         // rule 3: make sure we aren't outside the map. This only works
2218         // for somewhat well formed maps. A good rule of thumb is that
2219         // the map should have a convex outside hull.
2220         // these can be traceLINES as we already verified the starting box
2221         mstart = start + 0.5 * (e.mins + e.maxs);
2222         traceline(mstart, mstart + '1 0 0' * delta_x, MOVE_NORMAL, e);
2223         if (trace_fraction >= 1)
2224             continue;
2225         traceline(mstart, mstart - '1 0 0' * delta_x, MOVE_NORMAL, e);
2226         if (trace_fraction >= 1)
2227             continue;
2228         traceline(mstart, mstart + '0 1 0' * delta_y, MOVE_NORMAL, e);
2229         if (trace_fraction >= 1)
2230             continue;
2231         traceline(mstart, mstart - '0 1 0' * delta_y, MOVE_NORMAL, e);
2232         if (trace_fraction >= 1)
2233             continue;
2234         traceline(mstart, mstart + '0 0 1' * delta_z, MOVE_NORMAL, e);
2235         if (trace_fraction >= 1)
2236             continue;
2237
2238         // rule 4: we must "see" some spawnpoint
2239         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
2240                 if(checkpvs(mstart, sp))
2241                         break;
2242         if(!sp)
2243         {
2244                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
2245                         if(checkpvs(mstart, sp))
2246                                 break;
2247                 if(!sp)
2248                         continue;
2249         }
2250
2251         // find a random vector to "look at"
2252         end_x = org_x + random() * delta_x;
2253         end_y = org_y + random() * delta_y;
2254         end_z = org_z + random() * delta_z;
2255         end = start + normalize(end - start) * vlen(delta);
2256
2257         // rule 4: start TO end must not be too short
2258         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
2259         if (trace_startsolid)
2260             continue;
2261         if (trace_fraction < minviewdistance / vlen(delta))
2262             continue;
2263
2264         // rule 5: don't want to look at sky
2265         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
2266             continue;
2267
2268         // rule 6: we must not end up in trigger_hurt
2269         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
2270             continue;
2271
2272         break;
2273     }
2274
2275     e.dphitcontentsmask = m;
2276
2277     if (i < attempts)
2278     {
2279         setorigin(e, start);
2280         e.angles = vectoangles(end - start);
2281         dprint("Needed ", ftos(i + 1), " attempts\n");
2282         return TRUE;
2283     }
2284     else
2285         return FALSE;
2286 }
2287
2288 float zcurveparticles_effectno;
2289 vector zcurveparticles_start;
2290 float zcurveparticles_spd;
2291
2292 void endzcurveparticles()
2293 {
2294         if(zcurveparticles_effectno)
2295         {
2296                 // terminator
2297                 WriteShort(MSG_BROADCAST, zcurveparticles_spd | 0x8000);
2298         }
2299         zcurveparticles_effectno = 0;
2300 }
2301
2302 void zcurveparticles(float effectno, vector start, vector end, float end_dz, float spd)
2303 {
2304         spd = bound(0, floor(spd / 16), 32767);
2305         if(effectno != zcurveparticles_effectno || start != zcurveparticles_start)
2306         {
2307                 endzcurveparticles();
2308                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
2309                 WriteByte(MSG_BROADCAST, TE_CSQC_ZCURVEPARTICLES);
2310                 WriteShort(MSG_BROADCAST, effectno);
2311                 WriteCoord(MSG_BROADCAST, start_x);
2312                 WriteCoord(MSG_BROADCAST, start_y);
2313                 WriteCoord(MSG_BROADCAST, start_z);
2314                 zcurveparticles_effectno = effectno;
2315                 zcurveparticles_start = start;
2316         }
2317         else
2318                 WriteShort(MSG_BROADCAST, zcurveparticles_spd);
2319         WriteCoord(MSG_BROADCAST, end_x);
2320         WriteCoord(MSG_BROADCAST, end_y);
2321         WriteCoord(MSG_BROADCAST, end_z);
2322         WriteCoord(MSG_BROADCAST, end_dz);
2323         zcurveparticles_spd = spd;
2324 }
2325
2326 void zcurveparticles_from_tracetoss(float effectno, vector start, vector end, vector vel)
2327 {
2328         float end_dz;
2329         vector vecxy, velxy;
2330
2331         vecxy = end - start;
2332         vecxy_z = 0;
2333         velxy = vel;
2334         velxy_z = 0;
2335
2336         if (vlen(velxy) < 0.000001 * fabs(vel_z))
2337         {
2338                 endzcurveparticles();
2339                 trailparticles(world, effectno, start, end);
2340                 return;
2341         }
2342
2343         end_dz = vlen(vecxy) / vlen(velxy) * vel_z - (end_z - start_z);
2344         zcurveparticles(effectno, start, end, end_dz, vlen(vel));
2345 }
2346
2347 void write_recordmarker(entity pl, float tstart, float dt)
2348 {
2349     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
2350
2351     // also write a marker into demo files for demotc-race-record-extractor to find
2352     stuffcmd(pl,
2353              strcat(
2354                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
2355                  " ", ftos(tstart), " ", ftos(dt), "\n"));
2356 }
2357
2358 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float allowcenter, float algn)
2359 {
2360         switch(algn)
2361         {
2362                 default:
2363                 case 3: // right
2364                         break;
2365
2366                 case 4: // left
2367                         vecs_y = -vecs_y;
2368                         break;
2369
2370                 case 1:
2371                         if(allowcenter) // 2: allow center handedness
2372                         {
2373                                 // center
2374                                 vecs_y = 0;
2375                                 vecs_z -= 2;
2376                         }
2377                         else
2378                         {
2379                                 // right
2380                         }
2381                         break;
2382
2383                 case 2:
2384                         if(allowcenter) // 2: allow center handedness
2385                         {
2386                                 // center
2387                                 vecs_y = 0;
2388                                 vecs_z -= 2;
2389                         }
2390                         else
2391                         {
2392                                 // left
2393                                 vecs_y = -vecs_y;
2394                         }
2395                         break;
2396         }
2397         return vecs;
2398 }
2399
2400 vector shotorg_adjust_values(vector vecs, float y_is_right, float visual, float algn)
2401 {
2402         string s;
2403         vector v;
2404
2405         if (autocvar_g_shootfromeye)
2406         {
2407                 if (visual)
2408                 {
2409                         if (autocvar_g_shootfromclient) { vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn); }
2410                         else { vecs_y = 0; vecs_z -= 2; }
2411                 }
2412                 else
2413                 {
2414                         vecs_y = 0;
2415                         vecs_z = 0;
2416                 }
2417         }
2418         else if (autocvar_g_shootfromcenter)
2419         {
2420                 vecs_y = 0;
2421                 vecs_z -= 2;
2422         }
2423         else if ((s = autocvar_g_shootfromfixedorigin) != "")
2424         {
2425                 v = stov(s);
2426                 if (y_is_right)
2427                         v_y = -v_y;
2428                 if (v_x != 0)
2429                         vecs_x = v_x;
2430                 vecs_y = v_y;
2431                 vecs_z = v_z;
2432         }
2433         else if (autocvar_g_shootfromclient)
2434         {
2435                 vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn);
2436         }
2437         return vecs;
2438 }
2439
2440 vector shotorg_adjust(vector vecs, float y_is_right, float visual)
2441 {
2442         return shotorg_adjust_values(vecs, y_is_right, visual, self.owner.cvar_cl_gunalign);
2443 }
2444
2445
2446 void attach_sameorigin(entity e, entity to, string tag)
2447 {
2448     vector org, t_forward, t_left, t_up, e_forward, e_up;
2449     float tagscale;
2450
2451     org = e.origin - gettaginfo(to, gettagindex(to, tag));
2452     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
2453     t_forward = v_forward * tagscale;
2454     t_left = v_right * -tagscale;
2455     t_up = v_up * tagscale;
2456
2457     e.origin_x = org * t_forward;
2458     e.origin_y = org * t_left;
2459     e.origin_z = org * t_up;
2460
2461     // current forward and up directions
2462     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2463                 e.angles = AnglesTransform_FromVAngles(e.angles);
2464         else
2465                 e.angles = AnglesTransform_FromAngles(e.angles);
2466     fixedmakevectors(e.angles);
2467
2468     // untransform forward, up!
2469     e_forward_x = v_forward * t_forward;
2470     e_forward_y = v_forward * t_left;
2471     e_forward_z = v_forward * t_up;
2472     e_up_x = v_up * t_forward;
2473     e_up_y = v_up * t_left;
2474     e_up_z = v_up * t_up;
2475
2476     e.angles = fixedvectoangles2(e_forward, e_up);
2477     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2478                 e.angles = AnglesTransform_ToVAngles(e.angles);
2479         else
2480                 e.angles = AnglesTransform_ToAngles(e.angles);
2481
2482     setattachment(e, to, tag);
2483     setorigin(e, e.origin);
2484 }
2485
2486 void detach_sameorigin(entity e)
2487 {
2488     vector org;
2489     org = gettaginfo(e, 0);
2490     e.angles = fixedvectoangles2(v_forward, v_up);
2491     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2492                 e.angles = AnglesTransform_ToVAngles(e.angles);
2493         else
2494                 e.angles = AnglesTransform_ToAngles(e.angles);
2495     setorigin(e, org);
2496     setattachment(e, world, "");
2497     setorigin(e, e.origin);
2498 }
2499
2500 void follow_sameorigin(entity e, entity to)
2501 {
2502     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
2503     e.aiment = to; // make the hole follow bmodel
2504     e.punchangle = to.angles; // the original angles of bmodel
2505     e.view_ofs = e.origin - to.origin; // relative origin
2506     e.v_angle = e.angles - to.angles; // relative angles
2507 }
2508
2509 void unfollow_sameorigin(entity e)
2510 {
2511     e.movetype = MOVETYPE_NONE;
2512 }
2513
2514 entity gettaginfo_relative_ent;
2515 vector gettaginfo_relative(entity e, float tag)
2516 {
2517     if (!gettaginfo_relative_ent)
2518     {
2519         gettaginfo_relative_ent = spawn();
2520         gettaginfo_relative_ent.effects = EF_NODRAW;
2521     }
2522     gettaginfo_relative_ent.model = e.model;
2523     gettaginfo_relative_ent.modelindex = e.modelindex;
2524     gettaginfo_relative_ent.frame = e.frame;
2525     return gettaginfo(gettaginfo_relative_ent, tag);
2526 }
2527
2528 void SoundEntity_StartSound(entity pl, float chan, string samp, float vol, float attn)
2529 {
2530     float p;
2531     p = pow(2, chan);
2532     if (pl.soundentity.cnt & p)
2533         return;
2534     soundtoat(MSG_ALL, pl.soundentity, gettaginfo(pl.soundentity, 0), chan, samp, vol, attn);
2535     pl.soundentity.cnt |= p;
2536 }
2537
2538 void SoundEntity_StopSound(entity pl, float chan)
2539 {
2540     float p;
2541     p = pow(2, chan);
2542     if (pl.soundentity.cnt & p)
2543     {
2544         stopsoundto(MSG_ALL, pl.soundentity, chan);
2545         pl.soundentity.cnt &~= p;
2546     }
2547 }
2548
2549 void SoundEntity_Attach(entity pl)
2550 {
2551     pl.soundentity = spawn();
2552     pl.soundentity.classname = "soundentity";
2553     pl.soundentity.owner = pl;
2554     setattachment(pl.soundentity, pl, "");
2555     setmodel(pl.soundentity, "null");
2556 }
2557
2558 void SoundEntity_Detach(entity pl)
2559 {
2560     float i;
2561     for (i = 0; i <= 7; ++i)
2562         SoundEntity_StopSound(pl, i);
2563 }
2564
2565 .float scale2;
2566
2567 float modeleffect_SendEntity(entity to, float sf)
2568 {
2569         float f;
2570         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
2571
2572         f = 0;
2573         if(self.velocity != '0 0 0')
2574                 f |= 1;
2575         if(self.angles != '0 0 0')
2576                 f |= 2;
2577         if(self.avelocity != '0 0 0')
2578                 f |= 4;
2579
2580         WriteByte(MSG_ENTITY, f);
2581         WriteShort(MSG_ENTITY, self.modelindex);
2582         WriteByte(MSG_ENTITY, self.skin);
2583         WriteByte(MSG_ENTITY, self.frame);
2584         WriteCoord(MSG_ENTITY, self.origin_x);
2585         WriteCoord(MSG_ENTITY, self.origin_y);
2586         WriteCoord(MSG_ENTITY, self.origin_z);
2587         if(f & 1)
2588         {
2589                 WriteCoord(MSG_ENTITY, self.velocity_x);
2590                 WriteCoord(MSG_ENTITY, self.velocity_y);
2591                 WriteCoord(MSG_ENTITY, self.velocity_z);
2592         }
2593         if(f & 2)
2594         {
2595                 WriteCoord(MSG_ENTITY, self.angles_x);
2596                 WriteCoord(MSG_ENTITY, self.angles_y);
2597                 WriteCoord(MSG_ENTITY, self.angles_z);
2598         }
2599         if(f & 4)
2600         {
2601                 WriteCoord(MSG_ENTITY, self.avelocity_x);
2602                 WriteCoord(MSG_ENTITY, self.avelocity_y);
2603                 WriteCoord(MSG_ENTITY, self.avelocity_z);
2604         }
2605         WriteShort(MSG_ENTITY, self.scale * 256.0);
2606         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
2607         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
2608         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
2609         WriteByte(MSG_ENTITY, self.alpha * 255.0);
2610
2611         return TRUE;
2612 }
2613
2614 void modeleffect_spawn(string m, float s, float f, vector o, vector v, vector ang, vector angv, float s0, float s2, float a, float t1, float t2)
2615 {
2616         entity e;
2617         float sz;
2618         e = spawn();
2619         e.classname = "modeleffect";
2620         setmodel(e, m);
2621         e.frame = f;
2622         setorigin(e, o);
2623         e.velocity = v;
2624         e.angles = ang;
2625         e.avelocity = angv;
2626         e.alpha = a;
2627         e.teleport_time = t1;
2628         e.fade_time = t2;
2629         e.skin = s;
2630         if(s0 >= 0)
2631                 e.scale = s0 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2632         else
2633                 e.scale = -s0;
2634         if(s2 >= 0)
2635                 e.scale2 = s2 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2636         else
2637                 e.scale2 = -s2;
2638         sz = max(e.scale, e.scale2);
2639         setsize(e, e.mins * sz, e.maxs * sz);
2640         Net_LinkEntity(e, FALSE, 0.1, modeleffect_SendEntity);
2641 }
2642
2643 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
2644 {
2645         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
2646 }
2647
2648 float randombit(float bits)
2649 {
2650         if not(bits & (bits-1)) // this ONLY holds for powers of two!
2651                 return bits;
2652
2653         float n, f, b, r;
2654
2655         r = random();
2656         b = 0;
2657         n = 0;
2658
2659         for(f = 1; f <= bits; f *= 2)
2660         {
2661                 if(bits & f)
2662                 {
2663                         ++n;
2664                         r *= n;
2665                         if(r <= 1)
2666                                 b = f;
2667                         else
2668                                 r = (r - 1) / (n - 1);
2669                 }
2670         }
2671
2672         return b;
2673 }
2674
2675 float randombits(float bits, float k, float error_return)
2676 {
2677         float r;
2678         r = 0;
2679         while(k > 0 && bits != r)
2680         {
2681                 r += randombit(bits - r);
2682                 --k;
2683         }
2684         if(error_return)
2685                 if(k > 0)
2686                         return -1; // all
2687         return r;
2688 }
2689
2690 void randombit_test(float bits, float iter)
2691 {
2692         while(iter > 0)
2693         {
2694                 print(ftos(randombit(bits)), "\n");
2695                 --iter;
2696         }
2697 }
2698
2699 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
2700 {
2701         if(halflifedist > 0)
2702                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
2703         else if(halflifedist < 0)
2704                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
2705         else
2706                 return 1;
2707 }
2708
2709
2710
2711
2712 #ifdef RELEASE
2713 #define cvar_string_normal builtin_cvar_string
2714 #define cvar_normal builtin_cvar
2715 #else
2716 string cvar_string_normal(string n)
2717 {
2718         if not(cvar_type(n) & 1)
2719                 backtrace(strcat("Attempt to access undefined cvar: ", n));
2720         return builtin_cvar_string(n);
2721 }
2722
2723 float cvar_normal(string n)
2724 {
2725         return stof(cvar_string_normal(n));
2726 }
2727 #endif
2728 #define cvar_set_normal builtin_cvar_set
2729
2730 void defer_think()
2731 {
2732     entity oself;
2733
2734     oself           = self;
2735     self            = self.owner;
2736     oself.think     = SUB_Remove;
2737     oself.nextthink = time;
2738
2739     oself.use();
2740 }
2741
2742 /*
2743     Execute func() after time + fdelay.
2744     self when func is executed = self when defer is called
2745 */
2746 void defer(float fdelay, void() func)
2747 {
2748     entity e;
2749
2750     e           = spawn();
2751     e.owner     = self;
2752     e.use       = func;
2753     e.think     = defer_think;
2754     e.nextthink = time + fdelay;
2755 }
2756
2757 .string aiment_classname;
2758 .float aiment_deadflag;
2759 void SetMovetypeFollow(entity ent, entity e)
2760 {
2761         // FIXME this may not be warpzone aware
2762         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
2763         ent.solid = SOLID_NOT; // MOVETYPE_FOLLOW is always non-solid - this means this cannot be teleported by warpzones any more! Instead, we must notice when our owner gets teleported.
2764         ent.aiment = e; // make the hole follow bmodel
2765         ent.punchangle = e.angles; // the original angles of bmodel
2766         ent.view_ofs = ent.origin - e.origin; // relative origin
2767         ent.v_angle = ent.angles - e.angles; // relative angles
2768         ent.aiment_classname = strzone(e.classname);
2769         ent.aiment_deadflag = e.deadflag;
2770 }
2771 void UnsetMovetypeFollow(entity ent)
2772 {
2773         ent.movetype = MOVETYPE_FLY;
2774         PROJECTILE_MAKETRIGGER(ent);
2775         ent.aiment = world;
2776 }
2777 float LostMovetypeFollow(entity ent)
2778 {
2779 /*
2780         if(ent.movetype != MOVETYPE_FOLLOW)
2781                 if(ent.aiment)
2782                         error("???");
2783 */
2784         if(ent.aiment)
2785         {
2786                 if(ent.aiment.classname != ent.aiment_classname)
2787                         return 1;
2788                 if(ent.aiment.deadflag != ent.aiment_deadflag)
2789                         return 1;
2790         }
2791         return 0;
2792 }
2793
2794 float isPushable(entity e)
2795 {
2796         if(e.iscreature)
2797                 return TRUE;
2798         if(e.pushable)
2799                 return TRUE;
2800         switch(e.classname)
2801         {
2802                 case "body":
2803                 case "droppedweapon":
2804                 case "keepawayball":
2805                 case "nexball_basketball":
2806                 case "nexball_football":
2807                         return TRUE;
2808                 case "bullet": // antilagged bullets can't hit this either
2809                         return FALSE;
2810         }
2811         if (e.projectiledeathtype)
2812                 return TRUE;
2813         return FALSE;
2814 }