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