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