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