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