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