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