]> de.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
1073         if(cvar("sv_allow_fullbright"))
1074                 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
1075
1076     g_bugrigs = cvar("g_bugrigs");
1077     g_bugrigs_planar_movement = cvar("g_bugrigs_planar_movement");
1078     g_bugrigs_planar_movement_car_jumping = cvar("g_bugrigs_planar_movement_car_jumping");
1079     g_bugrigs_reverse_spinning = cvar("g_bugrigs_reverse_spinning");
1080     g_bugrigs_reverse_speeding = cvar("g_bugrigs_reverse_speeding");
1081     g_bugrigs_reverse_stopping = cvar("g_bugrigs_reverse_stopping");
1082     g_bugrigs_air_steering = cvar("g_bugrigs_air_steering");
1083     g_bugrigs_angle_smoothing = cvar("g_bugrigs_angle_smoothing");
1084     g_bugrigs_friction_floor = cvar("g_bugrigs_friction_floor");
1085     g_bugrigs_friction_brake = cvar("g_bugrigs_friction_brake");
1086     g_bugrigs_friction_air = cvar("g_bugrigs_friction_air");
1087     g_bugrigs_accel = cvar("g_bugrigs_accel");
1088     g_bugrigs_speed_ref = cvar("g_bugrigs_speed_ref");
1089     g_bugrigs_speed_pow = cvar("g_bugrigs_speed_pow");
1090     g_bugrigs_steer = cvar("g_bugrigs_steer");
1091
1092     g_touchexplode = cvar("g_touchexplode");
1093     g_touchexplode_radius = cvar("g_touchexplode_radius");
1094     g_touchexplode_damage = cvar("g_touchexplode_damage");
1095     g_touchexplode_edgedamage = cvar("g_touchexplode_edgedamage");
1096     g_touchexplode_force = cvar("g_touchexplode_force");
1097
1098 #ifdef ALLOW_FORCEMODELS
1099         sv_clforceplayermodels = cvar("sv_clforceplayermodels");
1100 #endif
1101
1102         sv_clones = cvar("sv_clones");
1103         sv_gentle = cvar("sv_gentle");
1104         sv_foginterval = cvar("sv_foginterval");
1105         g_cloaked = cvar("g_cloaked");
1106     if(g_cts)
1107         g_cloaked = 1; // always enable cloak in CTS
1108         g_jump_grunt = cvar("g_jump_grunt");
1109         g_footsteps = cvar("g_footsteps");
1110         g_grappling_hook = cvar("g_grappling_hook");
1111         g_jetpack = cvar("g_jetpack");
1112         g_midair = cvar("g_midair");
1113         g_minstagib = cvar("g_minstagib");
1114         g_norecoil = cvar("g_norecoil");
1115         g_bloodloss = cvar("g_bloodloss");
1116         sv_maxidle = cvar("sv_maxidle");
1117         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
1118         g_ctf_reverse = cvar("g_ctf_reverse");
1119         sv_autotaunt = cvar("sv_autotaunt");
1120         sv_taunt = cvar("sv_taunt");
1121
1122         inWarmupStage = cvar("g_warmup");
1123         g_warmup_limit = cvar("g_warmup_limit");
1124         g_warmup_allguns = cvar("g_warmup_allguns");
1125         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
1126
1127         if ((g_race && g_race_qualifying == 2) || g_runematch || g_arena || g_assault || cvar("g_campaign"))
1128                 inWarmupStage = 0; // these modes cannot work together, sorry
1129
1130         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
1131         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
1132         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
1133         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
1134         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
1135         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
1136         g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
1137         g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
1138         g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
1139         g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
1140         g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
1141         g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
1142
1143         g_weaponspeedfactor = cvar("g_weaponspeedfactor");
1144         g_weaponratefactor = cvar("g_weaponratefactor");
1145         g_weapondamagefactor = cvar("g_weapondamagefactor");
1146         g_weaponforcefactor = cvar("g_weaponforcefactor");
1147         g_weaponspreadfactor = cvar("g_weaponspreadfactor");
1148
1149         g_pickup_shells = cvar("g_pickup_shells");
1150         g_pickup_shells_max = cvar("g_pickup_shells_max");
1151         g_pickup_nails = cvar("g_pickup_nails");
1152         g_pickup_nails_max = cvar("g_pickup_nails_max");
1153         g_pickup_rockets = cvar("g_pickup_rockets");
1154         g_pickup_rockets_max = cvar("g_pickup_rockets_max");
1155         g_pickup_cells = cvar("g_pickup_cells");
1156         g_pickup_cells_max = cvar("g_pickup_cells_max");
1157         g_pickup_fuel = cvar("g_pickup_fuel");
1158         g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
1159         g_pickup_fuel_max = cvar("g_pickup_fuel_max");
1160         g_pickup_armorsmall = cvar("g_pickup_armorsmall");
1161         g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
1162         g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
1163         g_pickup_armormedium = cvar("g_pickup_armormedium");
1164         g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
1165         g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
1166         g_pickup_armorbig = cvar("g_pickup_armorbig");
1167         g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
1168         g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
1169         g_pickup_armorlarge = cvar("g_pickup_armorlarge");
1170         g_pickup_armorlarge_max = cvar("g_pickup_armorlarge_max");
1171         g_pickup_armorlarge_anyway = cvar("g_pickup_armorlarge_anyway");
1172         g_pickup_healthsmall = cvar("g_pickup_healthsmall");
1173         g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
1174         g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
1175         g_pickup_healthmedium = cvar("g_pickup_healthmedium");
1176         g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
1177         g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
1178         g_pickup_healthlarge = cvar("g_pickup_healthlarge");
1179         g_pickup_healthlarge_max = cvar("g_pickup_healthlarge_max");
1180         g_pickup_healthlarge_anyway = cvar("g_pickup_healthlarge_anyway");
1181         g_pickup_healthmega = cvar("g_pickup_healthmega");
1182         g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
1183         g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
1184
1185         g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
1186         g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
1187
1188         g_pinata = cvar("g_pinata");
1189
1190     g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
1191     if(!g_weapon_stay)
1192         g_weapon_stay = cvar("g_weapon_stay");
1193
1194         g_ghost_items = cvar("g_ghost_items");
1195
1196         if(g_ghost_items >= 1)
1197                 g_ghost_items = 0.25; // default alpha value
1198
1199         if not(inWarmupStage && !g_ca)
1200                 game_starttime = cvar("g_start_delay");
1201
1202         sv_pitch_min = cvar("sv_pitch_min");
1203         sv_pitch_max = cvar("sv_pitch_max");
1204         sv_pitch_fixyaw = cvar("sv_pitch_fixyaw");
1205
1206         readplayerstartcvars();
1207 }
1208
1209 //#NO AUTOCVARS END
1210
1211 // Sound functions
1212 string precache_sound (string s) = #19;
1213 float precache_sound_index (string s) = #19;
1214
1215 #define SND_VOLUME      1
1216 #define SND_ATTENUATION 2
1217 #define SND_LARGEENTITY 8
1218 #define SND_LARGESOUND  16
1219
1220 float sound_allowed(float dest, entity e)
1221 {
1222     // sounds from world may always pass
1223     for (;;)
1224     {
1225         if (e.classname == "body")
1226             e = e.enemy;
1227         else if (e.realowner && e.realowner != e)
1228             e = e.realowner;
1229         else if (e.owner && e.owner != e)
1230             e = e.owner;
1231         else
1232             break;
1233     }
1234     // sounds to self may always pass
1235     if (dest == MSG_ONE)
1236         if (e == msg_entity)
1237             return TRUE;
1238     // sounds by players can be removed
1239     if (autocvar_bot_sound_monopoly)
1240         if (clienttype(e) == CLIENTTYPE_REAL)
1241             return FALSE;
1242     // anything else may pass
1243     return TRUE;
1244 }
1245
1246 #ifdef COMPAT_XON010_CHANNELS
1247 void(entity e, float chan, string samp, float vol, float atten) builtin_sound = #8;
1248 void sound(entity e, float chan, string samp, float vol, float atten)
1249 {
1250     if (!sound_allowed(MSG_BROADCAST, e))
1251         return;
1252     builtin_sound(e, chan, samp, vol, atten);
1253 }
1254 #else
1255 #undef sound
1256 void sound(entity e, float chan, string samp, float vol, float atten)
1257 {
1258     if (!sound_allowed(MSG_BROADCAST, e))
1259         return;
1260     sound7(e, chan, samp, vol, atten, 0, 0);
1261 }
1262 #endif
1263
1264 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
1265 {
1266     float entno, idx;
1267
1268     if (!sound_allowed(dest, e))
1269         return;
1270
1271     entno = num_for_edict(e);
1272     idx = precache_sound_index(samp);
1273
1274     float sflags;
1275     sflags = 0;
1276
1277     atten = floor(atten * 64);
1278     vol = floor(vol * 255);
1279
1280     if (vol != 255)
1281         sflags |= SND_VOLUME;
1282     if (atten != 64)
1283         sflags |= SND_ATTENUATION;
1284     if (entno >= 8192 || chan < 0 || chan > 7)
1285         sflags |= SND_LARGEENTITY;
1286     if (idx >= 256)
1287         sflags |= SND_LARGESOUND;
1288
1289     WriteByte(dest, SVC_SOUND);
1290     WriteByte(dest, sflags);
1291     if (sflags & SND_VOLUME)
1292         WriteByte(dest, vol);
1293     if (sflags & SND_ATTENUATION)
1294         WriteByte(dest, atten);
1295     if (sflags & SND_LARGEENTITY)
1296     {
1297         WriteShort(dest, entno);
1298         WriteByte(dest, chan);
1299     }
1300     else
1301     {
1302         WriteShort(dest, entno * 8 + chan);
1303     }
1304     if (sflags & SND_LARGESOUND)
1305         WriteShort(dest, idx);
1306     else
1307         WriteByte(dest, idx);
1308
1309     WriteCoord(dest, o_x);
1310     WriteCoord(dest, o_y);
1311     WriteCoord(dest, o_z);
1312 }
1313 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1314 {
1315     vector o;
1316
1317     if (!sound_allowed(dest, e))
1318         return;
1319
1320     o = e.origin + 0.5 * (e.mins + e.maxs);
1321     soundtoat(dest, e, o, chan, samp, vol, atten);
1322 }
1323 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1324 {
1325     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, atten);
1326 }
1327 void stopsoundto(float dest, entity e, float chan)
1328 {
1329     float entno;
1330
1331     if (!sound_allowed(dest, e))
1332         return;
1333
1334     entno = num_for_edict(e);
1335
1336     if (entno >= 8192 || chan < 0 || chan > 7)
1337     {
1338         float idx, sflags;
1339         idx = precache_sound_index("misc/null.wav");
1340         sflags = SND_LARGEENTITY;
1341         if (idx >= 256)
1342             sflags |= SND_LARGESOUND;
1343         WriteByte(dest, SVC_SOUND);
1344         WriteByte(dest, sflags);
1345         WriteShort(dest, entno);
1346         WriteByte(dest, chan);
1347         if (sflags & SND_LARGESOUND)
1348             WriteShort(dest, idx);
1349         else
1350             WriteByte(dest, idx);
1351         WriteCoord(dest, e.origin_x);
1352         WriteCoord(dest, e.origin_y);
1353         WriteCoord(dest, e.origin_z);
1354     }
1355     else
1356     {
1357         WriteByte(dest, SVC_STOPSOUND);
1358         WriteShort(dest, entno * 8 + chan);
1359     }
1360 }
1361 void stopsound(entity e, float chan)
1362 {
1363     if (!sound_allowed(MSG_BROADCAST, e))
1364         return;
1365
1366     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
1367     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
1368 }
1369
1370 void play2(entity e, string filename)
1371 {
1372     //stuffcmd(e, strcat("play2 ", filename, "\n"));
1373     msg_entity = e;
1374     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTN_NONE);
1375 }
1376
1377 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
1378 .float spamtime;
1379 float spamsound(entity e, float chan, string samp, float vol, float atten)
1380 {
1381     if (!sound_allowed(MSG_BROADCAST, e))
1382         return FALSE;
1383
1384     if (time > e.spamtime)
1385     {
1386         e.spamtime = time;
1387         sound(e, chan, samp, vol, atten);
1388         return TRUE;
1389     }
1390     return FALSE;
1391 }
1392
1393 void play2team(float t, string filename)
1394 {
1395     entity head;
1396
1397     if (autocvar_bot_sound_monopoly)
1398         return;
1399
1400     FOR_EACH_REALPLAYER(head)
1401     {
1402         if (head.team == t)
1403             play2(head, filename);
1404     }
1405 }
1406
1407 void play2all(string samp)
1408 {
1409     if (autocvar_bot_sound_monopoly)
1410         return;
1411
1412     sound(world, CH_INFO, samp, VOL_BASE, ATTN_NONE);
1413 }
1414
1415 void PrecachePlayerSounds(string f);
1416 void precache_playermodel(string m)
1417 {
1418         float globhandle, i, n;
1419         string f;
1420
1421         if(substring(m, -9,5) == "_lod1")
1422                 return;
1423         if(substring(m, -9,5) == "_lod2")
1424                 return;
1425         precache_model(m);
1426         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
1427         if(fexists(f))
1428                 precache_model(f);
1429         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
1430         if(fexists(f))
1431                 precache_model(f);
1432
1433         globhandle = search_begin(strcat(m, "_*.sounds"), TRUE, FALSE);
1434         if (globhandle < 0)
1435                 return;
1436         n = search_getsize(globhandle);
1437         for (i = 0; i < n; ++i)
1438         {
1439                 //print(search_getfilename(globhandle, i), "\n");
1440                 f = search_getfilename(globhandle, i);
1441                 PrecachePlayerSounds(f);
1442         }
1443         search_end(globhandle);
1444 }
1445 void precache_all_playermodels(string pattern)
1446 {
1447         float globhandle, i, n;
1448         string f;
1449
1450         globhandle = search_begin(pattern, TRUE, FALSE);
1451         if (globhandle < 0)
1452                 return;
1453         n = search_getsize(globhandle);
1454         for (i = 0; i < n; ++i)
1455         {
1456                 //print(search_getfilename(globhandle, i), "\n");
1457                 f = search_getfilename(globhandle, i);
1458                 precache_playermodel(f);
1459         }
1460         search_end(globhandle);
1461 }
1462
1463 void precache()
1464 {
1465     // gamemode related things
1466     precache_model ("models/misc/chatbubble.spr");
1467     if (g_runematch)
1468     {
1469         precache_model ("models/runematch/curse.mdl");
1470         precache_model ("models/runematch/rune.mdl");
1471     }
1472
1473 #ifdef TTURRETS_ENABLED
1474     if (autocvar_g_turrets)
1475         turrets_precash();
1476 #endif
1477
1478     // Precache all player models if desired
1479     if (autocvar_sv_precacheplayermodels)
1480     {
1481         PrecachePlayerSounds("sound/player/default.sounds");
1482         precache_all_playermodels("models/player/*.zym");
1483         precache_all_playermodels("models/player/*.dpm");
1484         precache_all_playermodels("models/player/*.md3");
1485         precache_all_playermodels("models/player/*.psk");
1486         precache_all_playermodels("models/player/*.iqm");
1487     }
1488
1489     if (autocvar_sv_defaultcharacter)
1490     {
1491         string s;
1492         s = autocvar_sv_defaultplayermodel_red;
1493         if (s != "")
1494             precache_playermodel(s);
1495         s = autocvar_sv_defaultplayermodel_blue;
1496         if (s != "")
1497             precache_playermodel(s);
1498         s = autocvar_sv_defaultplayermodel_yellow;
1499         if (s != "")
1500             precache_playermodel(s);
1501         s = autocvar_sv_defaultplayermodel_pink;
1502         if (s != "")
1503             precache_playermodel(s);
1504         s = autocvar_sv_defaultplayermodel;
1505         if (s != "")
1506             precache_playermodel(s);
1507     }
1508
1509     if (g_footsteps)
1510     {
1511         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1512         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1513     }
1514
1515     // gore and miscellaneous sounds
1516     //precache_sound ("misc/h2ohit.wav");
1517     precache_model ("models/hook.md3");
1518     precache_sound ("misc/armorimpact.wav");
1519     precache_sound ("misc/bodyimpact1.wav");
1520     precache_sound ("misc/bodyimpact2.wav");
1521     precache_sound ("misc/gib.wav");
1522     precache_sound ("misc/gib_splat01.wav");
1523     precache_sound ("misc/gib_splat02.wav");
1524     precache_sound ("misc/gib_splat03.wav");
1525     precache_sound ("misc/gib_splat04.wav");
1526     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1527     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1528     precache_sound ("misc/null.wav");
1529     precache_sound ("misc/spawn.wav");
1530     precache_sound ("misc/talk.wav");
1531     precache_sound ("misc/teleport.wav");
1532     precache_sound ("misc/poweroff.wav");
1533     precache_sound ("player/lava.wav");
1534     precache_sound ("player/slime.wav");
1535
1536     if (g_jetpack)
1537         precache_sound ("misc/jetpack_fly.wav");
1538
1539     precache_model ("models/sprites/0.spr32");
1540     precache_model ("models/sprites/1.spr32");
1541     precache_model ("models/sprites/2.spr32");
1542     precache_model ("models/sprites/3.spr32");
1543     precache_model ("models/sprites/4.spr32");
1544     precache_model ("models/sprites/5.spr32");
1545     precache_model ("models/sprites/6.spr32");
1546     precache_model ("models/sprites/7.spr32");
1547     precache_model ("models/sprites/8.spr32");
1548     precache_model ("models/sprites/9.spr32");
1549     precache_model ("models/sprites/10.spr32");
1550
1551     // common weapon precaches
1552         precache_sound ("weapons/reload.wav"); // until weapons have individual reload sounds, precache the reload sound here
1553     precache_sound ("weapons/weapon_switch.wav");
1554     precache_sound ("weapons/weaponpickup.wav");
1555     precache_sound ("weapons/unavailable.wav");
1556     precache_sound ("weapons/dryfire.wav");
1557     if (g_grappling_hook)
1558     {
1559         precache_sound ("weapons/hook_fire.wav"); // hook
1560         precache_sound ("weapons/hook_impact.wav"); // hook
1561     }
1562
1563     if(autocvar_sv_precacheweapons)
1564     {
1565         //precache weapon models/sounds
1566         float wep;
1567         wep = WEP_FIRST;
1568         while (wep <= WEP_LAST)
1569         {
1570             weapon_action(wep, WR_PRECACHE);
1571             wep = wep + 1;
1572         }
1573     }
1574
1575     precache_model("models/elaser.mdl");
1576     precache_model("models/laser.mdl");
1577     precache_model("models/ebomb.mdl");
1578
1579 #if 0
1580     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1581
1582     if (!self.noise && self.music) // quake 3 uses the music field
1583         self.noise = self.music;
1584
1585     // plays music for the level if there is any
1586     if (self.noise)
1587     {
1588         precache_sound (self.noise);
1589         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1590     }
1591 #endif
1592 }
1593
1594 // sorry, but using \ in macros breaks line numbers
1595 #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
1596 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1597 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1598
1599
1600 void Send_CSQC_Centerprint_Generic(entity e, float id, string s, float duration, float countdown_num)
1601 {
1602         if (clienttype(e) == CLIENTTYPE_REAL)
1603         {
1604                 msg_entity = e;
1605                 WRITESPECTATABLE_MSG_ONE({
1606                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1607                         WriteByte(MSG_ONE, TE_CSQC_CENTERPRINT_GENERIC);
1608                         WriteByte(MSG_ONE, id);
1609                         WriteString(MSG_ONE, s);
1610                         if (id != 0 && s != "")
1611                         {
1612                                 WriteByte(MSG_ONE, duration);
1613                                 WriteByte(MSG_ONE, countdown_num);
1614                         }
1615                 });
1616         }
1617 }
1618 void Send_CSQC_Centerprint_Generic_Expire(entity e, float id)
1619 {
1620         Send_CSQC_Centerprint_Generic(e, id, "", 1, 0);
1621 }
1622 // WARNING: this kills the trace globals
1623 #define EXACTTRIGGER_TOUCH if(WarpZoneLib_ExactTrigger_Touch()) return
1624 #define EXACTTRIGGER_INIT  WarpZoneLib_ExactTrigger_Init()
1625
1626 #define INITPRIO_FIRST              0
1627 #define INITPRIO_GAMETYPE           0
1628 #define INITPRIO_GAMETYPE_FALLBACK  1
1629 #define INITPRIO_FINDTARGET        10
1630 #define INITPRIO_DROPTOFLOOR       20
1631 #define INITPRIO_SETLOCATION       90
1632 #define INITPRIO_LINKDOORS         91
1633 #define INITPRIO_LAST              99
1634
1635 .void(void) initialize_entity;
1636 .float initialize_entity_order;
1637 .entity initialize_entity_next;
1638 entity initialize_entity_first;
1639
1640 void make_safe_for_remove(entity e)
1641 {
1642     if (e.initialize_entity)
1643     {
1644         entity ent, prev;
1645         for (ent = initialize_entity_first; ent; )
1646         {
1647             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1648             {
1649                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1650                 // skip it in linked list
1651                 if (prev)
1652                 {
1653                     prev.initialize_entity_next = ent.initialize_entity_next;
1654                     ent = prev.initialize_entity_next;
1655                 }
1656                 else
1657                 {
1658                     initialize_entity_first = ent.initialize_entity_next;
1659                     ent = initialize_entity_first;
1660                 }
1661             }
1662             else
1663             {
1664                 prev = ent;
1665                 ent = ent.initialize_entity_next;
1666             }
1667         }
1668     }
1669 }
1670
1671 void objerror(string s)
1672 {
1673     make_safe_for_remove(self);
1674     builtin_objerror(s);
1675 }
1676
1677 .float remove_except_protected_forbidden;
1678 void remove_except_protected(entity e)
1679 {
1680         if(e.remove_except_protected_forbidden)
1681                 error("not allowed to remove this at this point");
1682         builtin_remove(e);
1683 }
1684
1685 void remove_unsafely(entity e)
1686 {
1687     if(e.classname == "spike")
1688         error("Removing spikes is forbidden (crylink bug), please report");
1689     builtin_remove(e);
1690 }
1691
1692 void remove_safely(entity e)
1693 {
1694     make_safe_for_remove(e);
1695     builtin_remove(e);
1696 }
1697
1698 void InitializeEntity(entity e, void(void) func, float order)
1699 {
1700     entity prev, cur;
1701
1702     if (!e || e.initialize_entity)
1703     {
1704         // make a proxy initializer entity
1705         entity e_old;
1706         e_old = e;
1707         e = spawn();
1708         e.classname = "initialize_entity";
1709         e.enemy = e_old;
1710     }
1711
1712     e.initialize_entity = func;
1713     e.initialize_entity_order = order;
1714
1715     cur = initialize_entity_first;
1716     for (;;)
1717     {
1718         if (!cur || cur.initialize_entity_order > order)
1719         {
1720             // insert between prev and cur
1721             if (prev)
1722                 prev.initialize_entity_next = e;
1723             else
1724                 initialize_entity_first = e;
1725             e.initialize_entity_next = cur;
1726             return;
1727         }
1728         prev = cur;
1729         cur = cur.initialize_entity_next;
1730     }
1731 }
1732 void InitializeEntitiesRun()
1733 {
1734     entity startoflist;
1735     startoflist = initialize_entity_first;
1736     initialize_entity_first = world;
1737     remove = remove_except_protected;
1738     for (self = startoflist; self; self = self.initialize_entity_next)
1739     {
1740         self.remove_except_protected_forbidden = 1;
1741     }
1742     for (self = startoflist; self; )
1743     {
1744         entity e;
1745         var void(void) func;
1746         e = self.initialize_entity_next;
1747         func = self.initialize_entity;
1748         self.initialize_entity_order = 0;
1749         self.initialize_entity = func_null;
1750         self.initialize_entity_next = world;
1751         self.remove_except_protected_forbidden = 0;
1752         if (self.classname == "initialize_entity")
1753         {
1754             entity e_old;
1755             e_old = self.enemy;
1756             builtin_remove(self);
1757             self = e_old;
1758         }
1759         //dprint("Delayed initialization: ", self.classname, "\n");
1760         if(func != func_null)
1761             func();
1762         else
1763         {
1764             eprint(self);
1765             backtrace(strcat("Null function in: ", self.classname, "\n"));
1766         }
1767         self = e;
1768     }
1769     remove = remove_unsafely;
1770 }
1771
1772 .float uncustomizeentityforclient_set;
1773 .void(void) uncustomizeentityforclient;
1774 void(void) SUB_Nullpointer = #0;
1775 void UncustomizeEntitiesRun()
1776 {
1777     entity oldself;
1778     oldself = self;
1779     for (self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1780         self.uncustomizeentityforclient();
1781     self = oldself;
1782 }
1783 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1784 {
1785     e.customizeentityforclient = customizer;
1786     e.uncustomizeentityforclient = uncustomizer;
1787     e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1788 }
1789
1790 .float nottargeted;
1791 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1792
1793 void() SUB_Remove;
1794 void Net_LinkEntity(entity e, float docull, float dt, float(entity, float) sendfunc)
1795 {
1796     vector mi, ma;
1797
1798     if (e.classname == "")
1799         e.classname = "net_linked";
1800
1801     if (e.model == "" || self.modelindex == 0)
1802     {
1803         mi = e.mins;
1804         ma = e.maxs;
1805         setmodel(e, "null");
1806         setsize(e, mi, ma);
1807     }
1808
1809     e.SendEntity = sendfunc;
1810     e.SendFlags = 0xFFFFFF;
1811
1812     if (!docull)
1813         e.effects |= EF_NODEPTHTEST;
1814
1815     if (dt)
1816     {
1817         e.nextthink = time + dt;
1818         e.think = SUB_Remove;
1819     }
1820 }
1821
1822 void adaptor_think2touch()
1823 {
1824     entity o;
1825     o = other;
1826     other = world;
1827     self.touch();
1828     other = o;
1829 }
1830
1831 void adaptor_think2use()
1832 {
1833     entity o, a;
1834     o = other;
1835     a = activator;
1836     activator = world;
1837     other = world;
1838     self.use();
1839     other = o;
1840     activator = a;
1841 }
1842
1843 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1844 {
1845         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
1846                 self.projectiledeathtype |= HITTYPE_SPLASH;
1847         adaptor_think2use();
1848 }
1849
1850 // deferred dropping
1851 void DropToFloor_Handler()
1852 {
1853     builtin_droptofloor();
1854     self.dropped_origin = self.origin;
1855 }
1856
1857 void droptofloor()
1858 {
1859     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1860 }
1861
1862
1863
1864 float trace_hits_box_a0, trace_hits_box_a1;
1865
1866 float trace_hits_box_1d(float end, float thmi, float thma)
1867 {
1868     if (end == 0)
1869     {
1870         // just check if x is in range
1871         if (0 < thmi)
1872             return FALSE;
1873         if (0 > thma)
1874             return FALSE;
1875     }
1876     else
1877     {
1878         // do the trace with respect to x
1879         // 0 -> end has to stay in thmi -> thma
1880         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1881         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1882         if (trace_hits_box_a0 > trace_hits_box_a1)
1883             return FALSE;
1884     }
1885     return TRUE;
1886 }
1887
1888 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1889 {
1890     end -= start;
1891     thmi -= start;
1892     thma -= start;
1893     // now it is a trace from 0 to end
1894
1895     trace_hits_box_a0 = 0;
1896     trace_hits_box_a1 = 1;
1897
1898     if (!trace_hits_box_1d(end_x, thmi_x, thma_x))
1899         return FALSE;
1900     if (!trace_hits_box_1d(end_y, thmi_y, thma_y))
1901         return FALSE;
1902     if (!trace_hits_box_1d(end_z, thmi_z, thma_z))
1903         return FALSE;
1904
1905     return TRUE;
1906 }
1907
1908 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1909 {
1910     return trace_hits_box(start, end, thmi - ma, thma - mi);
1911 }
1912
1913 float SUB_NoImpactCheck()
1914 {
1915         // zero hitcontents = this is not the real impact, but either the
1916         // mirror-impact of something hitting the projectile instead of the
1917         // projectile hitting the something, or a touchareagrid one. Neither of
1918         // these stop the projectile from moving, so...
1919         if(trace_dphitcontents == 0)
1920         {
1921                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1922                 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)));
1923                 checkclient();
1924         }
1925     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1926         return 1;
1927     if (other == world && self.size != '0 0 0')
1928     {
1929         vector tic;
1930         tic = self.velocity * sys_frametime;
1931         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1932         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1933         if (trace_fraction >= 1)
1934         {
1935             dprint("Odd... did not hit...?\n");
1936         }
1937         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1938         {
1939             dprint("Detected and prevented the sky-grapple bug.\n");
1940             return 1;
1941         }
1942     }
1943
1944     return 0;
1945 }
1946
1947 #define SUB_OwnerCheck() (other && (other == self.owner))
1948
1949 void RemoveGrapplingHook(entity pl);
1950 void W_Crylink_Dequeue(entity e);
1951 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1952 {
1953         if(SUB_OwnerCheck())
1954                 return TRUE;
1955         if(SUB_NoImpactCheck())
1956         {
1957                 if(self.classname == "grapplinghook")
1958                         RemoveGrapplingHook(self.realowner);
1959                 else if(self.classname == "spike")
1960                 {
1961                         W_Crylink_Dequeue(self);
1962                         remove(self);
1963                 }
1964                 else
1965                         remove(self);
1966                 return TRUE;
1967         }
1968         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1969                 UpdateCSQCProjectile(self);
1970         return FALSE;
1971 }
1972 #define PROJECTILE_TOUCH if(WarpZone_Projectile_Touch()) return
1973
1974 float MAX_IPBAN_URIS           = 16;
1975                               
1976 float URI_GET_DISCARD          = 0;
1977 float URI_GET_IPBAN            = 1;
1978 float URI_GET_IPBAN_END        = 16;
1979
1980 void URI_Get_Callback(float id, float status, string data)
1981 {
1982     dprint("Received HTTP request data for id ", ftos(id), "; status is ", ftos(status), "\nData is:\n");
1983     dprint(data);
1984     dprint("\nEnd of data.\n");
1985
1986     if(url_URI_Get_Callback(id, status, data))
1987     {
1988         // handled
1989     }
1990     else if (id == URI_GET_DISCARD)
1991     {
1992         // discard
1993     }
1994     else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1995     {
1996         // online ban list
1997         OnlineBanList_URI_Get_Callback(id, status, data);
1998     }
1999     else
2000     {
2001         print("Received HTTP request data for an invalid id ", ftos(id), ".\n");
2002     }
2003 }
2004
2005 void print_to(entity e, string s)
2006 {
2007     if (e)
2008         sprint(e, strcat(s, "\n"));
2009     else
2010         print(s, "\n");
2011 }
2012
2013 string uid2name(string myuid) {
2014         string s;
2015         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
2016
2017         // FIXME remove this later after 0.6 release
2018         // convert old style broken records to correct style
2019         if(s == "")
2020         {
2021                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
2022                 if(s != "")
2023                 {
2024                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
2025                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
2026                 }
2027         }
2028         
2029         if(s == "")
2030                 s = "^1Unregistered Player";
2031         return s;
2032 }
2033
2034 float race_readTime(string map, float pos)
2035 {
2036         string rr;
2037         if(g_cts)
2038                 rr = CTS_RECORD;
2039         else
2040                 rr = RACE_RECORD;
2041
2042         return stof(db_get(ServerProgsDB, strcat(map, rr, "time", ftos(pos))));
2043 }
2044
2045 string race_readUID(string map, float pos)
2046 {
2047         string rr;
2048         if(g_cts)
2049                 rr = CTS_RECORD;
2050         else
2051                 rr = RACE_RECORD;
2052
2053         return db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos)));
2054 }
2055
2056 float race_readPos(string map, float t) {
2057         float i;
2058         for (i = 1; i <= RANKINGS_CNT; ++i)
2059                 if (race_readTime(map, i) == 0 || race_readTime(map, i) > t)
2060                         return i;
2061
2062         return 0; // pos is zero if unranked
2063 }
2064
2065 void race_writeTime(string map, float t, string myuid)
2066 {
2067         string rr;
2068         if(g_cts)
2069                 rr = CTS_RECORD;
2070         else
2071                 rr = RACE_RECORD;
2072
2073         float newpos;
2074         newpos = race_readPos(map, t);
2075
2076         float i, prevpos;
2077         for(i = 1; i <= RANKINGS_CNT; ++i)
2078         {
2079                 if(race_readUID(map, i) == myuid)
2080                         prevpos = i;
2081         }
2082         if (prevpos) { // player improved his existing record, only have to iterate on ranks between new and old recs
2083                 for (i = prevpos; i > newpos; --i) {
2084                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2085                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2086                 }
2087         } else { // player has no ranked record yet
2088                 for (i = RANKINGS_CNT; i > newpos; --i) {
2089                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2090                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2091                 }
2092         }
2093
2094         // store new time itself
2095         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(newpos)), ftos(t));
2096         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(newpos)), myuid);
2097 }
2098
2099 string race_readName(string map, float pos)
2100 {
2101         string rr;
2102         if(g_cts)
2103                 rr = CTS_RECORD;
2104         else
2105                 rr = RACE_RECORD;
2106
2107         return uid2name(db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos))));
2108 }
2109
2110 string race_placeName(float pos) {
2111         if(floor((mod(pos, 100))/10) * 10 != 10) // examples: 12th, 111th, 213th will not execute this block
2112         {
2113                 if(mod(pos, 10) == 1)
2114                         return strcat(ftos(pos), "st");
2115                 else if(mod(pos, 10) == 2)
2116                         return strcat(ftos(pos), "nd");
2117                 else if(mod(pos, 10) == 3)
2118                         return strcat(ftos(pos), "rd");
2119                 else
2120                         return strcat(ftos(pos), "th");
2121         }
2122         else
2123                 return strcat(ftos(pos), "th");
2124 }
2125 string getrecords(float page) // 50 records per page
2126 {
2127     float rec;
2128     string h;
2129     float r;
2130     float i;
2131     string s;
2132
2133     rec = 0;
2134
2135     s = "";
2136
2137     if (g_ctf)
2138     {
2139         for (i = page * 200; i < MapInfo_count && i < page * 200 + 200; ++i)
2140         {
2141             if (MapInfo_Get_ByID(i))
2142             {
2143                 r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/time")));
2144                 if (r == 0)
2145                     continue;
2146                 // TODO: uid2name
2147                 h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/netname"));
2148                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-6, ftos_decimals(r, 2)), " ", h, "\n");
2149                 ++rec;
2150             }
2151         }
2152     }
2153
2154     if (g_race)
2155     {
2156         for (i = page * 200; i < MapInfo_count && i < page * 200 + 200; ++i)
2157         {
2158             if (MapInfo_Get_ByID(i))
2159             {
2160                 r = race_readTime(MapInfo_Map_bspname, 1);
2161                 if (r == 0)
2162                     continue;
2163                 h = race_readName(MapInfo_Map_bspname, 1);
2164                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, TIME_ENCODED_TOSTRING(r)), " ", h, "\n");
2165                 ++rec;
2166             }
2167         }
2168     }
2169
2170     if (g_cts)
2171     {
2172         for (i = page * 200; i < MapInfo_count && i < page * 200 + 200; ++i)
2173         {
2174             if (MapInfo_Get_ByID(i))
2175             {
2176                 r = race_readTime(MapInfo_Map_bspname, 1);
2177                 if (r == 0)
2178                     continue;
2179                 h = race_readName(MapInfo_Map_bspname, 1);
2180                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, TIME_ENCODED_TOSTRING(r)), " ", h, "\n");
2181                 ++rec;
2182             }
2183         }
2184     }
2185
2186     MapInfo_ClearTemps();
2187
2188     if (s == "" && page == 0)
2189         return "No records are available on this server.\n";
2190     else
2191         return s;
2192 }
2193
2194 string getrankings()
2195 {
2196     string n;
2197     float t;
2198     float i;
2199     string s;
2200     string p;
2201     string map;
2202
2203     s = "";
2204
2205     map = GetMapname();
2206
2207     for (i = 1; i <= RANKINGS_CNT; ++i)
2208     {
2209         t = race_readTime(map, i);
2210         if (t == 0)
2211             continue;
2212         n = race_readName(map, i);
2213         p = race_placeName(i);
2214         s = strcat(s, strpad(8, p), " ", strpad(-8, TIME_ENCODED_TOSTRING(t)), " ", n, "\n");
2215     }
2216
2217     MapInfo_ClearTemps();
2218
2219     if (s == "")
2220         return strcat("No records are available for the map: ", map, "\n");
2221     else
2222         return strcat("Records for ", map, ":\n", s);
2223 }
2224
2225 #define LADDER_FIRSTPOINT 100
2226 #define LADDER_CNT 10
2227         // position X still gives LADDER_FIRSTPOINT/X points
2228 #define LADDER_SIZE 30
2229         // ladder shows the top X players
2230 string top_uids[LADDER_SIZE];
2231 float top_scores[LADDER_SIZE];
2232 string getladder()
2233 {
2234     float i, j, k, uidcnt;
2235     string s, temp_s;
2236
2237     s = "";
2238     temp_s = "";
2239
2240     string rr;
2241     if(g_cts)
2242         rr = CTS_RECORD;
2243     else
2244         rr = RACE_RECORD;
2245
2246     string myuid;
2247
2248     for (k = 0; k < MapInfo_count; ++k)
2249     {
2250         if (MapInfo_Get_ByID(k))
2251         {
2252                 for (i = 0; i <= LADDER_CNT; ++i) { // i = 0 because it is the speed award
2253                         if(i == 0) // speed award
2254                         {
2255                                 if(stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, rr, "speed/speed"))) == 0)
2256                                         continue;
2257
2258                                 myuid = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, rr, "speed/crypto_idfp"));
2259                         }
2260                         else // normal record, if it exists (else break)
2261                         {
2262                                 if(race_readTime(MapInfo_Map_bspname, i) == 0)
2263                                         continue;
2264
2265                                 myuid = race_readUID(MapInfo_Map_bspname, i);
2266                         }
2267
2268                         // string s contains:
2269                         // arg 0 = # of speed recs
2270                         // arg 1 = # of 1st place recs
2271                         // arg 2 = # of 2nd place recs
2272                         // ... etc
2273                         // LADDER_CNT+1 = total points
2274
2275                         temp_s = db_get(TemporaryDB, strcat("ladder", myuid));
2276                         if (temp_s == "")
2277                         {
2278                             db_put(TemporaryDB, strcat("uid", ftos(uidcnt)), myuid);
2279                             ++uidcnt;
2280                             for (j = 0; j <= LADDER_CNT + 1; ++j)
2281                             {
2282                                 if(j != LADDER_CNT + 1)
2283                                     temp_s = strcat(temp_s, "0 ");
2284                                 else
2285                                     temp_s = strcat(temp_s, "0");
2286                             }
2287                         }
2288
2289                         tokenize_console(temp_s);
2290                         s = "";
2291
2292                         if(i == 0) // speed award
2293                             for (j = 0; j <= LADDER_CNT; ++j) // loop over each arg in the string
2294                             {
2295                                 if(j == 0) // speed award
2296                                     s = strcat(s, ftos(stof(argv(j)) +1)); // add 1 to speed rec count and write
2297                                 else
2298                                     s = strcat(s, " ", argv(j)); // just copy over everything else
2299                             }
2300                         else // record
2301                             for (j = 0; j <= LADDER_CNT; ++j) // loop over each arg in the string
2302                             {
2303                                 if(j == 0)
2304                                     s = strcat(s, argv(j)); // speed award, dont prefix with " "
2305                                 else if(j == i) // wanted rec!
2306                                     s = strcat(s, " ", ftos(stof(argv(j)) +1)); // update argv(j)
2307                                 else
2308                                     s = strcat(s, " ", argv(j)); // just copy over everything else
2309                             }
2310
2311                         // total points are (by default) calculated like this:
2312                         // speedrec = floor(100 / 10) = 10 points
2313                         // 1st place = floor(100 / 1) = 100 points
2314                         // 2nd place = floor(100 / 2) = 50 points
2315                         // 3rd place = floor(100 / 3) = 33 points
2316                         // 4th place = floor(100 / 4) = 25 points
2317                         // 5th place = floor(100 / 5) = 20 points
2318                         // ... etc
2319
2320                         if(i == 0)
2321                             s = strcat(s, " ", ftos(stof(argv(LADDER_CNT+1)) + LADDER_FIRSTPOINT / 10)); // speed award, add LADDER_FIRSTPOINT / 10 points
2322                         else
2323                             s = strcat(s, " ", ftos(stof(argv(LADDER_CNT+1)) + floor(LADDER_FIRSTPOINT / i))); // record, add LADDER_FIRSTPOINT / i points
2324
2325                         db_put(TemporaryDB, strcat("ladder", myuid), s);
2326                 }
2327         }
2328     }
2329
2330     float thiscnt;
2331     string thisuid;
2332     for (i = 0; i <= uidcnt; ++i) // for each known uid
2333     {
2334         thisuid = db_get(TemporaryDB, strcat("uid", ftos(i)));
2335         temp_s = db_get(TemporaryDB, strcat("ladder", thisuid));
2336         tokenize_console(temp_s);
2337         thiscnt = stof(argv(LADDER_CNT+1));
2338
2339         if(thiscnt > top_scores[LADDER_SIZE-1])
2340         for (j = 0; j < LADDER_SIZE; ++j) // for each place in ladder
2341         {
2342             if(thiscnt > top_scores[j])
2343             {
2344                 for (k = LADDER_SIZE-1; k >= j; --k)
2345                 {
2346                     top_uids[k] = top_uids[k-1];
2347                     top_scores[k] = top_scores[k-1];
2348                 }
2349                 top_uids[j] = thisuid;
2350                 top_scores[j] = thiscnt;
2351                 break;
2352             }
2353         }
2354     }
2355
2356     s = "^3-----------------------\n\n";
2357
2358     s = strcat(s, "Pos ^3|");
2359     s = strcat(s, " ^7Total  ^3|");
2360     for (i = 1; i <= LADDER_CNT; ++i)
2361     {
2362         s = strcat(s, " ^7", race_placeName(i), " ^3|");
2363     }
2364     s = strcat(s, " ^7Speed awards ^3| ^7Name");
2365
2366     s = strcat(s, "\n^3----+--------");
2367     for (i = 1; i <= min(9, LADDER_CNT); ++i)
2368     {
2369         s = strcat(s, "+-----");
2370     }
2371 #if LADDER_CNT > 9
2372     for (i = 1; i <= LADDER_CNT - 9; ++i)
2373     {
2374         s = strcat(s, "+------");
2375     }
2376 #endif
2377
2378     s = strcat(s, "+--------------+--------------------\n");
2379
2380     for (i = 0; i < LADDER_SIZE; ++i)
2381     {
2382         temp_s = db_get(TemporaryDB, strcat("ladder", top_uids[i]));
2383         tokenize_console(temp_s);
2384         if (argv(LADDER_CNT+1) == "") // total is 0, skip
2385             continue;
2386         s = strcat(s, strpad(4, race_placeName(i+1)), "^3| ^7"); // pos
2387         s = strcat(s, strpad(7, argv(LADDER_CNT+1)), "^3| ^7"); // total
2388         for (j = 1; j <= min(9, LADDER_CNT); ++j)
2389         {
2390             s = strcat(s, strpad(4, argv(j)), "^3| ^7"); // 1st, 2nd, 3rd etc cnt
2391         }
2392 #if LADDER_CNT > 9
2393         for (j = 10; j <= LADDER_CNT; ++j)
2394         {
2395             s = strcat(s, strpad(4, argv(j)), " ^3| ^7"); // 1st, 2nd, 3rd etc cnt
2396         }
2397 #endif
2398
2399         s = strcat(s, strpad(13, argv(0)), "^3| ^7"); // speed award cnt
2400         s = strcat(s, uid2name(top_uids[i]), "\n"); // name
2401     }
2402
2403     MapInfo_ClearTemps();
2404
2405     if (s == "")
2406         return "No ladder on this server!\n";
2407     else
2408         return strcat("Top ", ftos(LADDER_SIZE), " ladder rankings:\n", s);
2409 }
2410
2411
2412 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
2413 {
2414     float m, i;
2415     vector start, org, delta, end, enddown, mstart;
2416     entity sp;
2417
2418     m = e.dphitcontentsmask;
2419     e.dphitcontentsmask = goodcontents | badcontents;
2420
2421     org = world.mins;
2422     delta = world.maxs - world.mins;
2423
2424     for (i = 0; i < attempts; ++i)
2425     {
2426         start_x = org_x + random() * delta_x;
2427         start_y = org_y + random() * delta_y;
2428         start_z = org_z + random() * delta_z;
2429
2430         // rule 1: start inside world bounds, and outside
2431         // solid, and don't start from somewhere where you can
2432         // fall down to evil
2433         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta_z, MOVE_NORMAL, e);
2434         if (trace_fraction >= 1)
2435             continue;
2436         if (trace_startsolid)
2437             continue;
2438         if (trace_dphitcontents & badcontents)
2439             continue;
2440         if (trace_dphitq3surfaceflags & badsurfaceflags)
2441             continue;
2442
2443         // rule 2: if we are too high, lower the point
2444         if (trace_fraction * delta_z > maxaboveground)
2445             start = trace_endpos + '0 0 1' * maxaboveground;
2446         enddown = trace_endpos;
2447
2448         // rule 3: make sure we aren't outside the map. This only works
2449         // for somewhat well formed maps. A good rule of thumb is that
2450         // the map should have a convex outside hull.
2451         // these can be traceLINES as we already verified the starting box
2452         mstart = start + 0.5 * (e.mins + e.maxs);
2453         traceline(mstart, mstart + '1 0 0' * delta_x, MOVE_NORMAL, e);
2454         if (trace_fraction >= 1)
2455             continue;
2456         traceline(mstart, mstart - '1 0 0' * delta_x, MOVE_NORMAL, e);
2457         if (trace_fraction >= 1)
2458             continue;
2459         traceline(mstart, mstart + '0 1 0' * delta_y, MOVE_NORMAL, e);
2460         if (trace_fraction >= 1)
2461             continue;
2462         traceline(mstart, mstart - '0 1 0' * delta_y, MOVE_NORMAL, e);
2463         if (trace_fraction >= 1)
2464             continue;
2465         traceline(mstart, mstart + '0 0 1' * delta_z, MOVE_NORMAL, e);
2466         if (trace_fraction >= 1)
2467             continue;
2468
2469         // rule 4: we must "see" some spawnpoint
2470         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
2471                 if(checkpvs(mstart, sp))
2472                         break;
2473         if(!sp)
2474         {
2475                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
2476                         if(checkpvs(mstart, sp))
2477                                 break;
2478                 if(!sp)
2479                         continue;
2480         }
2481
2482         // find a random vector to "look at"
2483         end_x = org_x + random() * delta_x;
2484         end_y = org_y + random() * delta_y;
2485         end_z = org_z + random() * delta_z;
2486         end = start + normalize(end - start) * vlen(delta);
2487
2488         // rule 4: start TO end must not be too short
2489         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
2490         if (trace_startsolid)
2491             continue;
2492         if (trace_fraction < minviewdistance / vlen(delta))
2493             continue;
2494
2495         // rule 5: don't want to look at sky
2496         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
2497             continue;
2498
2499         // rule 6: we must not end up in trigger_hurt
2500         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
2501             continue;
2502
2503         break;
2504     }
2505
2506     e.dphitcontentsmask = m;
2507
2508     if (i < attempts)
2509     {
2510         setorigin(e, start);
2511         e.angles = vectoangles(end - start);
2512         dprint("Needed ", ftos(i + 1), " attempts\n");
2513         return TRUE;
2514     }
2515     else
2516         return FALSE;
2517 }
2518
2519 float zcurveparticles_effectno;
2520 vector zcurveparticles_start;
2521 float zcurveparticles_spd;
2522
2523 void endzcurveparticles()
2524 {
2525         if(zcurveparticles_effectno)
2526         {
2527                 // terminator
2528                 WriteShort(MSG_BROADCAST, zcurveparticles_spd | 0x8000);
2529         }
2530         zcurveparticles_effectno = 0;
2531 }
2532
2533 void zcurveparticles(float effectno, vector start, vector end, float end_dz, float spd)
2534 {
2535         spd = bound(0, floor(spd / 16), 32767);
2536         if(effectno != zcurveparticles_effectno || start != zcurveparticles_start)
2537         {
2538                 endzcurveparticles();
2539                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
2540                 WriteByte(MSG_BROADCAST, TE_CSQC_ZCURVEPARTICLES);
2541                 WriteShort(MSG_BROADCAST, effectno);
2542                 WriteCoord(MSG_BROADCAST, start_x);
2543                 WriteCoord(MSG_BROADCAST, start_y);
2544                 WriteCoord(MSG_BROADCAST, start_z);
2545                 zcurveparticles_effectno = effectno;
2546                 zcurveparticles_start = start;
2547         }
2548         else
2549                 WriteShort(MSG_BROADCAST, zcurveparticles_spd);
2550         WriteCoord(MSG_BROADCAST, end_x);
2551         WriteCoord(MSG_BROADCAST, end_y);
2552         WriteCoord(MSG_BROADCAST, end_z);
2553         WriteCoord(MSG_BROADCAST, end_dz);
2554         zcurveparticles_spd = spd;
2555 }
2556
2557 void zcurveparticles_from_tracetoss(float effectno, vector start, vector end, vector vel)
2558 {
2559         float end_dz;
2560         vector vecxy, velxy;
2561
2562         vecxy = end - start;
2563         vecxy_z = 0;
2564         velxy = vel;
2565         velxy_z = 0;
2566
2567         if (vlen(velxy) < 0.000001 * fabs(vel_z))
2568         {
2569                 endzcurveparticles();
2570                 trailparticles(world, effectno, start, end);
2571                 return;
2572         }
2573
2574         end_dz = vlen(vecxy) / vlen(velxy) * vel_z - (end_z - start_z);
2575         zcurveparticles(effectno, start, end, end_dz, vlen(vel));
2576 }
2577
2578 void write_recordmarker(entity pl, float tstart, float dt)
2579 {
2580     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
2581
2582     // also write a marker into demo files for demotc-race-record-extractor to find
2583     stuffcmd(pl,
2584              strcat(
2585                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
2586                  " ", ftos(tstart), " ", ftos(dt), "\n"));
2587 }
2588
2589 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float allowcenter, float algn)
2590 {
2591         switch(algn)
2592         {
2593                 default:
2594                 case 3: // right
2595                         break;
2596
2597                 case 4: // left
2598                         vecs_y = -vecs_y;
2599                         break;
2600
2601                 case 1:
2602                         if(allowcenter) // 2: allow center handedness
2603                         {
2604                                 // center
2605                                 vecs_y = 0;
2606                                 vecs_z -= 2;
2607                         }
2608                         else
2609                         {
2610                                 // right
2611                         }
2612                         break;
2613
2614                 case 2:
2615                         if(allowcenter) // 2: allow center handedness
2616                         {
2617                                 // center
2618                                 vecs_y = 0;
2619                                 vecs_z -= 2;
2620                         }
2621                         else
2622                         {
2623                                 // left
2624                                 vecs_y = -vecs_y;
2625                         }
2626                         break;
2627         }
2628         return vecs;
2629 }
2630
2631 vector shotorg_adjust_values(vector vecs, float y_is_right, float visual, float algn)
2632 {
2633         string s;
2634         vector v;
2635
2636         if (autocvar_g_shootfromeye)
2637         {
2638                 if (visual)
2639                 {
2640                         vecs_y = 0;
2641                         vecs_z -= 2;
2642                 }
2643                 else
2644                 {
2645                         vecs_y = 0;
2646                         vecs_z = 0;
2647                 }
2648         }
2649         else if (autocvar_g_shootfromcenter)
2650         {
2651                 vecs_y = 0;
2652                 vecs_z -= 2;
2653         }
2654         else if ((s = autocvar_g_shootfromfixedorigin) != "")
2655         {
2656                 v = stov(s);
2657                 if (y_is_right)
2658                         v_y = -v_y;
2659                 if (v_x != 0)
2660                         vecs_x = v_x;
2661                 vecs_y = v_y;
2662                 vecs_z = v_z;
2663         }
2664         else if (autocvar_g_shootfromclient)
2665         {
2666                 vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn);
2667         }
2668         return vecs;
2669 }
2670
2671 vector shotorg_adjust(vector vecs, float y_is_right, float visual)
2672 {
2673         return shotorg_adjust_values(vecs, y_is_right, visual, self.owner.cvar_cl_gunalign);
2674 }
2675
2676
2677 void attach_sameorigin(entity e, entity to, string tag)
2678 {
2679     vector org, t_forward, t_left, t_up, e_forward, e_up;
2680     vector org0, ang0;
2681     float tagscale;
2682
2683     ang0 = e.angles;
2684     org0 = e.origin;
2685
2686     org = e.origin - gettaginfo(to, gettagindex(to, tag));
2687     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
2688     t_forward = v_forward * tagscale;
2689     t_left = v_right * -tagscale;
2690     t_up = v_up * tagscale;
2691
2692     e.origin_x = org * t_forward;
2693     e.origin_y = org * t_left;
2694     e.origin_z = org * t_up;
2695
2696     // current forward and up directions
2697     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2698                 e.angles = AnglesTransform_FromVAngles(e.angles);
2699         else
2700                 e.angles = AnglesTransform_FromAngles(e.angles);
2701     fixedmakevectors(e.angles);
2702
2703     // untransform forward, up!
2704     e_forward_x = v_forward * t_forward;
2705     e_forward_y = v_forward * t_left;
2706     e_forward_z = v_forward * t_up;
2707     e_up_x = v_up * t_forward;
2708     e_up_y = v_up * t_left;
2709     e_up_z = v_up * t_up;
2710
2711     e.angles = fixedvectoangles2(e_forward, e_up);
2712     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2713                 e.angles = AnglesTransform_ToVAngles(e.angles);
2714         else
2715                 e.angles = AnglesTransform_ToAngles(e.angles);
2716
2717     setattachment(e, to, tag);
2718     setorigin(e, e.origin);
2719 }
2720
2721 void detach_sameorigin(entity e)
2722 {
2723     vector org;
2724     org = gettaginfo(e, 0);
2725     e.angles = fixedvectoangles2(v_forward, v_up);
2726     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2727                 e.angles = AnglesTransform_ToVAngles(e.angles);
2728         else
2729                 e.angles = AnglesTransform_ToAngles(e.angles);
2730     setorigin(e, org);
2731     setattachment(e, world, "");
2732     setorigin(e, e.origin);
2733 }
2734
2735 void follow_sameorigin(entity e, entity to)
2736 {
2737     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
2738     e.aiment = to; // make the hole follow bmodel
2739     e.punchangle = to.angles; // the original angles of bmodel
2740     e.view_ofs = e.origin - to.origin; // relative origin
2741     e.v_angle = e.angles - to.angles; // relative angles
2742 }
2743
2744 void unfollow_sameorigin(entity e)
2745 {
2746     e.movetype = MOVETYPE_NONE;
2747 }
2748
2749 entity gettaginfo_relative_ent;
2750 vector gettaginfo_relative(entity e, float tag)
2751 {
2752     if (!gettaginfo_relative_ent)
2753     {
2754         gettaginfo_relative_ent = spawn();
2755         gettaginfo_relative_ent.effects = EF_NODRAW;
2756     }
2757     gettaginfo_relative_ent.model = e.model;
2758     gettaginfo_relative_ent.modelindex = e.modelindex;
2759     gettaginfo_relative_ent.frame = e.frame;
2760     return gettaginfo(gettaginfo_relative_ent, tag);
2761 }
2762
2763 void SoundEntity_StartSound(entity pl, float chan, string samp, float vol, float attn)
2764 {
2765     float p;
2766     p = pow(2, chan);
2767     if (pl.soundentity.cnt & p)
2768         return;
2769     soundtoat(MSG_ALL, pl.soundentity, gettaginfo(pl.soundentity, 0), chan, samp, vol, attn);
2770     pl.soundentity.cnt |= p;
2771 }
2772
2773 void SoundEntity_StopSound(entity pl, float chan)
2774 {
2775     float p;
2776     p = pow(2, chan);
2777     if (pl.soundentity.cnt & p)
2778     {
2779         stopsoundto(MSG_ALL, pl.soundentity, chan);
2780         pl.soundentity.cnt &~= p;
2781     }
2782 }
2783
2784 void SoundEntity_Attach(entity pl)
2785 {
2786     pl.soundentity = spawn();
2787     pl.soundentity.classname = "soundentity";
2788     pl.soundentity.owner = pl;
2789     setattachment(pl.soundentity, pl, "");
2790     setmodel(pl.soundentity, "null");
2791 }
2792
2793 void SoundEntity_Detach(entity pl)
2794 {
2795     float i;
2796     for (i = 0; i <= 7; ++i)
2797         SoundEntity_StopSound(pl, i);
2798 }
2799
2800
2801 float ParseCommandPlayerSlotTarget_firsttoken;
2802 entity GetCommandPlayerSlotTargetFromTokenizedCommand(float tokens, float idx) // idx = start index
2803 {
2804         string s;
2805         entity e, head;
2806         float n;
2807
2808         s = string_null;
2809
2810         ParseCommandPlayerSlotTarget_firsttoken = -1;
2811
2812         if (tokens > idx)
2813         {
2814                 if (substring(argv(idx), 0, 1) == "#")
2815                 {
2816                         s = substring(argv(idx), 1, -1);
2817                         ++idx;
2818                         if (s == "") if (tokens > idx)
2819                         {
2820                                 s = argv(idx);
2821                                 ++idx;
2822                         }
2823                         ParseCommandPlayerSlotTarget_firsttoken = idx;
2824                         n = stof(s);
2825                         if (s == ftos(n) && n > 0 && n <= maxclients)
2826                         {
2827                                 e = edict_num(n);
2828                                 if (e.flags & FL_CLIENT)
2829                                         return e;
2830                         }
2831                 }
2832                 else
2833                 {
2834                         // it must be a nick name
2835                         s = argv(idx);
2836                         ++idx;
2837                         ParseCommandPlayerSlotTarget_firsttoken = idx;
2838
2839                         n = 0;
2840                         FOR_EACH_CLIENT(head)
2841                                 if (head.netname == s)
2842                                 {
2843                                         e = head;
2844                                         ++n;
2845                                 }
2846                         if (n == 1)
2847                                 return e;
2848
2849                         s = strdecolorize(s);
2850                         n = 0;
2851                         FOR_EACH_CLIENT(head)
2852                                 if (strdecolorize(head.netname) == s)
2853                                 {
2854                                         e = head;
2855                                         ++n;
2856                                 }
2857                         if (n == 1)
2858                                 return e;
2859                 }
2860         }
2861
2862         return world;
2863 }
2864
2865 .float scale2;
2866
2867 float modeleffect_SendEntity(entity to, float sf)
2868 {
2869         float f;
2870         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
2871
2872         f = 0;
2873         if(self.velocity != '0 0 0')
2874                 f |= 1;
2875         if(self.angles != '0 0 0')
2876                 f |= 2;
2877         if(self.avelocity != '0 0 0')
2878                 f |= 4;
2879
2880         WriteByte(MSG_ENTITY, f);
2881         WriteShort(MSG_ENTITY, self.modelindex);
2882         WriteByte(MSG_ENTITY, self.skin);
2883         WriteByte(MSG_ENTITY, self.frame);
2884         WriteCoord(MSG_ENTITY, self.origin_x);
2885         WriteCoord(MSG_ENTITY, self.origin_y);
2886         WriteCoord(MSG_ENTITY, self.origin_z);
2887         if(f & 1)
2888         {
2889                 WriteCoord(MSG_ENTITY, self.velocity_x);
2890                 WriteCoord(MSG_ENTITY, self.velocity_y);
2891                 WriteCoord(MSG_ENTITY, self.velocity_z);
2892         }
2893         if(f & 2)
2894         {
2895                 WriteCoord(MSG_ENTITY, self.angles_x);
2896                 WriteCoord(MSG_ENTITY, self.angles_y);
2897                 WriteCoord(MSG_ENTITY, self.angles_z);
2898         }
2899         if(f & 4)
2900         {
2901                 WriteCoord(MSG_ENTITY, self.avelocity_x);
2902                 WriteCoord(MSG_ENTITY, self.avelocity_y);
2903                 WriteCoord(MSG_ENTITY, self.avelocity_z);
2904         }
2905         WriteShort(MSG_ENTITY, self.scale * 256.0);
2906         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
2907         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
2908         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
2909         WriteByte(MSG_ENTITY, self.alpha * 255.0);
2910
2911         return TRUE;
2912 }
2913
2914 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)
2915 {
2916         entity e;
2917         float sz;
2918         e = spawn();
2919         e.classname = "modeleffect";
2920         setmodel(e, m);
2921         e.frame = f;
2922         setorigin(e, o);
2923         e.velocity = v;
2924         e.angles = ang;
2925         e.avelocity = angv;
2926         e.alpha = a;
2927         e.teleport_time = t1;
2928         e.fade_time = t2;
2929         e.skin = s;
2930         if(s0 >= 0)
2931                 e.scale = s0 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2932         else
2933                 e.scale = -s0;
2934         if(s2 >= 0)
2935                 e.scale2 = s2 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2936         else
2937                 e.scale2 = -s2;
2938         sz = max(e.scale, e.scale2);
2939         setsize(e, e.mins * sz, e.maxs * sz);
2940         Net_LinkEntity(e, FALSE, 0.1, modeleffect_SendEntity);
2941 }
2942
2943 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
2944 {
2945         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
2946 }
2947
2948 float randombit(float bits)
2949 {
2950         if not(bits & (bits-1)) // this ONLY holds for powers of two!
2951                 return bits;
2952
2953         float n, f, b, r;
2954
2955         r = random();
2956         b = 0;
2957         n = 0;
2958
2959         for(f = 1; f <= bits; f *= 2)
2960         {
2961                 if(bits & f)
2962                 {
2963                         ++n;
2964                         r *= n;
2965                         if(r <= 1)
2966                                 b = f;
2967                         else
2968                                 r = (r - 1) / (n - 1);
2969                 }
2970         }
2971
2972         return b;
2973 }
2974
2975 float randombits(float bits, float k, float error_return)
2976 {
2977         float r;
2978         r = 0;
2979         while(k > 0 && bits != r)
2980         {
2981                 r += randombit(bits - r);
2982                 --k;
2983         }
2984         if(error_return)
2985                 if(k > 0)
2986                         return -1; // all
2987         return r;
2988 }
2989
2990 void randombit_test(float bits, float iter)
2991 {
2992         while(iter > 0)
2993         {
2994                 print(ftos(randombit(bits)), "\n");
2995                 --iter;
2996         }
2997 }
2998
2999 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
3000 {
3001         if(halflifedist > 0)
3002                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
3003         else if(halflifedist < 0)
3004                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
3005         else
3006                 return 1;
3007 }
3008
3009
3010
3011
3012 #ifdef RELEASE
3013 #define cvar_string_normal builtin_cvar_string
3014 #define cvar_normal builtin_cvar
3015 #else
3016 string cvar_string_normal(string n)
3017 {
3018         if not(cvar_type(n) & 1)
3019                 backtrace(strcat("Attempt to access undefined cvar: ", n));
3020         return builtin_cvar_string(n);
3021 }
3022
3023 float cvar_normal(string n)
3024 {
3025         return stof(cvar_string_normal(n));
3026 }
3027 #endif
3028 #define cvar_set_normal builtin_cvar_set
3029
3030 void defer_think()
3031 {
3032     entity oself;
3033
3034     oself           = self;
3035     self            = self.owner;
3036     oself.think     = SUB_Remove;
3037     oself.nextthink = time;
3038
3039     oself.use();
3040 }
3041
3042 /*
3043     Execute func() after time + fdelay.
3044     self when func is executed = self when defer is called
3045 */
3046 void defer(float fdelay, void() func)
3047 {
3048     entity e;
3049
3050     e           = spawn();
3051     e.owner     = self;
3052     e.use       = func;
3053     e.think     = defer_think;
3054     e.nextthink = time + fdelay;
3055 }
3056
3057 .string aiment_classname;
3058 .float aiment_deadflag;
3059 void SetMovetypeFollow(entity ent, entity e)
3060 {
3061         // FIXME this may not be warpzone aware
3062         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
3063         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.
3064         ent.aiment = e; // make the hole follow bmodel
3065         ent.punchangle = e.angles; // the original angles of bmodel
3066         ent.view_ofs = ent.origin - e.origin; // relative origin
3067         ent.v_angle = ent.angles - e.angles; // relative angles
3068         ent.aiment_classname = strzone(e.classname);
3069         ent.aiment_deadflag = e.deadflag;
3070 }
3071 void UnsetMovetypeFollow(entity ent)
3072 {
3073         ent.movetype = MOVETYPE_FLY;
3074         PROJECTILE_MAKETRIGGER(ent);
3075         ent.aiment = world;
3076 }
3077 float LostMovetypeFollow(entity ent)
3078 {
3079 /*
3080         if(ent.movetype != MOVETYPE_FOLLOW)
3081                 if(ent.aiment)
3082                         error("???");
3083 */
3084         if(ent.aiment)
3085         {
3086                 if(ent.aiment.classname != ent.aiment_classname)
3087                         return 1;
3088                 if(ent.aiment.deadflag != ent.aiment_deadflag)
3089                         return 1;
3090         }
3091         return 0;
3092 }
3093
3094 float isPushable(entity e)
3095 {
3096         if(e.iscreature)
3097                 return TRUE;
3098         switch(e.classname)
3099         {
3100                 case "body":
3101                 case "droppedweapon":
3102                 case "keepawayball":
3103                 case "nexball_basketball":
3104                 case "nexball_football":
3105                         return TRUE;
3106                 case "bullet": // antilagged bullets can't hit this either
3107                         return FALSE;
3108         }
3109         if (e.projectiledeathtype)
3110                 return TRUE;
3111         return FALSE;
3112 }