]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
910f33b7394ab615545044351f47c773dee59e86
[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_grappling_hook) // if possible, redirect off-hand hook to on-hand hook
505                 d |= (i == WEP_HOOK.m_id);
506         if(!g_cts && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
507                 d = 0;
508
509         float t = weaponinfo.weaponstartoverride;
510
511         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
512
513         // bit order in t:
514         // 1: want or not
515         // 2: is default?
516         // 4: is set by default?
517         if(t < 0)
518                 t = 4 | (3 * d);
519         else
520                 t |= (2 * d);
521
522         return t;
523 }
524
525 void readplayerstartcvars()
526 {
527         entity e;
528         float i, j, t;
529         string s;
530
531         // initialize starting values for players
532         start_weapons = '0 0 0';
533         start_weapons_default = '0 0 0';
534         start_weapons_defaultmask = '0 0 0';
535         start_items = 0;
536         start_ammo_shells = 0;
537         start_ammo_nails = 0;
538         start_ammo_rockets = 0;
539         start_ammo_cells = 0;
540         start_ammo_plasma = 0;
541         start_health = cvar("g_balance_health_start");
542         start_armorvalue = cvar("g_balance_armor_start");
543
544         g_weaponarena = 0;
545         g_weaponarena_weapons = '0 0 0';
546
547         s = cvar_string("g_weaponarena");
548         if (s == "0" || s == "")
549         {
550                 if(g_ca || g_freezetag)
551                         s = "most";
552         }
553
554         if (s == "0" || s == "")
555         {
556                 // no arena
557         }
558         else if (s == "off")
559         {
560                 // forcibly turn off weaponarena
561         }
562         else if (s == "all" || s == "1")
563         {
564                 g_weaponarena = 1;
565                 g_weaponarena_list = "All Weapons";
566                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
567                 {
568                         e = get_weaponinfo(j);
569                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
570                                 g_weaponarena_weapons |= WepSet_FromWeapon(j);
571                 }
572         }
573         else if (s == "most")
574         {
575                 g_weaponarena = 1;
576                 g_weaponarena_list = "Most Weapons";
577                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
578                 {
579                         e = get_weaponinfo(j);
580                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
581                                 if (e.spawnflags & WEP_FLAG_NORMAL)
582                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
583                 }
584         }
585         else if (s == "none")
586         {
587                 g_weaponarena = 1;
588                 g_weaponarena_list = "No Weapons";
589         }
590         else
591         {
592                 g_weaponarena = 1;
593                 t = tokenize_console(s);
594                 g_weaponarena_list = "";
595                 for (i = 0; i < t; ++i)
596                 {
597                         s = argv(i);
598                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
599                         {
600                                 e = get_weaponinfo(j);
601                                 if (e.netname == s)
602                                 {
603                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
604                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
605                                         break;
606                                 }
607                         }
608                         if (j > WEP_LAST)
609                         {
610                                 LOG_INFO("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
611                         }
612                 }
613                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
614         }
615
616         if(g_weaponarena)
617                 g_weaponarena_random = cvar("g_weaponarena_random");
618         else
619                 g_weaponarena_random = 0;
620         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
621
622         if (g_weaponarena)
623         {
624                 g_weapon_stay = 0; // incompatible
625                 start_weapons = g_weaponarena_weapons;
626                 start_items |= IT_UNLIMITED_AMMO;
627         }
628         else
629         {
630                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
631                 {
632                         e = get_weaponinfo(i);
633                         int w = want_weapon(e, false);
634                         if(w & 1)
635                                 start_weapons |= WepSet_FromWeapon(i);
636                         if(w & 2)
637                                 start_weapons_default |= WepSet_FromWeapon(i);
638                         if(w & 4)
639                                 start_weapons_defaultmask |= WepSet_FromWeapon(i);
640                 }
641         }
642
643         if(!cvar("g_use_ammunition"))
644                 start_items |= IT_UNLIMITED_AMMO;
645
646         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
647         {
648                 start_ammo_shells = 999;
649                 start_ammo_nails = 999;
650                 start_ammo_rockets = 999;
651                 start_ammo_cells = 999;
652                 start_ammo_plasma = 999;
653                 start_ammo_fuel = 999;
654         }
655         else
656         {
657                 start_ammo_shells = cvar("g_start_ammo_shells");
658                 start_ammo_nails = cvar("g_start_ammo_nails");
659                 start_ammo_rockets = cvar("g_start_ammo_rockets");
660                 start_ammo_cells = cvar("g_start_ammo_cells");
661                 start_ammo_plasma = cvar("g_start_ammo_plasma");
662                 start_ammo_fuel = cvar("g_start_ammo_fuel");
663         }
664
665         if (warmup_stage)
666         {
667                 warmup_start_ammo_shells = start_ammo_shells;
668                 warmup_start_ammo_nails = start_ammo_nails;
669                 warmup_start_ammo_rockets = start_ammo_rockets;
670                 warmup_start_ammo_cells = start_ammo_cells;
671                 warmup_start_ammo_plasma = start_ammo_plasma;
672                 warmup_start_ammo_fuel = start_ammo_fuel;
673                 warmup_start_health = start_health;
674                 warmup_start_armorvalue = start_armorvalue;
675                 warmup_start_weapons = start_weapons;
676                 warmup_start_weapons_default = start_weapons_default;
677                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
678
679                 if (!g_weaponarena && !g_ca && !g_freezetag)
680                 {
681                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
682                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
683                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
684                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
685                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
686                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
687                         warmup_start_health = cvar("g_warmup_start_health");
688                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
689                         warmup_start_weapons = '0 0 0';
690                         warmup_start_weapons_default = '0 0 0';
691                         warmup_start_weapons_defaultmask = '0 0 0';
692                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
693                         {
694                                 e = get_weaponinfo(i);
695                                 int w = want_weapon(e, g_warmup_allguns);
696                                 if(w & 1)
697                                         warmup_start_weapons |= WepSet_FromWeapon(i);
698                                 if(w & 2)
699                                         warmup_start_weapons_default |= WepSet_FromWeapon(i);
700                                 if(w & 4)
701                                         warmup_start_weapons_defaultmask |= WepSet_FromWeapon(i);
702                         }
703                 }
704         }
705
706         if (g_jetpack)
707                 start_items |= ITEM_Jetpack.m_itemid;
708
709         MUTATOR_CALLHOOK(SetStartItems);
710
711         if (start_items & ITEM_Jetpack.m_itemid)
712         {
713                 start_items |= ITEM_JetpackRegen.m_itemid;
714                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
715                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
716         }
717
718         WepSet precache_weapons = start_weapons;
719         if (g_warmup_allguns != 1)
720                 precache_weapons |= warmup_start_weapons;
721         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
722         {
723                 e = get_weaponinfo(i);
724                 if(precache_weapons & WepSet_FromWeapon(i)) {
725                         Weapon w = get_weaponinfo(i);
726                         w.wr_init(w);
727                 }
728         }
729
730         start_ammo_shells = max(0, start_ammo_shells);
731         start_ammo_nails = max(0, start_ammo_nails);
732         start_ammo_rockets = max(0, start_ammo_rockets);
733         start_ammo_cells = max(0, start_ammo_cells);
734         start_ammo_plasma = max(0, start_ammo_plasma);
735         start_ammo_fuel = max(0, start_ammo_fuel);
736
737         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
738         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
739         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
740         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
741         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
742         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
743 }
744
745 float sound_allowed(float destin, entity e)
746 {
747     // sounds from world may always pass
748     for (;;)
749     {
750         if (e.classname == "body")
751             e = e.enemy;
752         else if (e.realowner && e.realowner != e)
753             e = e.realowner;
754         else if (e.owner && e.owner != e)
755             e = e.owner;
756         else
757             break;
758     }
759     // sounds to self may always pass
760     if (destin == MSG_ONE)
761         if (e == msg_entity)
762             return true;
763     // sounds by players can be removed
764     if (autocvar_bot_sound_monopoly)
765         if (IS_REAL_CLIENT(e))
766             return false;
767     // anything else may pass
768     return true;
769 }
770
771 void soundtoat(float _dest, entity e, vector o, float chan, string samp, float vol, float attenu)
772 {
773     float entno, idx;
774
775     if (!sound_allowed(_dest, e))
776         return;
777
778     entno = num_for_edict(e);
779     idx = precache_sound_index(samp);
780
781     int sflags;
782     sflags = 0;
783
784     attenu = floor(attenu * 64);
785     vol = floor(vol * 255);
786
787     if (vol != 255)
788         sflags |= SND_VOLUME;
789     if (attenu != 64)
790         sflags |= SND_ATTENUATION;
791     if (entno >= 8192 || chan < 0 || chan > 7)
792         sflags |= SND_LARGEENTITY;
793     if (idx >= 256)
794         sflags |= SND_LARGESOUND;
795
796     WriteByte(_dest, SVC_SOUND);
797     WriteByte(_dest, sflags);
798     if (sflags & SND_VOLUME)
799         WriteByte(_dest, vol);
800     if (sflags & SND_ATTENUATION)
801         WriteByte(_dest, attenu);
802     if (sflags & SND_LARGEENTITY)
803     {
804         WriteShort(_dest, entno);
805         WriteByte(_dest, chan);
806     }
807     else
808     {
809         WriteShort(_dest, entno * 8 + chan);
810     }
811     if (sflags & SND_LARGESOUND)
812         WriteShort(_dest, idx);
813     else
814         WriteByte(_dest, idx);
815
816     WriteCoord(_dest, o.x);
817     WriteCoord(_dest, o.y);
818     WriteCoord(_dest, o.z);
819 }
820 void soundto(float _dest, entity e, float chan, string samp, float vol, float _atten)
821 {
822     vector o;
823
824     if (!sound_allowed(_dest, e))
825         return;
826
827     o = e.origin + 0.5 * (e.mins + e.maxs);
828     soundtoat(_dest, e, o, chan, samp, vol, _atten);
829 }
830 void soundat(entity e, vector o, float chan, string samp, float vol, float _atten)
831 {
832     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, _atten);
833 }
834 void stopsoundto(float _dest, entity e, float chan)
835 {
836     float entno;
837
838     if (!sound_allowed(_dest, e))
839         return;
840
841     entno = num_for_edict(e);
842
843     if (entno >= 8192 || chan < 0 || chan > 7)
844     {
845         float idx, sflags;
846         idx = precache_sound_index(SND(Null));
847         sflags = SND_LARGEENTITY;
848         if (idx >= 256)
849             sflags |= SND_LARGESOUND;
850         WriteByte(_dest, SVC_SOUND);
851         WriteByte(_dest, sflags);
852         WriteShort(_dest, entno);
853         WriteByte(_dest, chan);
854         if (sflags & SND_LARGESOUND)
855             WriteShort(_dest, idx);
856         else
857             WriteByte(_dest, idx);
858         WriteCoord(_dest, e.origin.x);
859         WriteCoord(_dest, e.origin.y);
860         WriteCoord(_dest, e.origin.z);
861     }
862     else
863     {
864         WriteByte(_dest, SVC_STOPSOUND);
865         WriteShort(_dest, entno * 8 + chan);
866     }
867 }
868 void stopsound(entity e, float chan)
869 {
870     if (!sound_allowed(MSG_BROADCAST, e))
871         return;
872
873     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
874     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
875 }
876
877 void play2(entity e, string filename)
878 {
879     //stuffcmd(e, strcat("play2 ", filename, "\n"));
880     msg_entity = e;
881     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTEN_NONE);
882 }
883
884 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
885 .float spamtime;
886 float spamsound(entity e, float chan, string samp, float vol, float _atten)
887 {
888     if (!sound_allowed(MSG_BROADCAST, e))
889         return false;
890
891     if (time > e.spamtime)
892     {
893         e.spamtime = time;
894         _sound(e, chan, samp, vol, _atten);
895         return true;
896     }
897     return false;
898 }
899
900 void play2team(float t, string filename)
901 {
902     entity head;
903
904     if (autocvar_bot_sound_monopoly)
905         return;
906
907     FOR_EACH_REALPLAYER(head)
908     {
909         if (head.team == t)
910             play2(head, filename);
911     }
912 }
913
914 void play2all(string samp)
915 {
916     if (autocvar_bot_sound_monopoly)
917         return;
918
919     _sound(world, CH_INFO, samp, VOL_BASE, ATTEN_NONE);
920 }
921
922 void PrecachePlayerSounds(string f);
923 void precache_playermodel(string m)
924 {
925         float globhandle, i, n;
926         string f;
927
928         if(substring(m, -9,5) == "_lod1")
929                 return;
930         if(substring(m, -9,5) == "_lod2")
931                 return;
932         precache_model(m);
933         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
934         if(fexists(f))
935                 precache_model(f);
936         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
937         if(fexists(f))
938                 precache_model(f);
939
940         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
941         if (globhandle < 0)
942                 return;
943         n = search_getsize(globhandle);
944         for (i = 0; i < n; ++i)
945         {
946                 //print(search_getfilename(globhandle, i), "\n");
947                 f = search_getfilename(globhandle, i);
948                 PrecachePlayerSounds(f);
949         }
950         search_end(globhandle);
951 }
952 void precache_all_playermodels(string pattern)
953 {
954         float globhandle, i, n;
955         string f;
956
957         globhandle = search_begin(pattern, true, false);
958         if (globhandle < 0)
959                 return;
960         n = search_getsize(globhandle);
961         for (i = 0; i < n; ++i)
962         {
963                 //print(search_getfilename(globhandle, i), "\n");
964                 f = search_getfilename(globhandle, i);
965                 precache_playermodel(f);
966         }
967         search_end(globhandle);
968 }
969
970 void precache()
971 {SELFPARAM();
972     // gamemode related things
973
974     // Precache all player models if desired
975     if (autocvar_sv_precacheplayermodels)
976     {
977         PrecachePlayerSounds("sound/player/default.sounds");
978         precache_all_playermodels("models/player/*.zym");
979         precache_all_playermodels("models/player/*.dpm");
980         precache_all_playermodels("models/player/*.md3");
981         precache_all_playermodels("models/player/*.psk");
982         precache_all_playermodels("models/player/*.iqm");
983     }
984
985     if (autocvar_sv_defaultcharacter)
986     {
987         string s;
988         s = autocvar_sv_defaultplayermodel_red;
989         if (s != "")
990             precache_playermodel(s);
991         s = autocvar_sv_defaultplayermodel_blue;
992         if (s != "")
993             precache_playermodel(s);
994         s = autocvar_sv_defaultplayermodel_yellow;
995         if (s != "")
996             precache_playermodel(s);
997         s = autocvar_sv_defaultplayermodel_pink;
998         if (s != "")
999             precache_playermodel(s);
1000         s = autocvar_sv_defaultplayermodel;
1001         if (s != "")
1002             precache_playermodel(s);
1003     }
1004
1005     if (g_footsteps)
1006     {
1007         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1008         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1009     }
1010
1011     // gore and miscellaneous sounds
1012     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1013     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1014
1015 #if 0
1016     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1017
1018     if (!self.noise && self.music) // quake 3 uses the music field
1019         self.noise = self.music;
1020
1021     // plays music for the level if there is any
1022     if (self.noise)
1023     {
1024         precache_sound (self.noise);
1025         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTEN_NONE);
1026     }
1027 #endif
1028 }
1029
1030
1031 void make_safe_for_remove(entity e)
1032 {
1033     if (e.initialize_entity)
1034     {
1035         entity ent, prev = world;
1036         for (ent = initialize_entity_first; ent; )
1037         {
1038             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1039             {
1040                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1041                 // skip it in linked list
1042                 if (prev)
1043                 {
1044                     prev.initialize_entity_next = ent.initialize_entity_next;
1045                     ent = prev.initialize_entity_next;
1046                 }
1047                 else
1048                 {
1049                     initialize_entity_first = ent.initialize_entity_next;
1050                     ent = initialize_entity_first;
1051                 }
1052             }
1053             else
1054             {
1055                 prev = ent;
1056                 ent = ent.initialize_entity_next;
1057             }
1058         }
1059     }
1060 }
1061
1062 void objerror(string s)
1063 {SELFPARAM();
1064     make_safe_for_remove(self);
1065     builtin_objerror(s);
1066 }
1067
1068 .float remove_except_protected_forbidden;
1069 void remove_except_protected(entity e)
1070 {
1071         if(e.remove_except_protected_forbidden)
1072                 error("not allowed to remove this at this point");
1073         builtin_remove(e);
1074 }
1075
1076 void remove_unsafely(entity e)
1077 {
1078     if(e.classname == "spike")
1079         error("Removing spikes is forbidden (crylink bug), please report");
1080     builtin_remove(e);
1081 }
1082
1083 void remove_safely(entity e)
1084 {
1085     make_safe_for_remove(e);
1086     builtin_remove(e);
1087 }
1088
1089 void InitializeEntity(entity e, void(void) func, float order)
1090 {
1091     entity prev, cur;
1092
1093     if (!e || e.initialize_entity)
1094     {
1095         // make a proxy initializer entity
1096         entity e_old = e;
1097         e = new(initialize_entity);
1098         e.enemy = e_old;
1099     }
1100
1101     e.initialize_entity = func;
1102     e.initialize_entity_order = order;
1103
1104     cur = initialize_entity_first;
1105     prev = world;
1106     for (;;)
1107     {
1108         if (!cur || cur.initialize_entity_order > order)
1109         {
1110             // insert between prev and cur
1111             if (prev)
1112                 prev.initialize_entity_next = e;
1113             else
1114                 initialize_entity_first = e;
1115             e.initialize_entity_next = cur;
1116             return;
1117         }
1118         prev = cur;
1119         cur = cur.initialize_entity_next;
1120     }
1121 }
1122 void InitializeEntitiesRun()
1123 {SELFPARAM();
1124     entity startoflist = initialize_entity_first;
1125     initialize_entity_first = NULL;
1126     remove = remove_except_protected;
1127     for (entity e = startoflist; e; e = e.initialize_entity_next)
1128     {
1129                 e.remove_except_protected_forbidden = 1;
1130     }
1131     for (entity e = startoflist; e; )
1132     {
1133                 e.remove_except_protected_forbidden = 0;
1134         e.initialize_entity_order = 0;
1135         entity next = e.initialize_entity_next;
1136         e.initialize_entity_next = NULL;
1137         var void() func = e.initialize_entity;
1138         e.initialize_entity = func_null;
1139         if (e.classname == "initialize_entity")
1140         {
1141             entity wrappee = e.enemy;
1142             builtin_remove(e);
1143             e = wrappee;
1144         }
1145         //dprint("Delayed initialization: ", e.classname, "\n");
1146         if (func)
1147         {
1148                 WITH(entity, self, e, func());
1149         }
1150         else
1151         {
1152             eprint(e);
1153             backtrace(strcat("Null function in: ", e.classname, "\n"));
1154         }
1155         e = next;
1156     }
1157     remove = remove_unsafely;
1158 }
1159
1160 void UncustomizeEntitiesRun()
1161 {SELFPARAM();
1162     for (entity e = NULL; (e = findfloat(e, uncustomizeentityforclient_set, 1)); )
1163     {
1164         WITH(entity, self, e, e.uncustomizeentityforclient());
1165     }
1166 }
1167 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1168 {
1169     e.customizeentityforclient = customizer;
1170     e.uncustomizeentityforclient = uncustomizer;
1171     e.uncustomizeentityforclient_set = !!uncustomizer;
1172 }
1173
1174 void Net_LinkEntity(entity e, bool docull, float dt, bool(entity, int) sendfunc)
1175 {SELFPARAM();
1176     vector mi, ma;
1177
1178     if (e.classname == "")
1179         e.classname = "net_linked";
1180
1181     if (e.model == "" || self.modelindex == 0)
1182     {
1183         mi = e.mins;
1184         ma = e.maxs;
1185         setmodel(e, MDL_Null);
1186         setsize(e, mi, ma);
1187     }
1188
1189     e.SendEntity = sendfunc;
1190     e.SendFlags = 0xFFFFFF;
1191
1192     if (!docull)
1193         e.effects |= EF_NODEPTHTEST;
1194
1195     if (dt)
1196     {
1197         e.nextthink = time + dt;
1198         e.think = SUB_Remove;
1199     }
1200 }
1201
1202
1203 .float(entity) isEliminated;
1204 float EliminatedPlayers_SendEntity(entity to, float sendflags)
1205 {
1206         float i, f, b;
1207         entity e;
1208         WriteByte(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
1209         WriteByte(MSG_ENTITY, sendflags);
1210
1211         if(sendflags & 1)
1212         {
1213                 for(i = 1; i <= maxclients; i += 8)
1214                 {
1215                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
1216                         {
1217                                 if(eliminatedPlayers.isEliminated(e))
1218                                         f |= b;
1219                         }
1220                         WriteByte(MSG_ENTITY, f);
1221                 }
1222         }
1223
1224         return true;
1225 }
1226
1227 void EliminatedPlayers_Init(float(entity) isEliminated_func)
1228 {
1229         if(eliminatedPlayers)
1230         {
1231                 backtrace("Can't spawn eliminatedPlayers again!");
1232                 return;
1233         }
1234         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
1235         eliminatedPlayers.isEliminated = isEliminated_func;
1236 }
1237
1238
1239 void adaptor_think2touch()
1240 {SELFPARAM();
1241     entity o;
1242     o = other;
1243     other = world;
1244     self.touch();
1245     other = o;
1246 }
1247
1248 void adaptor_think2use()
1249 {SELFPARAM();
1250     entity o, a;
1251     o = other;
1252     a = activator;
1253     activator = world;
1254     other = world;
1255     self.use();
1256     other = o;
1257     activator = a;
1258 }
1259
1260 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1261 {SELFPARAM();
1262         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
1263                 self.projectiledeathtype |= HITTYPE_SPLASH;
1264         adaptor_think2use();
1265 }
1266
1267 // deferred dropping
1268 void DropToFloor_Handler()
1269 {SELFPARAM();
1270     builtin_droptofloor();
1271     self.dropped_origin = self.origin;
1272 }
1273
1274 void droptofloor()
1275 {SELFPARAM();
1276     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1277 }
1278
1279
1280
1281 float trace_hits_box_a0, trace_hits_box_a1;
1282
1283 float trace_hits_box_1d(float end, float thmi, float thma)
1284 {
1285     if (end == 0)
1286     {
1287         // just check if x is in range
1288         if (0 < thmi)
1289             return false;
1290         if (0 > thma)
1291             return false;
1292     }
1293     else
1294     {
1295         // do the trace with respect to x
1296         // 0 -> end has to stay in thmi -> thma
1297         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1298         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1299         if (trace_hits_box_a0 > trace_hits_box_a1)
1300             return false;
1301     }
1302     return true;
1303 }
1304
1305 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1306 {
1307     end -= start;
1308     thmi -= start;
1309     thma -= start;
1310     // now it is a trace from 0 to end
1311
1312     trace_hits_box_a0 = 0;
1313     trace_hits_box_a1 = 1;
1314
1315     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1316         return false;
1317     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1318         return false;
1319     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1320         return false;
1321
1322     return true;
1323 }
1324
1325 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1326 {
1327     return trace_hits_box(start, end, thmi - ma, thma - mi);
1328 }
1329
1330 float SUB_NoImpactCheck()
1331 {SELFPARAM();
1332         // zero hitcontents = this is not the real impact, but either the
1333         // mirror-impact of something hitting the projectile instead of the
1334         // projectile hitting the something, or a touchareagrid one. Neither of
1335         // these stop the projectile from moving, so...
1336         if(trace_dphitcontents == 0)
1337         {
1338                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1339                 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));
1340                 checkclient();
1341         }
1342     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1343         return 1;
1344     if (other == world && self.size != '0 0 0')
1345     {
1346         vector tic;
1347         tic = self.velocity * sys_frametime;
1348         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1349         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1350         if (trace_fraction >= 1)
1351         {
1352             LOG_TRACE("Odd... did not hit...?\n");
1353         }
1354         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1355         {
1356             LOG_TRACE("Detected and prevented the sky-grapple bug.\n");
1357             return 1;
1358         }
1359     }
1360
1361     return 0;
1362 }
1363
1364 #define SUB_OwnerCheck() (other && (other == self.owner))
1365
1366 void W_Crylink_Dequeue(entity e);
1367 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1368 {SELFPARAM();
1369         if(SUB_OwnerCheck())
1370                 return true;
1371         if(SUB_NoImpactCheck())
1372         {
1373                 if(self.classname == "nade")
1374                         return false; // no checks here
1375                 else if(self.classname == "grapplinghook")
1376                         RemoveGrapplingHook(self.realowner);
1377                 else if(self.classname == "spike")
1378                 {
1379                         W_Crylink_Dequeue(self);
1380                         remove(self);
1381                 }
1382                 else
1383                         remove(self);
1384                 return true;
1385         }
1386         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1387                 UpdateCSQCProjectile(self);
1388         return false;
1389 }
1390
1391
1392 void URI_Get_Callback(float id, float status, string data)
1393 {
1394         if(url_URI_Get_Callback(id, status, data))
1395         {
1396                 // handled
1397         }
1398         else if (id == URI_GET_DISCARD)
1399         {
1400                 // discard
1401         }
1402         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1403         {
1404                 // sv_cmd curl
1405                 Curl_URI_Get_Callback(id, status, data);
1406         }
1407         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1408         {
1409                 // online ban list
1410                 OnlineBanList_URI_Get_Callback(id, status, data);
1411         }
1412         else
1413         {
1414                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1415         }
1416 }
1417
1418 string uid2name(string myuid) {
1419         string s;
1420         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1421
1422         // FIXME remove this later after 0.6 release
1423         // convert old style broken records to correct style
1424         if(s == "")
1425         {
1426                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1427                 if(s != "")
1428                 {
1429                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1430                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
1431                 }
1432         }
1433
1434         if(s == "")
1435                 s = "^1Unregistered Player";
1436         return s;
1437 }
1438
1439 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1440 {
1441     float m, i;
1442     vector start, org, delta, end, enddown, mstart;
1443     entity sp;
1444
1445     m = e.dphitcontentsmask;
1446     e.dphitcontentsmask = goodcontents | badcontents;
1447
1448     org = boundmin;
1449     delta = boundmax - boundmin;
1450
1451     start = end = org;
1452
1453     for (i = 0; i < attempts; ++i)
1454     {
1455         start.x = org.x + random() * delta.x;
1456         start.y = org.y + random() * delta.y;
1457         start.z = org.z + random() * delta.z;
1458
1459         // rule 1: start inside world bounds, and outside
1460         // solid, and don't start from somewhere where you can
1461         // fall down to evil
1462         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1463         if (trace_fraction >= 1)
1464             continue;
1465         if (trace_startsolid)
1466             continue;
1467         if (trace_dphitcontents & badcontents)
1468             continue;
1469         if (trace_dphitq3surfaceflags & badsurfaceflags)
1470             continue;
1471
1472         // rule 2: if we are too high, lower the point
1473         if (trace_fraction * delta.z > maxaboveground)
1474             start = trace_endpos + '0 0 1' * maxaboveground;
1475         enddown = trace_endpos;
1476
1477         // rule 3: make sure we aren't outside the map. This only works
1478         // for somewhat well formed maps. A good rule of thumb is that
1479         // the map should have a convex outside hull.
1480         // these can be traceLINES as we already verified the starting box
1481         mstart = start + 0.5 * (e.mins + e.maxs);
1482         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1483         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1484             continue;
1485         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1486         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1487             continue;
1488         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1489         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1490             continue;
1491         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1492         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1493             continue;
1494         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1495         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1496             continue;
1497
1498         // rule 4: we must "see" some spawnpoint or item
1499         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
1500                 if(checkpvs(mstart, sp))
1501                         if((traceline(mstart, sp.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1502                                 break;
1503         if(!sp)
1504         {
1505                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
1506                         if(checkpvs(mstart, sp))
1507                                 if((traceline(mstart, sp.origin + (sp.mins + sp.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1508                                         break;
1509                 if(!sp)
1510                         continue;
1511         }
1512
1513         // find a random vector to "look at"
1514         end.x = org.x + random() * delta.x;
1515         end.y = org.y + random() * delta.y;
1516         end.z = org.z + random() * delta.z;
1517         end = start + normalize(end - start) * vlen(delta);
1518
1519         // rule 4: start TO end must not be too short
1520         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1521         if (trace_startsolid)
1522             continue;
1523         if (trace_fraction < minviewdistance / vlen(delta))
1524             continue;
1525
1526         // rule 5: don't want to look at sky
1527         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1528             continue;
1529
1530         // rule 6: we must not end up in trigger_hurt
1531         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1532             continue;
1533
1534         break;
1535     }
1536
1537     e.dphitcontentsmask = m;
1538
1539     if (i < attempts)
1540     {
1541         setorigin(e, start);
1542         e.angles = vectoangles(end - start);
1543         LOG_TRACE("Needed ", ftos(i + 1), " attempts\n");
1544         return true;
1545     }
1546     else
1547         return false;
1548 }
1549
1550 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1551 {
1552         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1553 }
1554
1555 void write_recordmarker(entity pl, float tstart, float dt)
1556 {
1557     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1558
1559     // also write a marker into demo files for demotc-race-record-extractor to find
1560     stuffcmd(pl,
1561              strcat(
1562                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1563                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1564 }
1565
1566 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float allowcenter, float algn)
1567 {
1568         switch(algn)
1569         {
1570                 default:
1571                 case 3: // right
1572                         break;
1573
1574                 case 4: // left
1575                         vecs.y = -vecs.y;
1576                         break;
1577
1578                 case 1:
1579                         if(allowcenter) // 2: allow center handedness
1580                         {
1581                                 // center
1582                                 vecs.y = 0;
1583                                 vecs.z -= 2;
1584                         }
1585                         else
1586                         {
1587                                 // right
1588                         }
1589                         break;
1590
1591                 case 2:
1592                         if(allowcenter) // 2: allow center handedness
1593                         {
1594                                 // center
1595                                 vecs.y = 0;
1596                                 vecs.z -= 2;
1597                         }
1598                         else
1599                         {
1600                                 // left
1601                                 vecs.y = -vecs.y;
1602                         }
1603                         break;
1604         }
1605         return vecs;
1606 }
1607
1608 vector shotorg_adjust_values(vector vecs, float y_is_right, float visual, float algn)
1609 {
1610         string s;
1611         vector v;
1612
1613         if (autocvar_g_shootfromeye)
1614         {
1615                 if (visual)
1616                 {
1617                         if (autocvar_g_shootfromclient) { vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn); }
1618                         else { vecs.y = 0; vecs.z -= 2; }
1619                 }
1620                 else
1621                 {
1622                         vecs.y = 0;
1623                         vecs.z = 0;
1624                 }
1625         }
1626         else if (autocvar_g_shootfromcenter)
1627         {
1628                 vecs.y = 0;
1629                 vecs.z -= 2;
1630         }
1631         else if ((s = autocvar_g_shootfromfixedorigin) != "")
1632         {
1633                 v = stov(s);
1634                 if (y_is_right)
1635                         v.y = -v.y;
1636                 if (v.x != 0)
1637                         vecs.x = v.x;
1638                 vecs.y = v.y;
1639                 vecs.z = v.z;
1640         }
1641         else if (autocvar_g_shootfromclient)
1642         {
1643                 vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn);
1644         }
1645         return vecs;
1646 }
1647
1648 vector shotorg_adjust(vector vecs, float y_is_right, float visual)
1649 {SELFPARAM();
1650         return shotorg_adjust_values(vecs, y_is_right, visual, self.owner.cvar_cl_gunalign);
1651 }
1652
1653
1654 void attach_sameorigin(entity e, entity to, string tag)
1655 {
1656     vector org, t_forward, t_left, t_up, e_forward, e_up;
1657     float tagscale;
1658
1659     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1660     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1661     t_forward = v_forward * tagscale;
1662     t_left = v_right * -tagscale;
1663     t_up = v_up * tagscale;
1664
1665     e.origin_x = org * t_forward;
1666     e.origin_y = org * t_left;
1667     e.origin_z = org * t_up;
1668
1669     // current forward and up directions
1670     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1671                 e.angles = AnglesTransform_FromVAngles(e.angles);
1672         else
1673                 e.angles = AnglesTransform_FromAngles(e.angles);
1674     fixedmakevectors(e.angles);
1675
1676     // untransform forward, up!
1677     e_forward.x = v_forward * t_forward;
1678     e_forward.y = v_forward * t_left;
1679     e_forward.z = v_forward * t_up;
1680     e_up.x = v_up * t_forward;
1681     e_up.y = v_up * t_left;
1682     e_up.z = v_up * t_up;
1683
1684     e.angles = fixedvectoangles2(e_forward, e_up);
1685     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1686                 e.angles = AnglesTransform_ToVAngles(e.angles);
1687         else
1688                 e.angles = AnglesTransform_ToAngles(e.angles);
1689
1690     setattachment(e, to, tag);
1691     setorigin(e, e.origin);
1692 }
1693
1694 void detach_sameorigin(entity e)
1695 {
1696     vector org;
1697     org = gettaginfo(e, 0);
1698     e.angles = fixedvectoangles2(v_forward, v_up);
1699     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1700                 e.angles = AnglesTransform_ToVAngles(e.angles);
1701         else
1702                 e.angles = AnglesTransform_ToAngles(e.angles);
1703     setorigin(e, org);
1704     setattachment(e, world, "");
1705     setorigin(e, e.origin);
1706 }
1707
1708 void follow_sameorigin(entity e, entity to)
1709 {
1710     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
1711     e.aiment = to; // make the hole follow bmodel
1712     e.punchangle = to.angles; // the original angles of bmodel
1713     e.view_ofs = e.origin - to.origin; // relative origin
1714     e.v_angle = e.angles - to.angles; // relative angles
1715 }
1716
1717 void unfollow_sameorigin(entity e)
1718 {
1719     e.movetype = MOVETYPE_NONE;
1720 }
1721
1722 entity gettaginfo_relative_ent;
1723 vector gettaginfo_relative(entity e, float tag)
1724 {
1725     if (!gettaginfo_relative_ent)
1726     {
1727         gettaginfo_relative_ent = spawn();
1728         gettaginfo_relative_ent.effects = EF_NODRAW;
1729     }
1730     gettaginfo_relative_ent.model = e.model;
1731     gettaginfo_relative_ent.modelindex = e.modelindex;
1732     gettaginfo_relative_ent.frame = e.frame;
1733     return gettaginfo(gettaginfo_relative_ent, tag);
1734 }
1735
1736 .float scale2;
1737
1738 float modeleffect_SendEntity(entity to, int sf)
1739 {SELFPARAM();
1740         float f;
1741         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
1742
1743         f = 0;
1744         if(self.velocity != '0 0 0')
1745                 f |= 1;
1746         if(self.angles != '0 0 0')
1747                 f |= 2;
1748         if(self.avelocity != '0 0 0')
1749                 f |= 4;
1750
1751         WriteByte(MSG_ENTITY, f);
1752         WriteShort(MSG_ENTITY, self.modelindex);
1753         WriteByte(MSG_ENTITY, self.skin);
1754         WriteByte(MSG_ENTITY, self.frame);
1755         WriteCoord(MSG_ENTITY, self.origin.x);
1756         WriteCoord(MSG_ENTITY, self.origin.y);
1757         WriteCoord(MSG_ENTITY, self.origin.z);
1758         if(f & 1)
1759         {
1760                 WriteCoord(MSG_ENTITY, self.velocity.x);
1761                 WriteCoord(MSG_ENTITY, self.velocity.y);
1762                 WriteCoord(MSG_ENTITY, self.velocity.z);
1763         }
1764         if(f & 2)
1765         {
1766                 WriteCoord(MSG_ENTITY, self.angles.x);
1767                 WriteCoord(MSG_ENTITY, self.angles.y);
1768                 WriteCoord(MSG_ENTITY, self.angles.z);
1769         }
1770         if(f & 4)
1771         {
1772                 WriteCoord(MSG_ENTITY, self.avelocity.x);
1773                 WriteCoord(MSG_ENTITY, self.avelocity.y);
1774                 WriteCoord(MSG_ENTITY, self.avelocity.z);
1775         }
1776         WriteShort(MSG_ENTITY, self.scale * 256.0);
1777         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
1778         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
1779         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
1780         WriteByte(MSG_ENTITY, self.alpha * 255.0);
1781
1782         return true;
1783 }
1784
1785 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)
1786 {
1787         entity e;
1788         float sz;
1789         e = spawn();
1790         e.classname = "modeleffect";
1791         _setmodel(e, m);
1792         e.frame = f;
1793         setorigin(e, o);
1794         e.velocity = v;
1795         e.angles = ang;
1796         e.avelocity = angv;
1797         e.alpha = a;
1798         e.teleport_time = t1;
1799         e.fade_time = t2;
1800         e.skin = s;
1801         if(s0 >= 0)
1802                 e.scale = s0 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1803         else
1804                 e.scale = -s0;
1805         if(s2 >= 0)
1806                 e.scale2 = s2 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1807         else
1808                 e.scale2 = -s2;
1809         sz = max(e.scale, e.scale2);
1810         setsize(e, e.mins * sz, e.maxs * sz);
1811         Net_LinkEntity(e, false, 0.1, modeleffect_SendEntity);
1812 }
1813
1814 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
1815 {
1816         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
1817 }
1818
1819 float randombit(float bits)
1820 {
1821         if(!(bits & (bits-1))) // this ONLY holds for powers of two!
1822                 return bits;
1823
1824         float n, f, b, r;
1825
1826         r = random();
1827         b = 0;
1828         n = 0;
1829
1830         for(f = 1; f <= bits; f *= 2)
1831         {
1832                 if(bits & f)
1833                 {
1834                         ++n;
1835                         r *= n;
1836                         if(r <= 1)
1837                                 b = f;
1838                         else
1839                                 r = (r - 1) / (n - 1);
1840                 }
1841         }
1842
1843         return b;
1844 }
1845
1846 float randombits(float bits, float k, float error_return)
1847 {
1848         float r;
1849         r = 0;
1850         while(k > 0 && bits != r)
1851         {
1852                 r += randombit(bits - r);
1853                 --k;
1854         }
1855         if(error_return)
1856                 if(k > 0)
1857                         return -1; // all
1858         return r;
1859 }
1860
1861 void randombit_test(float bits, float iter)
1862 {
1863         while(iter > 0)
1864         {
1865                 LOG_INFO(ftos(randombit(bits)), "\n");
1866                 --iter;
1867         }
1868 }
1869
1870 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
1871 {
1872         if(halflifedist > 0)
1873                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
1874         else if(halflifedist < 0)
1875                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
1876         else
1877                 return 1;
1878 }
1879
1880
1881 .string aiment_classname;
1882 .float aiment_deadflag;
1883 void SetMovetypeFollow(entity ent, entity e)
1884 {
1885         // FIXME this may not be warpzone aware
1886         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
1887         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.
1888         ent.aiment = e; // make the hole follow bmodel
1889         ent.punchangle = e.angles; // the original angles of bmodel
1890         ent.view_ofs = ent.origin - e.origin; // relative origin
1891         ent.v_angle = ent.angles - e.angles; // relative angles
1892         ent.aiment_classname = strzone(e.classname);
1893         ent.aiment_deadflag = e.deadflag;
1894 }
1895 void UnsetMovetypeFollow(entity ent)
1896 {
1897         ent.movetype = MOVETYPE_FLY;
1898         PROJECTILE_MAKETRIGGER(ent);
1899         ent.aiment = world;
1900 }
1901 float LostMovetypeFollow(entity ent)
1902 {
1903 /*
1904         if(ent.movetype != MOVETYPE_FOLLOW)
1905                 if(ent.aiment)
1906                         error("???");
1907 */
1908         if(ent.aiment)
1909         {
1910                 if(ent.aiment.classname != ent.aiment_classname)
1911                         return 1;
1912                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1913                         return 1;
1914         }
1915         return 0;
1916 }
1917
1918 float isPushable(entity e)
1919 {
1920         if(e.pushable)
1921                 return true;
1922         if(IS_VEHICLE(e))
1923                 return false;
1924         if(e.iscreature)
1925                 return true;
1926         switch(e.classname)
1927         {
1928                 case "body":
1929                 case "droppedweapon":
1930                 case "keepawayball":
1931                 case "nexball_basketball":
1932                 case "nexball_football":
1933                         return true;
1934                 case "bullet": // antilagged bullets can't hit this either
1935                         return false;
1936         }
1937         if (e.projectiledeathtype)
1938                 return true;
1939         return false;
1940 }