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