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