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