Hook: don't give weapon when offhand is active
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 #include "miscfunctions.qh"
2 #include "_all.qh"
3 #include "antilag.qh"
4 #include "command/common.qh"
5 #include "constants.qh"
6 #include "g_hook.qh"
7 #include "ipban.qh"
8 #include "mutators/mutators_include.qh"
9 #include "t_items.qh"
10 #include "weapons/accuracy.qh"
11 #include "weapons/csqcprojectile.qh"
12 #include "weapons/selection.qh"
13 #include "../common/command/generic.qh"
14 #include "../common/constants.qh"
15 #include "../common/deathtypes.qh"
16 #include "../common/mapinfo.qh"
17 #include "../common/notifications.qh"
18 #include "../common/playerstats.qh"
19 #include "../common/teams.qh"
20 #include "../common/triggers/subs.qh"
21 #include "../common/util.qh"
22 #include "../common/turrets/sv_turrets.qh"
23 #include "../common/weapons/all.qh"
24 #include "../csqcmodellib/sv_model.qh"
25 #include "../warpzonelib/anglestransform.qh"
26 #include "../warpzonelib/server.qh"
27
28 void crosshair_trace(entity pl)
29 {
30         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));
31 }
32 void crosshair_trace_plusvisibletriggers(entity pl)
33 {
34         entity first;
35         entity e;
36         first = findchainfloat(solid, SOLID_TRIGGER);
37
38         for (e = first; e; e = e.chain)
39                 if (e.model != "")
40                         e.solid = SOLID_BSP;
41
42         crosshair_trace(pl);
43
44         for (e = first; e; e = e.chain)
45                 e.solid = SOLID_TRIGGER;
46 }
47 void WarpZone_crosshair_trace(entity pl)
48 {
49         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));
50 }
51
52
53 string admin_name(void)
54 {
55         if(autocvar_sv_adminnick != "")
56                 return autocvar_sv_adminnick;
57         else
58                 return "SERVER ADMIN";
59 }
60
61 void DistributeEvenly_Init(float amount, float totalweight)
62 {
63     if (DistributeEvenly_amount)
64     {
65         LOG_TRACE("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
66         LOG_TRACE(ftos(DistributeEvenly_totalweight), " left!)\n");
67     }
68     if (totalweight == 0)
69         DistributeEvenly_amount = 0;
70     else
71         DistributeEvenly_amount = amount;
72     DistributeEvenly_totalweight = totalweight;
73 }
74 float DistributeEvenly_Get(float weight)
75 {
76     float f;
77     if (weight <= 0)
78         return 0;
79     f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
80     DistributeEvenly_totalweight -= weight;
81     DistributeEvenly_amount -= f;
82     return f;
83 }
84 float DistributeEvenly_GetRandomized(float weight)
85 {
86     float f;
87     if (weight <= 0)
88         return 0;
89     f = floor(random() + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
90     DistributeEvenly_totalweight -= weight;
91     DistributeEvenly_amount -= f;
92     return f;
93 }
94
95
96 void GameLogEcho(string s)
97 {
98     string fn;
99     int matches;
100
101     if (autocvar_sv_eventlog_files)
102     {
103         if (!logfile_open)
104         {
105             logfile_open = true;
106             matches = autocvar_sv_eventlog_files_counter + 1;
107             cvar_set("sv_eventlog_files_counter", itos(matches));
108             fn = ftos(matches);
109             if (strlen(fn) < 8)
110                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
111             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
112             logfile = fopen(fn, FILE_APPEND);
113             fputs(logfile, ":logversion:3\n");
114         }
115         if (logfile >= 0)
116         {
117             if (autocvar_sv_eventlog_files_timestamps)
118                 fputs(logfile, strcat(":time:", strftime(true, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
119             else
120                 fputs(logfile, strcat(s, "\n"));
121         }
122     }
123     if (autocvar_sv_eventlog_console)
124     {
125         LOG_INFO(s, "\n");
126     }
127 }
128
129 void GameLogInit()
130 {
131     logfile_open = 0;
132     // will be opened later
133 }
134
135 void GameLogClose()
136 {
137     if (logfile_open && logfile >= 0)
138     {
139         fclose(logfile);
140         logfile = -1;
141     }
142 }
143
144 entity findnearest(vector point, .string field, string value, vector axismod)
145 {
146     entity localhead;
147     float i;
148     float j;
149     float len;
150     vector dist;
151
152     float num_nearest;
153     num_nearest = 0;
154
155     localhead = find(world, field, value);
156     while (localhead)
157     {
158         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
159             dist = localhead.oldorigin;
160         else
161             dist = localhead.origin;
162         dist = dist - point;
163         dist = dist.x * axismod.x * '1 0 0' + dist.y * axismod.y * '0 1 0' + dist.z * axismod.z * '0 0 1';
164         len = vlen(dist);
165
166         for (i = 0; i < num_nearest; ++i)
167         {
168             if (len < nearest_length[i])
169                 break;
170         }
171
172         // now i tells us where to insert at
173         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
174         if (i < NUM_NEAREST_ENTITIES)
175         {
176             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
177             {
178                 nearest_length[j + 1] = nearest_length[j];
179                 nearest_entity[j + 1] = nearest_entity[j];
180             }
181             nearest_length[i] = len;
182             nearest_entity[i] = localhead;
183             if (num_nearest < NUM_NEAREST_ENTITIES)
184                 num_nearest = num_nearest + 1;
185         }
186
187         localhead = find(localhead, field, value);
188     }
189
190     // now use the first one from our list that we can see
191     for (i = 0; i < num_nearest; ++i)
192     {
193         traceline(point, nearest_entity[i].origin, true, world);
194         if (trace_fraction == 1)
195         {
196             if (i != 0)
197             {
198                 LOG_TRACE("Nearest point (");
199                 LOG_TRACE(nearest_entity[0].netname);
200                 LOG_TRACE(") is not visible, using a visible one.\n");
201             }
202             return nearest_entity[i];
203         }
204     }
205
206     if (num_nearest == 0)
207         return world;
208
209     LOG_TRACE("Not seeing any location point, using nearest as fallback.\n");
210     /* DEBUGGING CODE:
211     dprint("Candidates were: ");
212     for(j = 0; j < num_nearest; ++j)
213     {
214         if(j != 0)
215                 dprint(", ");
216         dprint(nearest_entity[j].netname);
217     }
218     dprint("\n");
219     */
220
221     return nearest_entity[0];
222 }
223
224 string NearestLocation(vector p)
225 {
226     entity loc;
227     string ret;
228     ret = "somewhere";
229     loc = findnearest(p, classname, "target_location", '1 1 1');
230     if (loc)
231     {
232         ret = loc.message;
233     }
234     else
235     {
236         loc = findnearest(p, target, "###item###", '1 1 4');
237         if (loc)
238             ret = loc.netname;
239     }
240     return ret;
241 }
242
243 string formatmessage(string msg)
244 {SELFPARAM();
245         float p, p1, p2;
246         float n;
247         vector cursor;
248         entity cursor_ent;
249         string escape;
250         string replacement;
251         string ammoitems;
252         p = 0;
253         n = 7;
254
255         ammoitems = "batteries";
256         if(self.items & ITEM_Plasma.m_itemid) ammoitems = ITEM_Plasma.m_name;
257         if(self.items & ITEM_Cells.m_itemid) ammoitems = ITEM_Cells.m_name;
258         if(self.items & ITEM_Rockets.m_itemid) ammoitems = ITEM_Rockets.m_name;
259         if(self.items & ITEM_Shells.m_itemid) ammoitems = ITEM_Shells.m_name;
260
261         WarpZone_crosshair_trace(self);
262         cursor = trace_endpos;
263         cursor_ent = trace_ent;
264
265         while (1) {
266                 if (n < 1)
267                         break; // too many replacements
268
269                 n = n - 1;
270                 p1 = strstr(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
271                 p2 = strstr(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
272
273                 if (p1 < 0)
274                         p1 = p2;
275
276                 if (p2 < 0)
277                         p2 = p1;
278
279                 p = min(p1, p2);
280
281                 if (p < 0)
282                         break;
283
284                 replacement = substring(msg, p, 2);
285                 escape = substring(msg, p + 1, 1);
286
287                 switch(escape)
288                 {
289                         case "%": replacement = "%"; break;
290                         case "\\":replacement = "\\"; break;
291                         case "n": replacement = "\n"; break;
292                         case "a": replacement = ftos(floor(self.armorvalue)); break;
293                         case "h": replacement = ftos(floor(self.health)); break;
294                         case "l": replacement = NearestLocation(self.origin); break;
295                         case "y": replacement = NearestLocation(cursor); break;
296                         case "d": replacement = NearestLocation(self.death_origin); break;
297                         case "w": replacement = WEP_NAME((!self.weapon) ? (!self.switchweapon ? self.cnt : self.switchweapon) : self.weapon); break;
298                         case "W": replacement = ammoitems; break;
299                         case "x": replacement = ((cursor_ent.netname == "" || !cursor_ent) ? "nothing" : cursor_ent.netname); break;
300                         case "s": replacement = ftos(vlen(self.velocity - self.velocity_z * '0 0 1')); break;
301                         case "S": replacement = ftos(vlen(self.velocity)); break;
302                         case "t": replacement = seconds_tostring(ceil(max(0, autocvar_timelimit * 60 + game_starttime - time))); break;
303                         case "T": replacement = seconds_tostring(floor(time - game_starttime)); break;
304                         default:
305                         {
306                                 MUTATOR_CALLHOOK(FormatMessage, escape, replacement, msg);
307                                 escape = format_escape;
308                                 replacement = format_replacement;
309                                 break;
310                         }
311                 }
312
313                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
314                 p = p + strlen(replacement);
315         }
316         return msg;
317 }
318
319 /*
320 =============
321 GetCvars
322 =============
323 Called with:
324   0:  sends the request
325   >0: receives a cvar from name=argv(f) value=argv(f+1)
326 */
327 void GetCvars_handleString(string thisname, float f, .string field, string name)
328 {SELFPARAM();
329         if (f < 0)
330         {
331                 if (self.(field))
332                         strunzone(self.(field));
333                 self.(field) = string_null;
334         }
335         else if (f > 0)
336         {
337                 if (thisname == name)
338                 {
339                         if (self.(field))
340                                 strunzone(self.(field));
341                         self.(field) = strzone(argv(f + 1));
342                 }
343         }
344         else
345                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
346 }
347 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
348 {SELFPARAM();
349         GetCvars_handleString(thisname, f, field, name);
350         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
351                 if (thisname == name)
352                 {
353                         string s = func(strcat1(self.(field)));
354                         if (s != self.(field))
355                         {
356                                 strunzone(self.(field));
357                                 self.(field) = strzone(s);
358                         }
359                 }
360 }
361 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
362 {SELFPARAM();
363         if (f < 0)
364         {
365         }
366         else if (f > 0)
367         {
368                 if (thisname == name)
369                         self.(field) = stof(argv(f + 1));
370         }
371         else
372                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
373 }
374 void GetCvars_handleFloatOnce(string thisname, float f, .float field, string name)
375 {SELFPARAM();
376         if (f < 0)
377         {
378         }
379         else if (f > 0)
380         {
381                 if (thisname == name)
382                 {
383                         if (!self.(field))
384                         {
385                                 self.(field) = stof(argv(f + 1));
386                                 if (!self.(field))
387                                         self.(field) = -1;
388                         }
389                 }
390         }
391         else
392         {
393                 if (!self.(field))
394                         stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
395         }
396 }
397 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(string wo)
398 {SELFPARAM();
399         string o;
400         o = W_FixWeaponOrder_ForceComplete(wo);
401         if(self.weaponorder_byimpulse)
402         {
403                 strunzone(self.weaponorder_byimpulse);
404                 self.weaponorder_byimpulse = string_null;
405         }
406         self.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
407         return o;
408 }
409 void GetCvars(float f)
410 {SELFPARAM();
411         string s = string_null;
412
413         if (f > 0)
414                 s = strcat1(argv(f));
415
416         get_cvars_f = f;
417         get_cvars_s = s;
418         MUTATOR_CALLHOOK(GetCvars);
419
420         Notification_GetCvars();
421
422         ReplicateVars(this, s, f);
423
424         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
425         GetCvars_handleFloat(s, f, cvar_cl_autoscreenshot, "cl_autoscreenshot");
426         GetCvars_handleFloat(s, f, cvar_cl_jetpack_jump, "cl_jetpack_jump");
427         GetCvars_handleString(s, f, cvar_g_xonoticversion, "g_xonoticversion");
428         GetCvars_handleString(s, f, cvar_cl_physics, "cl_physics");
429         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
430         GetCvars_handleFloat(s, f, cvar_cl_clippedspectating, "cl_clippedspectating");
431         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
432         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
433         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
434         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
435         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
436         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
437         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
438         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
439         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
440         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
441         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
442         GetCvars_handleFloat(s, f, cvar_cl_weaponimpulsemode, "cl_weaponimpulsemode");
443         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
444         GetCvars_handleFloat(s, f, cvar_cl_noantilag, "cl_noantilag");
445         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
446         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
447         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_share, "cl_accuracy_data_share");
448         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_receive, "cl_accuracy_data_receive");
449
450         self.cvar_cl_accuracy_data_share = boolean(self.cvar_cl_accuracy_data_share);
451         self.cvar_cl_accuracy_data_receive = boolean(self.cvar_cl_accuracy_data_receive);
452
453         GetCvars_handleFloatOnce(s, f, cvar_cl_gunalign, "cl_gunalign");
454         GetCvars_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
455         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
456         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
457         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
458
459         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
460         if (f > 0)
461         {
462                 if (s == "cl_weaponpriority")
463                         self.switchweapon = w_getbestweapon(self);
464                 if (s == "cl_allow_uidtracking")
465                         PlayerStats_GameReport_AddPlayer(self);
466         }
467 }
468
469 // decolorizes and team colors the player name when needed
470 string playername(entity p)
471 {
472     string t;
473     if (teamplay && !intermission_running && IS_PLAYER(p))
474     {
475         t = Team_ColorCode(p.team);
476         return strcat(t, strdecolorize(p.netname));
477     }
478     else
479         return p.netname;
480 }
481
482 float want_weapon(entity weaponinfo, float allguns) // WEAPONTODO: what still needs done?
483 {
484         int i = weaponinfo.weapon;
485         int d = 0;
486
487         if (!i)
488                 return 0;
489
490         if (g_lms || g_ca || allguns)
491         {
492                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
493                         d = true;
494                 else
495                         d = false;
496         }
497         else if (g_cts)
498                 d = (i == WEP_SHOTGUN.m_id);
499         else if (g_nexball)
500                 d = 0; // weapon is set a few lines later
501         else
502                 d = !(!weaponinfo.weaponstart);
503
504         if(!g_cts && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
505                 d = 0;
506
507         float t = weaponinfo.weaponstartoverride;
508
509         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
510
511         // bit order in t:
512         // 1: want or not
513         // 2: is default?
514         // 4: is set by default?
515         if(t < 0)
516                 t = 4 | (3 * d);
517         else
518                 t |= (2 * d);
519
520         return t;
521 }
522
523 void readplayerstartcvars()
524 {
525         entity e;
526         float i, j, t;
527         string s;
528
529         // initialize starting values for players
530         start_weapons = '0 0 0';
531         start_weapons_default = '0 0 0';
532         start_weapons_defaultmask = '0 0 0';
533         start_items = 0;
534         start_ammo_shells = 0;
535         start_ammo_nails = 0;
536         start_ammo_rockets = 0;
537         start_ammo_cells = 0;
538         start_ammo_plasma = 0;
539         start_health = cvar("g_balance_health_start");
540         start_armorvalue = cvar("g_balance_armor_start");
541
542         g_weaponarena = 0;
543         g_weaponarena_weapons = '0 0 0';
544
545         s = cvar_string("g_weaponarena");
546         if (s == "0" || s == "")
547         {
548                 if(g_ca || g_freezetag)
549                         s = "most";
550         }
551
552         if (s == "0" || s == "")
553         {
554                 // no arena
555         }
556         else if (s == "off")
557         {
558                 // forcibly turn off weaponarena
559         }
560         else if (s == "all" || s == "1")
561         {
562                 g_weaponarena = 1;
563                 g_weaponarena_list = "All Weapons";
564                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
565                 {
566                         e = get_weaponinfo(j);
567                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
568                                 g_weaponarena_weapons |= WepSet_FromWeapon(j);
569                 }
570         }
571         else if (s == "most")
572         {
573                 g_weaponarena = 1;
574                 g_weaponarena_list = "Most Weapons";
575                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
576                 {
577                         e = get_weaponinfo(j);
578                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
579                                 if (e.spawnflags & WEP_FLAG_NORMAL)
580                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
581                 }
582         }
583         else if (s == "none")
584         {
585                 g_weaponarena = 1;
586                 g_weaponarena_list = "No Weapons";
587         }
588         else
589         {
590                 g_weaponarena = 1;
591                 t = tokenize_console(s);
592                 g_weaponarena_list = "";
593                 for (i = 0; i < t; ++i)
594                 {
595                         s = argv(i);
596                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
597                         {
598                                 e = get_weaponinfo(j);
599                                 if (e.netname == s)
600                                 {
601                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
602                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
603                                         break;
604                                 }
605                         }
606                         if (j > WEP_LAST)
607                         {
608                                 LOG_INFO("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
609                         }
610                 }
611                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
612         }
613
614         if(g_weaponarena)
615                 g_weaponarena_random = cvar("g_weaponarena_random");
616         else
617                 g_weaponarena_random = 0;
618         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
619
620         if (g_weaponarena)
621         {
622                 g_weapon_stay = 0; // incompatible
623                 start_weapons = g_weaponarena_weapons;
624                 start_items |= IT_UNLIMITED_AMMO;
625         }
626         else
627         {
628                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
629                 {
630                         e = get_weaponinfo(i);
631                         int w = want_weapon(e, false);
632                         if(w & 1)
633                                 start_weapons |= WepSet_FromWeapon(i);
634                         if(w & 2)
635                                 start_weapons_default |= WepSet_FromWeapon(i);
636                         if(w & 4)
637                                 start_weapons_defaultmask |= WepSet_FromWeapon(i);
638                 }
639         }
640
641         if(!cvar("g_use_ammunition"))
642                 start_items |= IT_UNLIMITED_AMMO;
643
644         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
645         {
646                 start_ammo_shells = 999;
647                 start_ammo_nails = 999;
648                 start_ammo_rockets = 999;
649                 start_ammo_cells = 999;
650                 start_ammo_plasma = 999;
651                 start_ammo_fuel = 999;
652         }
653         else
654         {
655                 start_ammo_shells = cvar("g_start_ammo_shells");
656                 start_ammo_nails = cvar("g_start_ammo_nails");
657                 start_ammo_rockets = cvar("g_start_ammo_rockets");
658                 start_ammo_cells = cvar("g_start_ammo_cells");
659                 start_ammo_plasma = cvar("g_start_ammo_plasma");
660                 start_ammo_fuel = cvar("g_start_ammo_fuel");
661         }
662
663         if (warmup_stage)
664         {
665                 warmup_start_ammo_shells = start_ammo_shells;
666                 warmup_start_ammo_nails = start_ammo_nails;
667                 warmup_start_ammo_rockets = start_ammo_rockets;
668                 warmup_start_ammo_cells = start_ammo_cells;
669                 warmup_start_ammo_plasma = start_ammo_plasma;
670                 warmup_start_ammo_fuel = start_ammo_fuel;
671                 warmup_start_health = start_health;
672                 warmup_start_armorvalue = start_armorvalue;
673                 warmup_start_weapons = start_weapons;
674                 warmup_start_weapons_default = start_weapons_default;
675                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
676
677                 if (!g_weaponarena && !g_ca && !g_freezetag)
678                 {
679                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
680                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
681                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
682                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
683                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
684                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
685                         warmup_start_health = cvar("g_warmup_start_health");
686                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
687                         warmup_start_weapons = '0 0 0';
688                         warmup_start_weapons_default = '0 0 0';
689                         warmup_start_weapons_defaultmask = '0 0 0';
690                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
691                         {
692                                 e = get_weaponinfo(i);
693                                 int w = want_weapon(e, g_warmup_allguns);
694                                 if(w & 1)
695                                         warmup_start_weapons |= WepSet_FromWeapon(i);
696                                 if(w & 2)
697                                         warmup_start_weapons_default |= WepSet_FromWeapon(i);
698                                 if(w & 4)
699                                         warmup_start_weapons_defaultmask |= WepSet_FromWeapon(i);
700                         }
701                 }
702         }
703
704         if (g_jetpack)
705                 start_items |= ITEM_Jetpack.m_itemid;
706
707         MUTATOR_CALLHOOK(SetStartItems);
708
709         if (start_items & ITEM_Jetpack.m_itemid)
710         {
711                 start_items |= ITEM_JetpackRegen.m_itemid;
712                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
713                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
714         }
715
716         WepSet precache_weapons = start_weapons;
717         if (g_warmup_allguns != 1)
718                 precache_weapons |= warmup_start_weapons;
719         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
720         {
721                 e = get_weaponinfo(i);
722                 if(precache_weapons & WepSet_FromWeapon(i)) {
723                         Weapon w = get_weaponinfo(i);
724                         w.wr_init(w);
725                 }
726         }
727
728         start_ammo_shells = max(0, start_ammo_shells);
729         start_ammo_nails = max(0, start_ammo_nails);
730         start_ammo_rockets = max(0, start_ammo_rockets);
731         start_ammo_cells = max(0, start_ammo_cells);
732         start_ammo_plasma = max(0, start_ammo_plasma);
733         start_ammo_fuel = max(0, start_ammo_fuel);
734
735         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
736         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
737         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
738         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
739         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
740         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
741 }
742
743 float sound_allowed(float destin, entity e)
744 {
745     // sounds from world may always pass
746     for (;;)
747     {
748         if (e.classname == "body")
749             e = e.enemy;
750         else if (e.realowner && e.realowner != e)
751             e = e.realowner;
752         else if (e.owner && e.owner != e)
753             e = e.owner;
754         else
755             break;
756     }
757     // sounds to self may always pass
758     if (destin == MSG_ONE)
759         if (e == msg_entity)
760             return true;
761     // sounds by players can be removed
762     if (autocvar_bot_sound_monopoly)
763         if (IS_REAL_CLIENT(e))
764             return false;
765     // anything else may pass
766     return true;
767 }
768
769 void soundtoat(float _dest, entity e, vector o, float chan, string samp, float vol, float attenu)
770 {
771     float entno, idx;
772
773     if (!sound_allowed(_dest, e))
774         return;
775
776     entno = num_for_edict(e);
777     idx = precache_sound_index(samp);
778
779     int sflags;
780     sflags = 0;
781
782     attenu = floor(attenu * 64);
783     vol = floor(vol * 255);
784
785     if (vol != 255)
786         sflags |= SND_VOLUME;
787     if (attenu != 64)
788         sflags |= SND_ATTENUATION;
789     if (entno >= 8192 || chan < 0 || chan > 7)
790         sflags |= SND_LARGEENTITY;
791     if (idx >= 256)
792         sflags |= SND_LARGESOUND;
793
794     WriteByte(_dest, SVC_SOUND);
795     WriteByte(_dest, sflags);
796     if (sflags & SND_VOLUME)
797         WriteByte(_dest, vol);
798     if (sflags & SND_ATTENUATION)
799         WriteByte(_dest, attenu);
800     if (sflags & SND_LARGEENTITY)
801     {
802         WriteShort(_dest, entno);
803         WriteByte(_dest, chan);
804     }
805     else
806     {
807         WriteShort(_dest, entno * 8 + chan);
808     }
809     if (sflags & SND_LARGESOUND)
810         WriteShort(_dest, idx);
811     else
812         WriteByte(_dest, idx);
813
814     WriteCoord(_dest, o.x);
815     WriteCoord(_dest, o.y);
816     WriteCoord(_dest, o.z);
817 }
818 void soundto(float _dest, entity e, float chan, string samp, float vol, float _atten)
819 {
820     vector o;
821
822     if (!sound_allowed(_dest, e))
823         return;
824
825     o = e.origin + 0.5 * (e.mins + e.maxs);
826     soundtoat(_dest, e, o, chan, samp, vol, _atten);
827 }
828 void soundat(entity e, vector o, float chan, string samp, float vol, float _atten)
829 {
830     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, _atten);
831 }
832 void stopsoundto(float _dest, entity e, float chan)
833 {
834     float entno;
835
836     if (!sound_allowed(_dest, e))
837         return;
838
839     entno = num_for_edict(e);
840
841     if (entno >= 8192 || chan < 0 || chan > 7)
842     {
843         float idx, sflags;
844         idx = precache_sound_index(SND(Null));
845         sflags = SND_LARGEENTITY;
846         if (idx >= 256)
847             sflags |= SND_LARGESOUND;
848         WriteByte(_dest, SVC_SOUND);
849         WriteByte(_dest, sflags);
850         WriteShort(_dest, entno);
851         WriteByte(_dest, chan);
852         if (sflags & SND_LARGESOUND)
853             WriteShort(_dest, idx);
854         else
855             WriteByte(_dest, idx);
856         WriteCoord(_dest, e.origin.x);
857         WriteCoord(_dest, e.origin.y);
858         WriteCoord(_dest, e.origin.z);
859     }
860     else
861     {
862         WriteByte(_dest, SVC_STOPSOUND);
863         WriteShort(_dest, entno * 8 + chan);
864     }
865 }
866 void stopsound(entity e, float chan)
867 {
868     if (!sound_allowed(MSG_BROADCAST, e))
869         return;
870
871     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
872     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
873 }
874
875 void play2(entity e, string filename)
876 {
877     //stuffcmd(e, strcat("play2 ", filename, "\n"));
878     msg_entity = e;
879     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTEN_NONE);
880 }
881
882 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
883 .float spamtime;
884 float spamsound(entity e, float chan, string samp, float vol, float _atten)
885 {
886     if (!sound_allowed(MSG_BROADCAST, e))
887         return false;
888
889     if (time > e.spamtime)
890     {
891         e.spamtime = time;
892         _sound(e, chan, samp, vol, _atten);
893         return true;
894     }
895     return false;
896 }
897
898 void play2team(float t, string filename)
899 {
900     entity head;
901
902     if (autocvar_bot_sound_monopoly)
903         return;
904
905     FOR_EACH_REALPLAYER(head)
906     {
907         if (head.team == t)
908             play2(head, filename);
909     }
910 }
911
912 void play2all(string samp)
913 {
914     if (autocvar_bot_sound_monopoly)
915         return;
916
917     _sound(world, CH_INFO, samp, VOL_BASE, ATTEN_NONE);
918 }
919
920 void PrecachePlayerSounds(string f);
921 void precache_playermodel(string m)
922 {
923         float globhandle, i, n;
924         string f;
925
926         if(substring(m, -9,5) == "_lod1")
927                 return;
928         if(substring(m, -9,5) == "_lod2")
929                 return;
930         precache_model(m);
931         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
932         if(fexists(f))
933                 precache_model(f);
934         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
935         if(fexists(f))
936                 precache_model(f);
937
938         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
939         if (globhandle < 0)
940                 return;
941         n = search_getsize(globhandle);
942         for (i = 0; i < n; ++i)
943         {
944                 //print(search_getfilename(globhandle, i), "\n");
945                 f = search_getfilename(globhandle, i);
946                 PrecachePlayerSounds(f);
947         }
948         search_end(globhandle);
949 }
950 void precache_all_playermodels(string pattern)
951 {
952         float globhandle, i, n;
953         string f;
954
955         globhandle = search_begin(pattern, true, false);
956         if (globhandle < 0)
957                 return;
958         n = search_getsize(globhandle);
959         for (i = 0; i < n; ++i)
960         {
961                 //print(search_getfilename(globhandle, i), "\n");
962                 f = search_getfilename(globhandle, i);
963                 precache_playermodel(f);
964         }
965         search_end(globhandle);
966 }
967
968 void precache()
969 {SELFPARAM();
970     // gamemode related things
971
972     // Precache all player models if desired
973     if (autocvar_sv_precacheplayermodels)
974     {
975         PrecachePlayerSounds("sound/player/default.sounds");
976         precache_all_playermodels("models/player/*.zym");
977         precache_all_playermodels("models/player/*.dpm");
978         precache_all_playermodels("models/player/*.md3");
979         precache_all_playermodels("models/player/*.psk");
980         precache_all_playermodels("models/player/*.iqm");
981     }
982
983     if (autocvar_sv_defaultcharacter)
984     {
985         string s;
986         s = autocvar_sv_defaultplayermodel_red;
987         if (s != "")
988             precache_playermodel(s);
989         s = autocvar_sv_defaultplayermodel_blue;
990         if (s != "")
991             precache_playermodel(s);
992         s = autocvar_sv_defaultplayermodel_yellow;
993         if (s != "")
994             precache_playermodel(s);
995         s = autocvar_sv_defaultplayermodel_pink;
996         if (s != "")
997             precache_playermodel(s);
998         s = autocvar_sv_defaultplayermodel;
999         if (s != "")
1000             precache_playermodel(s);
1001     }
1002
1003     if (g_footsteps)
1004     {
1005         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1006         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1007     }
1008
1009     // gore and miscellaneous sounds
1010     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1011     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1012
1013 #if 0
1014     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1015
1016     if (!self.noise && self.music) // quake 3 uses the music field
1017         self.noise = self.music;
1018
1019     // plays music for the level if there is any
1020     if (self.noise)
1021     {
1022         precache_sound (self.noise);
1023         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTEN_NONE);
1024     }
1025 #endif
1026 }
1027
1028
1029 void make_safe_for_remove(entity e)
1030 {
1031     if (e.initialize_entity)
1032     {
1033         entity ent, prev = world;
1034         for (ent = initialize_entity_first; ent; )
1035         {
1036             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1037             {
1038                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1039                 // skip it in linked list
1040                 if (prev)
1041                 {
1042                     prev.initialize_entity_next = ent.initialize_entity_next;
1043                     ent = prev.initialize_entity_next;
1044                 }
1045                 else
1046                 {
1047                     initialize_entity_first = ent.initialize_entity_next;
1048                     ent = initialize_entity_first;
1049                 }
1050             }
1051             else
1052             {
1053                 prev = ent;
1054                 ent = ent.initialize_entity_next;
1055             }
1056         }
1057     }
1058 }
1059
1060 void objerror(string s)
1061 {SELFPARAM();
1062     make_safe_for_remove(self);
1063     builtin_objerror(s);
1064 }
1065
1066 .float remove_except_protected_forbidden;
1067 void remove_except_protected(entity e)
1068 {
1069         if(e.remove_except_protected_forbidden)
1070                 error("not allowed to remove this at this point");
1071         builtin_remove(e);
1072 }
1073
1074 void remove_unsafely(entity e)
1075 {
1076     if(e.classname == "spike")
1077         error("Removing spikes is forbidden (crylink bug), please report");
1078     builtin_remove(e);
1079 }
1080
1081 void remove_safely(entity e)
1082 {
1083     make_safe_for_remove(e);
1084     builtin_remove(e);
1085 }
1086
1087 void InitializeEntity(entity e, void(void) func, float order)
1088 {
1089     entity prev, cur;
1090
1091     if (!e || e.initialize_entity)
1092     {
1093         // make a proxy initializer entity
1094         entity e_old = e;
1095         e = new(initialize_entity);
1096         e.enemy = e_old;
1097     }
1098
1099     e.initialize_entity = func;
1100     e.initialize_entity_order = order;
1101
1102     cur = initialize_entity_first;
1103     prev = world;
1104     for (;;)
1105     {
1106         if (!cur || cur.initialize_entity_order > order)
1107         {
1108             // insert between prev and cur
1109             if (prev)
1110                 prev.initialize_entity_next = e;
1111             else
1112                 initialize_entity_first = e;
1113             e.initialize_entity_next = cur;
1114             return;
1115         }
1116         prev = cur;
1117         cur = cur.initialize_entity_next;
1118     }
1119 }
1120 void InitializeEntitiesRun()
1121 {SELFPARAM();
1122     entity startoflist = initialize_entity_first;
1123     initialize_entity_first = NULL;
1124     remove = remove_except_protected;
1125     for (entity e = startoflist; e; e = e.initialize_entity_next)
1126     {
1127                 e.remove_except_protected_forbidden = 1;
1128     }
1129     for (entity e = startoflist; e; )
1130     {
1131                 e.remove_except_protected_forbidden = 0;
1132         e.initialize_entity_order = 0;
1133         entity next = e.initialize_entity_next;
1134         e.initialize_entity_next = NULL;
1135         var void() func = e.initialize_entity;
1136         e.initialize_entity = func_null;
1137         if (e.classname == "initialize_entity")
1138         {
1139             entity wrappee = e.enemy;
1140             builtin_remove(e);
1141             e = wrappee;
1142         }
1143         //dprint("Delayed initialization: ", e.classname, "\n");
1144         if (func)
1145         {
1146                 WITH(entity, self, e, func());
1147         }
1148         else
1149         {
1150             eprint(e);
1151             backtrace(strcat("Null function in: ", e.classname, "\n"));
1152         }
1153         e = next;
1154     }
1155     remove = remove_unsafely;
1156 }
1157
1158 void UncustomizeEntitiesRun()
1159 {SELFPARAM();
1160     for (entity e = NULL; (e = findfloat(e, uncustomizeentityforclient_set, 1)); )
1161     {
1162         WITH(entity, self, e, e.uncustomizeentityforclient());
1163     }
1164 }
1165 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1166 {
1167     e.customizeentityforclient = customizer;
1168     e.uncustomizeentityforclient = uncustomizer;
1169     e.uncustomizeentityforclient_set = !!uncustomizer;
1170 }
1171
1172 void Net_LinkEntity(entity e, bool docull, float dt, bool(entity, int) sendfunc)
1173 {SELFPARAM();
1174     vector mi, ma;
1175
1176     if (e.classname == "")
1177         e.classname = "net_linked";
1178
1179     if (e.model == "" || self.modelindex == 0)
1180     {
1181         mi = e.mins;
1182         ma = e.maxs;
1183         setmodel(e, MDL_Null);
1184         setsize(e, mi, ma);
1185     }
1186
1187     e.SendEntity = sendfunc;
1188     e.SendFlags = 0xFFFFFF;
1189
1190     if (!docull)
1191         e.effects |= EF_NODEPTHTEST;
1192
1193     if (dt)
1194     {
1195         e.nextthink = time + dt;
1196         e.think = SUB_Remove;
1197     }
1198 }
1199
1200
1201 .float(entity) isEliminated;
1202 float EliminatedPlayers_SendEntity(entity to, float sendflags)
1203 {
1204         float i, f, b;
1205         entity e;
1206         WriteByte(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
1207         WriteByte(MSG_ENTITY, sendflags);
1208
1209         if(sendflags & 1)
1210         {
1211                 for(i = 1; i <= maxclients; i += 8)
1212                 {
1213                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
1214                         {
1215                                 if(eliminatedPlayers.isEliminated(e))
1216                                         f |= b;
1217                         }
1218                         WriteByte(MSG_ENTITY, f);
1219                 }
1220         }
1221
1222         return true;
1223 }
1224
1225 void EliminatedPlayers_Init(float(entity) isEliminated_func)
1226 {
1227         if(eliminatedPlayers)
1228         {
1229                 backtrace("Can't spawn eliminatedPlayers again!");
1230                 return;
1231         }
1232         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
1233         eliminatedPlayers.isEliminated = isEliminated_func;
1234 }
1235
1236
1237 void adaptor_think2touch()
1238 {SELFPARAM();
1239     entity o;
1240     o = other;
1241     other = world;
1242     self.touch();
1243     other = o;
1244 }
1245
1246 void adaptor_think2use()
1247 {SELFPARAM();
1248     entity o, a;
1249     o = other;
1250     a = activator;
1251     activator = world;
1252     other = world;
1253     self.use();
1254     other = o;
1255     activator = a;
1256 }
1257
1258 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1259 {SELFPARAM();
1260         if(!(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
1261                 self.projectiledeathtype |= HITTYPE_SPLASH;
1262         adaptor_think2use();
1263 }
1264
1265 // deferred dropping
1266 void DropToFloor_Handler()
1267 {SELFPARAM();
1268     builtin_droptofloor();
1269     self.dropped_origin = self.origin;
1270 }
1271
1272 void droptofloor()
1273 {SELFPARAM();
1274     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1275 }
1276
1277
1278
1279 float trace_hits_box_a0, trace_hits_box_a1;
1280
1281 float trace_hits_box_1d(float end, float thmi, float thma)
1282 {
1283     if (end == 0)
1284     {
1285         // just check if x is in range
1286         if (0 < thmi)
1287             return false;
1288         if (0 > thma)
1289             return false;
1290     }
1291     else
1292     {
1293         // do the trace with respect to x
1294         // 0 -> end has to stay in thmi -> thma
1295         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1296         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1297         if (trace_hits_box_a0 > trace_hits_box_a1)
1298             return false;
1299     }
1300     return true;
1301 }
1302
1303 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1304 {
1305     end -= start;
1306     thmi -= start;
1307     thma -= start;
1308     // now it is a trace from 0 to end
1309
1310     trace_hits_box_a0 = 0;
1311     trace_hits_box_a1 = 1;
1312
1313     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1314         return false;
1315     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1316         return false;
1317     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1318         return false;
1319
1320     return true;
1321 }
1322
1323 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1324 {
1325     return trace_hits_box(start, end, thmi - ma, thma - mi);
1326 }
1327
1328 float SUB_NoImpactCheck()
1329 {SELFPARAM();
1330         // zero hitcontents = this is not the real impact, but either the
1331         // mirror-impact of something hitting the projectile instead of the
1332         // projectile hitting the something, or a touchareagrid one. Neither of
1333         // these stop the projectile from moving, so...
1334         if(trace_dphitcontents == 0)
1335         {
1336                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1337                 LOG_TRACEF("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));
1338                 checkclient();
1339         }
1340     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1341         return 1;
1342     if (other == world && self.size != '0 0 0')
1343     {
1344         vector tic;
1345         tic = self.velocity * sys_frametime;
1346         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1347         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1348         if (trace_fraction >= 1)
1349         {
1350             LOG_TRACE("Odd... did not hit...?\n");
1351         }
1352         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1353         {
1354             LOG_TRACE("Detected and prevented the sky-grapple bug.\n");
1355             return 1;
1356         }
1357     }
1358
1359     return 0;
1360 }
1361
1362 #define SUB_OwnerCheck() (other && (other == self.owner))
1363
1364 void W_Crylink_Dequeue(entity e);
1365 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1366 {SELFPARAM();
1367         if(SUB_OwnerCheck())
1368                 return true;
1369         if(SUB_NoImpactCheck())
1370         {
1371                 if(self.classname == "nade")
1372                         return false; // no checks here
1373                 else if(self.classname == "grapplinghook")
1374                         RemoveGrapplingHook(self.realowner);
1375                 else if(self.classname == "spike")
1376                 {
1377                         W_Crylink_Dequeue(self);
1378                         remove(self);
1379                 }
1380                 else
1381                         remove(self);
1382                 return true;
1383         }
1384         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1385                 UpdateCSQCProjectile(self);
1386         return false;
1387 }
1388
1389
1390 void URI_Get_Callback(float id, float status, string data)
1391 {
1392         if(url_URI_Get_Callback(id, status, data))
1393         {
1394                 // handled
1395         }
1396         else if (id == URI_GET_DISCARD)
1397         {
1398                 // discard
1399         }
1400         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1401         {
1402                 // sv_cmd curl
1403                 Curl_URI_Get_Callback(id, status, data);
1404         }
1405         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1406         {
1407                 // online ban list
1408                 OnlineBanList_URI_Get_Callback(id, status, data);
1409         }
1410         else
1411         {
1412                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1413         }
1414 }
1415
1416 string uid2name(string myuid) {
1417         string s;
1418         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1419
1420         // FIXME remove this later after 0.6 release
1421         // convert old style broken records to correct style
1422         if(s == "")
1423         {
1424                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1425                 if(s != "")
1426                 {
1427                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1428                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
1429                 }
1430         }
1431
1432         if(s == "")
1433                 s = "^1Unregistered Player";
1434         return s;
1435 }
1436
1437 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1438 {
1439     float m, i;
1440     vector start, org, delta, end, enddown, mstart;
1441     entity sp;
1442
1443     m = e.dphitcontentsmask;
1444     e.dphitcontentsmask = goodcontents | badcontents;
1445
1446     org = boundmin;
1447     delta = boundmax - boundmin;
1448
1449     start = end = org;
1450
1451     for (i = 0; i < attempts; ++i)
1452     {
1453         start.x = org.x + random() * delta.x;
1454         start.y = org.y + random() * delta.y;
1455         start.z = org.z + random() * delta.z;
1456
1457         // rule 1: start inside world bounds, and outside
1458         // solid, and don't start from somewhere where you can
1459         // fall down to evil
1460         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1461         if (trace_fraction >= 1)
1462             continue;
1463         if (trace_startsolid)
1464             continue;
1465         if (trace_dphitcontents & badcontents)
1466             continue;
1467         if (trace_dphitq3surfaceflags & badsurfaceflags)
1468             continue;
1469
1470         // rule 2: if we are too high, lower the point
1471         if (trace_fraction * delta.z > maxaboveground)
1472             start = trace_endpos + '0 0 1' * maxaboveground;
1473         enddown = trace_endpos;
1474
1475         // rule 3: make sure we aren't outside the map. This only works
1476         // for somewhat well formed maps. A good rule of thumb is that
1477         // the map should have a convex outside hull.
1478         // these can be traceLINES as we already verified the starting box
1479         mstart = start + 0.5 * (e.mins + e.maxs);
1480         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1481         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1482             continue;
1483         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1484         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1485             continue;
1486         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1487         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1488             continue;
1489         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1490         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1491             continue;
1492         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1493         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1494             continue;
1495
1496         // rule 4: we must "see" some spawnpoint or item
1497         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
1498                 if(checkpvs(mstart, sp))
1499                         if((traceline(mstart, sp.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1500                                 break;
1501         if(!sp)
1502         {
1503                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
1504                         if(checkpvs(mstart, sp))
1505                                 if((traceline(mstart, sp.origin + (sp.mins + sp.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1506                                         break;
1507                 if(!sp)
1508                         continue;
1509         }
1510
1511         // find a random vector to "look at"
1512         end.x = org.x + random() * delta.x;
1513         end.y = org.y + random() * delta.y;
1514         end.z = org.z + random() * delta.z;
1515         end = start + normalize(end - start) * vlen(delta);
1516
1517         // rule 4: start TO end must not be too short
1518         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1519         if (trace_startsolid)
1520             continue;
1521         if (trace_fraction < minviewdistance / vlen(delta))
1522             continue;
1523
1524         // rule 5: don't want to look at sky
1525         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1526             continue;
1527
1528         // rule 6: we must not end up in trigger_hurt
1529         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1530             continue;
1531
1532         break;
1533     }
1534
1535     e.dphitcontentsmask = m;
1536
1537     if (i < attempts)
1538     {
1539         setorigin(e, start);
1540         e.angles = vectoangles(end - start);
1541         LOG_TRACE("Needed ", ftos(i + 1), " attempts\n");
1542         return true;
1543     }
1544     else
1545         return false;
1546 }
1547
1548 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1549 {
1550         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1551 }
1552
1553 void write_recordmarker(entity pl, float tstart, float dt)
1554 {
1555     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1556
1557     // also write a marker into demo files for demotc-race-record-extractor to find
1558     stuffcmd(pl,
1559              strcat(
1560                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1561                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1562 }
1563
1564 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float allowcenter, float algn)
1565 {
1566         switch(algn)
1567         {
1568                 default:
1569                 case 3: // right
1570                         break;
1571
1572                 case 4: // left
1573                         vecs.y = -vecs.y;
1574                         break;
1575
1576                 case 1:
1577                         if(allowcenter) // 2: allow center handedness
1578                         {
1579                                 // center
1580                                 vecs.y = 0;
1581                                 vecs.z -= 2;
1582                         }
1583                         else
1584                         {
1585                                 // right
1586                         }
1587                         break;
1588
1589                 case 2:
1590                         if(allowcenter) // 2: allow center handedness
1591                         {
1592                                 // center
1593                                 vecs.y = 0;
1594                                 vecs.z -= 2;
1595                         }
1596                         else
1597                         {
1598                                 // left
1599                                 vecs.y = -vecs.y;
1600                         }
1601                         break;
1602         }
1603         return vecs;
1604 }
1605
1606 vector shotorg_adjust_values(vector vecs, float y_is_right, float visual, float algn)
1607 {
1608         string s;
1609         vector v;
1610
1611         if (autocvar_g_shootfromeye)
1612         {
1613                 if (visual)
1614                 {
1615                         if (autocvar_g_shootfromclient) { vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn); }
1616                         else { vecs.y = 0; vecs.z -= 2; }
1617                 }
1618                 else
1619                 {
1620                         vecs.y = 0;
1621                         vecs.z = 0;
1622                 }
1623         }
1624         else if (autocvar_g_shootfromcenter)
1625         {
1626                 vecs.y = 0;
1627                 vecs.z -= 2;
1628         }
1629         else if ((s = autocvar_g_shootfromfixedorigin) != "")
1630         {
1631                 v = stov(s);
1632                 if (y_is_right)
1633                         v.y = -v.y;
1634                 if (v.x != 0)
1635                         vecs.x = v.x;
1636                 vecs.y = v.y;
1637                 vecs.z = v.z;
1638         }
1639         else if (autocvar_g_shootfromclient)
1640         {
1641                 vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn);
1642         }
1643         return vecs;
1644 }
1645
1646 vector shotorg_adjust(vector vecs, float y_is_right, float visual)
1647 {SELFPARAM();
1648         return shotorg_adjust_values(vecs, y_is_right, visual, self.owner.cvar_cl_gunalign);
1649 }
1650
1651
1652 void attach_sameorigin(entity e, entity to, string tag)
1653 {
1654     vector org, t_forward, t_left, t_up, e_forward, e_up;
1655     float tagscale;
1656
1657     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1658     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1659     t_forward = v_forward * tagscale;
1660     t_left = v_right * -tagscale;
1661     t_up = v_up * tagscale;
1662
1663     e.origin_x = org * t_forward;
1664     e.origin_y = org * t_left;
1665     e.origin_z = org * t_up;
1666
1667     // current forward and up directions
1668     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1669                 e.angles = AnglesTransform_FromVAngles(e.angles);
1670         else
1671                 e.angles = AnglesTransform_FromAngles(e.angles);
1672     fixedmakevectors(e.angles);
1673
1674     // untransform forward, up!
1675     e_forward.x = v_forward * t_forward;
1676     e_forward.y = v_forward * t_left;
1677     e_forward.z = v_forward * t_up;
1678     e_up.x = v_up * t_forward;
1679     e_up.y = v_up * t_left;
1680     e_up.z = v_up * t_up;
1681
1682     e.angles = fixedvectoangles2(e_forward, e_up);
1683     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1684                 e.angles = AnglesTransform_ToVAngles(e.angles);
1685         else
1686                 e.angles = AnglesTransform_ToAngles(e.angles);
1687
1688     setattachment(e, to, tag);
1689     setorigin(e, e.origin);
1690 }
1691
1692 void detach_sameorigin(entity e)
1693 {
1694     vector org;
1695     org = gettaginfo(e, 0);
1696     e.angles = fixedvectoangles2(v_forward, v_up);
1697     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1698                 e.angles = AnglesTransform_ToVAngles(e.angles);
1699         else
1700                 e.angles = AnglesTransform_ToAngles(e.angles);
1701     setorigin(e, org);
1702     setattachment(e, world, "");
1703     setorigin(e, e.origin);
1704 }
1705
1706 void follow_sameorigin(entity e, entity to)
1707 {
1708     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
1709     e.aiment = to; // make the hole follow bmodel
1710     e.punchangle = to.angles; // the original angles of bmodel
1711     e.view_ofs = e.origin - to.origin; // relative origin
1712     e.v_angle = e.angles - to.angles; // relative angles
1713 }
1714
1715 void unfollow_sameorigin(entity e)
1716 {
1717     e.movetype = MOVETYPE_NONE;
1718 }
1719
1720 entity gettaginfo_relative_ent;
1721 vector gettaginfo_relative(entity e, float tag)
1722 {
1723     if (!gettaginfo_relative_ent)
1724     {
1725         gettaginfo_relative_ent = spawn();
1726         gettaginfo_relative_ent.effects = EF_NODRAW;
1727     }
1728     gettaginfo_relative_ent.model = e.model;
1729     gettaginfo_relative_ent.modelindex = e.modelindex;
1730     gettaginfo_relative_ent.frame = e.frame;
1731     return gettaginfo(gettaginfo_relative_ent, tag);
1732 }
1733
1734 .float scale2;
1735
1736 float modeleffect_SendEntity(entity to, int sf)
1737 {SELFPARAM();
1738         float f;
1739         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
1740
1741         f = 0;
1742         if(self.velocity != '0 0 0')
1743                 f |= 1;
1744         if(self.angles != '0 0 0')
1745                 f |= 2;
1746         if(self.avelocity != '0 0 0')
1747                 f |= 4;
1748
1749         WriteByte(MSG_ENTITY, f);
1750         WriteShort(MSG_ENTITY, self.modelindex);
1751         WriteByte(MSG_ENTITY, self.skin);
1752         WriteByte(MSG_ENTITY, self.frame);
1753         WriteCoord(MSG_ENTITY, self.origin.x);
1754         WriteCoord(MSG_ENTITY, self.origin.y);
1755         WriteCoord(MSG_ENTITY, self.origin.z);
1756         if(f & 1)
1757         {
1758                 WriteCoord(MSG_ENTITY, self.velocity.x);
1759                 WriteCoord(MSG_ENTITY, self.velocity.y);
1760                 WriteCoord(MSG_ENTITY, self.velocity.z);
1761         }
1762         if(f & 2)
1763         {
1764                 WriteCoord(MSG_ENTITY, self.angles.x);
1765                 WriteCoord(MSG_ENTITY, self.angles.y);
1766                 WriteCoord(MSG_ENTITY, self.angles.z);
1767         }
1768         if(f & 4)
1769         {
1770                 WriteCoord(MSG_ENTITY, self.avelocity.x);
1771                 WriteCoord(MSG_ENTITY, self.avelocity.y);
1772                 WriteCoord(MSG_ENTITY, self.avelocity.z);
1773         }
1774         WriteShort(MSG_ENTITY, self.scale * 256.0);
1775         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
1776         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
1777         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
1778         WriteByte(MSG_ENTITY, self.alpha * 255.0);
1779
1780         return true;
1781 }
1782
1783 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)
1784 {
1785         entity e;
1786         float sz;
1787         e = spawn();
1788         e.classname = "modeleffect";
1789         _setmodel(e, m);
1790         e.frame = f;
1791         setorigin(e, o);
1792         e.velocity = v;
1793         e.angles = ang;
1794         e.avelocity = angv;
1795         e.alpha = a;
1796         e.teleport_time = t1;
1797         e.fade_time = t2;
1798         e.skin = s;
1799         if(s0 >= 0)
1800                 e.scale = s0 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1801         else
1802                 e.scale = -s0;
1803         if(s2 >= 0)
1804                 e.scale2 = s2 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1805         else
1806                 e.scale2 = -s2;
1807         sz = max(e.scale, e.scale2);
1808         setsize(e, e.mins * sz, e.maxs * sz);
1809         Net_LinkEntity(e, false, 0.1, modeleffect_SendEntity);
1810 }
1811
1812 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
1813 {
1814         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
1815 }
1816
1817 float randombit(float bits)
1818 {
1819         if(!(bits & (bits-1))) // this ONLY holds for powers of two!
1820                 return bits;
1821
1822         float n, f, b, r;
1823
1824         r = random();
1825         b = 0;
1826         n = 0;
1827
1828         for(f = 1; f <= bits; f *= 2)
1829         {
1830                 if(bits & f)
1831                 {
1832                         ++n;
1833                         r *= n;
1834                         if(r <= 1)
1835                                 b = f;
1836                         else
1837                                 r = (r - 1) / (n - 1);
1838                 }
1839         }
1840
1841         return b;
1842 }
1843
1844 float randombits(float bits, float k, float error_return)
1845 {
1846         float r;
1847         r = 0;
1848         while(k > 0 && bits != r)
1849         {
1850                 r += randombit(bits - r);
1851                 --k;
1852         }
1853         if(error_return)
1854                 if(k > 0)
1855                         return -1; // all
1856         return r;
1857 }
1858
1859 void randombit_test(float bits, float iter)
1860 {
1861         while(iter > 0)
1862         {
1863                 LOG_INFO(ftos(randombit(bits)), "\n");
1864                 --iter;
1865         }
1866 }
1867
1868 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
1869 {
1870         if(halflifedist > 0)
1871                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
1872         else if(halflifedist < 0)
1873                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
1874         else
1875                 return 1;
1876 }
1877
1878
1879 .string aiment_classname;
1880 .float aiment_deadflag;
1881 void SetMovetypeFollow(entity ent, entity e)
1882 {
1883         // FIXME this may not be warpzone aware
1884         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
1885         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.
1886         ent.aiment = e; // make the hole follow bmodel
1887         ent.punchangle = e.angles; // the original angles of bmodel
1888         ent.view_ofs = ent.origin - e.origin; // relative origin
1889         ent.v_angle = ent.angles - e.angles; // relative angles
1890         ent.aiment_classname = strzone(e.classname);
1891         ent.aiment_deadflag = e.deadflag;
1892 }
1893 void UnsetMovetypeFollow(entity ent)
1894 {
1895         ent.movetype = MOVETYPE_FLY;
1896         PROJECTILE_MAKETRIGGER(ent);
1897         ent.aiment = world;
1898 }
1899 float LostMovetypeFollow(entity ent)
1900 {
1901 /*
1902         if(ent.movetype != MOVETYPE_FOLLOW)
1903                 if(ent.aiment)
1904                         error("???");
1905 */
1906         if(ent.aiment)
1907         {
1908                 if(ent.aiment.classname != ent.aiment_classname)
1909                         return 1;
1910                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1911                         return 1;
1912         }
1913         return 0;
1914 }
1915
1916 float isPushable(entity e)
1917 {
1918         if(e.pushable)
1919                 return true;
1920         if(IS_VEHICLE(e))
1921                 return false;
1922         if(e.iscreature)
1923                 return true;
1924         switch(e.classname)
1925         {
1926                 case "body":
1927                 case "droppedweapon":
1928                 case "keepawayball":
1929                 case "nexball_basketball":
1930                 case "nexball_football":
1931                         return true;
1932                 case "bullet": // antilagged bullets can't hit this either
1933                         return false;
1934         }
1935         if (e.projectiledeathtype)
1936                 return true;
1937         return false;
1938 }