]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
Merge branch 'master' into Mario/overkill
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 #include "miscfunctions.qh"
2 #include "antilag.qh"
3 #include "command/common.qh"
4 #include "constants.qh"
5 #include "g_hook.qh"
6 #include "ipban.qh"
7 #include "mutators/_mod.qh"
8 #include "../common/t_items.qh"
9 #include "weapons/accuracy.qh"
10 #include "weapons/csqcprojectile.qh"
11 #include "weapons/selection.qh"
12 #include "../common/command/_mod.qh"
13 #include "../common/constants.qh"
14 #include <common/net_linked.qh>
15 #include "../common/deathtypes/all.qh"
16 #include "../common/mapinfo.qh"
17 #include "../common/notifications/all.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 "../common/vehicles/sv_vehicles.qh"
25 #include "../common/vehicles/vehicle.qh"
26 #include "../common/items/_mod.qh"
27 #include "../common/state.qh"
28 #include "../common/effects/qc/globalsound.qh"
29 #include "../common/wepent.qh"
30 #include "../lib/csqcmodel/sv_model.qh"
31 #include "../lib/warpzone/anglestransform.qh"
32 #include "../lib/warpzone/server.qh"
33
34 void crosshair_trace(entity pl)
35 {
36         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));
37 }
38 .bool ctrace_solidchanged;
39 void crosshair_trace_plusvisibletriggers(entity pl)
40 {
41         FOREACH_ENTITY_FLOAT(solid, SOLID_TRIGGER,
42         {
43                 if(it.model != "")
44                 {
45                         it.solid = SOLID_BSP;
46                         it.ctrace_solidchanged = true;
47                 }
48         });
49
50         crosshair_trace(pl);
51
52         FOREACH_ENTITY_FLOAT(ctrace_solidchanged, true,
53         {
54                 it.solid = SOLID_TRIGGER;
55                 it.ctrace_solidchanged = false;
56         });
57 }
58 void WarpZone_crosshair_trace(entity pl)
59 {
60         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));
61 }
62
63
64 string admin_name()
65 {
66         if(autocvar_sv_adminnick != "")
67                 return autocvar_sv_adminnick;
68         else
69                 return "SERVER ADMIN";
70 }
71
72
73 void GameLogEcho(string s)
74 {
75     string fn;
76     int matches;
77
78     if (autocvar_sv_eventlog_files)
79     {
80         if (!logfile_open)
81         {
82             logfile_open = true;
83             matches = autocvar_sv_eventlog_files_counter + 1;
84             cvar_set("sv_eventlog_files_counter", itos(matches));
85             fn = ftos(matches);
86             if (strlen(fn) < 8)
87                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
88             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
89             logfile = fopen(fn, FILE_APPEND);
90             fputs(logfile, ":logversion:3\n");
91         }
92         if (logfile >= 0)
93         {
94             if (autocvar_sv_eventlog_files_timestamps)
95                 fputs(logfile, strcat(":time:", strftime(true, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
96             else
97                 fputs(logfile, strcat(s, "\n"));
98         }
99     }
100     if (autocvar_sv_eventlog_console)
101     {
102         dedicated_print(strcat(s, "\n"));
103     }
104 }
105
106 void GameLogInit()
107 {
108     logfile_open = 0;
109     // will be opened later
110 }
111
112 void GameLogClose()
113 {
114     if (logfile_open && logfile >= 0)
115     {
116         fclose(logfile);
117         logfile = -1;
118     }
119 }
120
121 entity findnearest(vector point, .string field, string value, vector axismod)
122 {
123     entity localhead;
124     float i;
125     float j;
126     float len;
127     vector dist;
128
129     float num_nearest;
130     num_nearest = 0;
131
132     localhead = find(NULL, field, value);
133     while (localhead)
134     {
135         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
136             dist = localhead.oldorigin;
137         else
138             dist = localhead.origin;
139         dist = dist - point;
140         dist = dist.x * axismod.x * '1 0 0' + dist.y * axismod.y * '0 1 0' + dist.z * axismod.z * '0 0 1';
141         len = vlen(dist);
142
143         for (i = 0; i < num_nearest; ++i)
144         {
145             if (len < nearest_length[i])
146                 break;
147         }
148
149         // now i tells us where to insert at
150         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
151         if (i < NUM_NEAREST_ENTITIES)
152         {
153             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
154             {
155                 nearest_length[j + 1] = nearest_length[j];
156                 nearest_entity[j + 1] = nearest_entity[j];
157             }
158             nearest_length[i] = len;
159             nearest_entity[i] = localhead;
160             if (num_nearest < NUM_NEAREST_ENTITIES)
161                 num_nearest = num_nearest + 1;
162         }
163
164         localhead = find(localhead, field, value);
165     }
166
167     // now use the first one from our list that we can see
168     for (i = 0; i < num_nearest; ++i)
169     {
170         traceline(point, nearest_entity[i].origin, true, NULL);
171         if (trace_fraction == 1)
172         {
173             if (i != 0)
174             {
175                 LOG_TRACE("Nearest point (");
176                 LOG_TRACE(nearest_entity[0].netname);
177                 LOG_TRACE(") is not visible, using a visible one.");
178             }
179             return nearest_entity[i];
180         }
181     }
182
183     if (num_nearest == 0)
184         return NULL;
185
186     LOG_TRACE("Not seeing any location point, using nearest as fallback.");
187     /* DEBUGGING CODE:
188     dprint("Candidates were: ");
189     for(j = 0; j < num_nearest; ++j)
190     {
191         if(j != 0)
192                 dprint(", ");
193         dprint(nearest_entity[j].netname);
194     }
195     dprint("\n");
196     */
197
198     return nearest_entity[0];
199 }
200
201 string NearestLocation(vector p)
202 {
203     entity loc;
204     string ret;
205     ret = "somewhere";
206     loc = findnearest(p, classname, "target_location", '1 1 1');
207     if (loc)
208     {
209         ret = loc.message;
210     }
211     else
212     {
213         loc = findnearest(p, target, "###item###", '1 1 4');
214         if (loc)
215             ret = loc.netname;
216     }
217     return ret;
218 }
219
220 string AmmoNameFromWeaponentity(entity wpn)
221 {
222         string ammoitems = "batteries";
223         switch((wpn.m_weapon).ammo_field)
224         {
225                 case ammo_shells:  ammoitems = ITEM_Shells.m_name;      break;
226                 case ammo_nails:   ammoitems = ITEM_Bullets.m_name;     break;
227                 case ammo_rockets: ammoitems = ITEM_Rockets.m_name;     break;
228                 case ammo_cells:   ammoitems = ITEM_Cells.m_name;       break;
229                 case ammo_plasma:  ammoitems = ITEM_Plasma.m_name;      break;
230                 case ammo_fuel:    ammoitems = ITEM_JetpackFuel.m_name; break;
231         }
232         return ammoitems;
233 }
234
235 string formatmessage(entity this, string msg)
236 {
237         float p, p1, p2;
238         float n;
239         vector cursor;
240         entity cursor_ent;
241         string escape;
242         string replacement;
243         p = 0;
244         n = 7;
245
246         WarpZone_crosshair_trace(this);
247         cursor = trace_endpos;
248         cursor_ent = trace_ent;
249
250         MUTATOR_CALLHOOK(PreFormatMessage, this, msg);
251         msg = M_ARGV(1, string);
252
253         while (1) {
254                 if (n < 1)
255                         break; // too many replacements
256
257                 n = n - 1;
258                 p1 = strstrofs(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
259                 p2 = strstrofs(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
260
261                 if (p1 < 0)
262                         p1 = p2;
263
264                 if (p2 < 0)
265                         p2 = p1;
266
267                 p = min(p1, p2);
268
269                 if (p < 0)
270                         break;
271
272                 replacement = substring(msg, p, 2);
273                 escape = substring(msg, p + 1, 1);
274
275                 .entity weaponentity = weaponentities[0]; // TODO: unhardcode
276
277                 switch(escape)
278                 {
279                         case "%": replacement = "%"; break;
280                         case "\\":replacement = "\\"; break;
281                         case "n": replacement = "\n"; break;
282                         case "a": replacement = ftos(floor(this.armorvalue)); break;
283                         case "h": replacement = ftos(floor(this.health)); break;
284                         case "l": replacement = NearestLocation(this.origin); break;
285                         case "y": replacement = NearestLocation(cursor); break;
286                         case "d": replacement = NearestLocation(this.death_origin); break;
287                         case "w": replacement = ((this.(weaponentity).m_weapon == WEP_Null) ? ((this.(weaponentity).m_switchweapon == WEP_Null) ? Weapons_from(this.(weaponentity).cnt) : this.(weaponentity).m_switchweapon) : this.(weaponentity).m_weapon).m_name; break;
288                         case "W": replacement = AmmoNameFromWeaponentity(this.(weaponentity)); break;
289                         case "x": replacement = ((cursor_ent.netname == "" || !cursor_ent) ? "nothing" : cursor_ent.netname); break;
290                         case "s": replacement = ftos(vlen(this.velocity - this.velocity_z * '0 0 1')); break;
291                         case "S": replacement = ftos(vlen(this.velocity)); break;
292                         case "t": replacement = seconds_tostring(ceil(max(0, autocvar_timelimit * 60 + game_starttime - time))); break;
293                         case "T": replacement = seconds_tostring(floor(time - game_starttime)); break;
294                         default:
295                         {
296                                 MUTATOR_CALLHOOK(FormatMessage, this, escape, replacement, msg);
297                                 replacement = M_ARGV(2, string);
298                                 break;
299                         }
300                 }
301
302                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
303                 p = p + strlen(replacement);
304         }
305         return msg;
306 }
307
308 /*
309 =============
310 GetCvars
311 =============
312 Called with:
313   0:  sends the request
314   >0: receives a cvar from name=argv(f) value=argv(f+1)
315 */
316 void GetCvars_handleString(entity this, string thisname, float f, .string field, string name)
317 {
318         if (f < 0)
319         {
320                 if (this.(field))
321                         strunzone(this.(field));
322                 this.(field) = string_null;
323         }
324         else if (f > 0)
325         {
326                 if (thisname == name)
327                 {
328                         if (this.(field))
329                                 strunzone(this.(field));
330                         this.(field) = strzone(argv(f + 1));
331                 }
332         }
333         else
334                 stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
335 }
336 void GetCvars_handleString_Fixup(entity this, string thisname, float f, .string field, string name, string(entity, string) func)
337 {
338         GetCvars_handleString(this, thisname, f, field, name);
339         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
340                 if (thisname == name)
341                 {
342                         string s = func(this, strcat1(this.(field)));
343                         if (s != this.(field))
344                         {
345                                 strunzone(this.(field));
346                                 this.(field) = strzone(s);
347                         }
348                 }
349 }
350 void GetCvars_handleFloat(entity this, string thisname, float f, .float field, string name)
351 {
352         if (f < 0)
353         {
354         }
355         else if (f > 0)
356         {
357                 if (thisname == name)
358                         this.(field) = stof(argv(f + 1));
359         }
360         else
361                 stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
362 }
363 void GetCvars_handleFloatOnce(entity this, string thisname, float f, .float field, string name)
364 {
365         if (f < 0)
366         {
367         }
368         else if (f > 0)
369         {
370                 if (thisname == name)
371                 {
372                         if (!this.(field))
373                         {
374                                 this.(field) = stof(argv(f + 1));
375                                 if (!this.(field))
376                                         this.(field) = -1;
377                         }
378                 }
379         }
380         else
381         {
382                 if (!this.(field))
383                         stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
384         }
385 }
386 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(entity this, string wo)
387 {
388         string o;
389         o = W_FixWeaponOrder_ForceComplete(wo);
390         if(this.weaponorder_byimpulse)
391         {
392                 strunzone(this.weaponorder_byimpulse);
393                 this.weaponorder_byimpulse = string_null;
394         }
395         this.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
396         return o;
397 }
398
399 REPLICATE(autoswitch, bool, "cl_autoswitch");
400
401 REPLICATE(cvar_cl_allow_uid2name, bool, "cl_allow_uid2name");
402
403 REPLICATE(cvar_cl_autoscreenshot, int, "cl_autoscreenshot");
404
405 REPLICATE(cvar_cl_autotaunt, float, "cl_autotaunt");
406
407 REPLICATE(cvar_cl_clippedspectating, bool, "cl_clippedspectating");
408
409 REPLICATE(cvar_cl_handicap, float, "cl_handicap");
410
411 REPLICATE(cvar_cl_jetpack_jump, bool, "cl_jetpack_jump");
412
413 REPLICATE(cvar_cl_movement_track_canjump, bool, "cl_movement_track_canjump");
414
415 REPLICATE(cvar_cl_newusekeysupported, bool, "cl_newusekeysupported");
416
417 REPLICATE(cvar_cl_noantilag, bool, "cl_noantilag");
418
419 REPLICATE(cvar_cl_physics, string, "cl_physics");
420
421 REPLICATE(cvar_cl_voice_directional, int, "cl_voice_directional");
422
423 REPLICATE(cvar_cl_voice_directional_taunt_attenuation, float, "cl_voice_directional_taunt_attenuation");
424
425 REPLICATE(cvar_cl_weaponimpulsemode, int, "cl_weaponimpulsemode");
426
427 REPLICATE(cvar_g_xonoticversion, string, "g_xonoticversion");
428
429 /**
430  * @param f -1: cleanup, 0: request, 1: receive
431  */
432 void GetCvars(entity this, int f)
433 {
434         string s = string_null;
435
436         if (f > 0)
437                 s = strcat1(argv(f));
438
439         get_cvars_f = f;
440         get_cvars_s = s;
441         MUTATOR_CALLHOOK(GetCvars);
442
443         Notification_GetCvars(this);
444
445         ReplicateVars(this, s, f);
446
447         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
448         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
449         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
450         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
451         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
452         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
453         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
454         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
455         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
456         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
457         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
458
459         GetCvars_handleFloat(this, s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
460
461         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
462         if (f > 0)
463         {
464                 if (s == "cl_weaponpriority")
465                 {
466                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
467                         {
468                                 .entity weaponentity = weaponentities[slot];
469                                 if (this.(weaponentity) && (this.(weaponentity).m_weapon != WEP_Null || slot == 0))
470                                         this.(weaponentity).m_switchweapon = w_getbestweapon(this, weaponentity);
471                         }
472                 }
473                 if (s == "cl_allow_uidtracking")
474                         PlayerStats_GameReport_AddPlayer(this);
475         }
476 }
477
478 // decolorizes and team colors the player name when needed
479 string playername(entity p)
480 {
481     string t;
482     if (teamplay && !intermission_running && IS_PLAYER(p))
483     {
484         t = Team_ColorCode(p.team);
485         return strcat(t, strdecolorize(p.netname));
486     }
487     else
488         return p.netname;
489 }
490
491 float want_weapon(entity weaponinfo, float allguns) // WEAPONTODO: what still needs done?
492 {
493         int i = weaponinfo.m_id;
494         int d = 0;
495         bool allow_mutatorblocked = false;
496
497         if(!i)
498                 return 0;
499
500         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
501         d = M_ARGV(1, float);
502         allguns = M_ARGV(2, bool);
503         allow_mutatorblocked = M_ARGV(3, bool);
504
505         if(allguns)
506         {
507                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
508                         d = true;
509                 else
510                         d = false;
511         }
512         else if(!mutator_returnvalue)
513                 d = !(!weaponinfo.weaponstart);
514
515         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
516                 d = 0;
517
518         float t = weaponinfo.weaponstartoverride;
519
520         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
521
522         // bit order in t:
523         // 1: want or not
524         // 2: is default?
525         // 4: is set by default?
526         if(t < 0)
527                 t = 4 | (3 * d);
528         else
529                 t |= (2 * d);
530
531         return t;
532 }
533
534 void readplayerstartcvars()
535 {
536         float i, t;
537         string s;
538
539         // initialize starting values for players
540         start_weapons = '0 0 0';
541         start_weapons_default = '0 0 0';
542         start_weapons_defaultmask = '0 0 0';
543         start_items = 0;
544         start_ammo_shells = 0;
545         start_ammo_nails = 0;
546         start_ammo_rockets = 0;
547         start_ammo_cells = 0;
548         start_ammo_plasma = 0;
549         start_health = cvar("g_balance_health_start");
550         start_armorvalue = cvar("g_balance_armor_start");
551
552         g_weaponarena = 0;
553         g_weaponarena_weapons = '0 0 0';
554
555         s = cvar_string("g_weaponarena");
556
557         MUTATOR_CALLHOOK(SetWeaponArena, s);
558         s = M_ARGV(0, string);
559
560         if (s == "0" || s == "")
561         {
562                 // no arena
563         }
564         else if (s == "off")
565         {
566                 // forcibly turn off weaponarena
567         }
568         else if (s == "all" || s == "1")
569         {
570                 g_weaponarena = 1;
571                 g_weaponarena_list = "All Weapons";
572                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
573                         if(!(it.spawnflags & WEP_FLAG_MUTATORBLOCKED))
574                                 g_weaponarena_weapons |= (it.m_wepset);
575                 ));
576         }
577         else if (s == "devall")
578         {
579                 g_weaponarena = 1;
580                 g_weaponarena_list = "All Weapons"; // TODO: report as more than just all weapons?
581                 FOREACH(Weapons, it != WEP_Null,
582                 {
583                         g_weaponarena_weapons |= (it.m_wepset);
584                 });
585         }
586         else if (s == "most")
587         {
588                 g_weaponarena = 1;
589                 g_weaponarena_list = "Most Weapons";
590                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
591                         if(!(it.spawnflags & WEP_FLAG_MUTATORBLOCKED))
592                                 if(it.spawnflags & WEP_FLAG_NORMAL)
593                                         g_weaponarena_weapons |= (it.m_wepset);
594                 ));
595         }
596         else if (s == "none")
597         {
598                 g_weaponarena = 1;
599                 g_weaponarena_list = "No Weapons";
600         }
601         else
602         {
603                 g_weaponarena = 1;
604                 t = tokenize_console(s);
605                 g_weaponarena_list = "";
606                 for (i = 0; i < t; ++i)
607                 {
608                         s = argv(i);
609                         FOREACH(Weapons, it != WEP_Null, LAMBDA(
610                                 if(it.netname == s)
611                                 {
612                                         g_weaponarena_weapons |= (it.m_wepset);
613                                         g_weaponarena_list = strcat(g_weaponarena_list, it.m_name, " & ");
614                                         break;
615                                 }
616                         ));
617                 }
618                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
619         }
620
621         if(g_weaponarena)
622                 g_weaponarena_random = cvar("g_weaponarena_random");
623         else
624                 g_weaponarena_random = 0;
625         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
626
627         if (g_weaponarena)
628         {
629                 g_weapon_stay = 0; // incompatible
630                 start_weapons = g_weaponarena_weapons;
631                 start_items |= IT_UNLIMITED_AMMO;
632         }
633         else
634         {
635                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
636                         int w = want_weapon(it, false);
637                         WepSet s = it.m_wepset;
638                         if(w & 1)
639                                 start_weapons |= s;
640                         if(w & 2)
641                                 start_weapons_default |= s;
642                         if(w & 4)
643                                 start_weapons_defaultmask |= s;
644                 ));
645         }
646
647         if(!cvar("g_use_ammunition"))
648                 start_items |= IT_UNLIMITED_AMMO;
649
650         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
651         {
652                 start_ammo_shells = 999;
653                 start_ammo_nails = 999;
654                 start_ammo_rockets = 999;
655                 start_ammo_cells = 999;
656                 start_ammo_plasma = 999;
657                 start_ammo_fuel = 999;
658         }
659         else
660         {
661                 start_ammo_shells = cvar("g_start_ammo_shells");
662                 start_ammo_nails = cvar("g_start_ammo_nails");
663                 start_ammo_rockets = cvar("g_start_ammo_rockets");
664                 start_ammo_cells = cvar("g_start_ammo_cells");
665                 start_ammo_plasma = cvar("g_start_ammo_plasma");
666                 start_ammo_fuel = cvar("g_start_ammo_fuel");
667         }
668
669         if (warmup_stage)
670         {
671                 warmup_start_ammo_shells = start_ammo_shells;
672                 warmup_start_ammo_nails = start_ammo_nails;
673                 warmup_start_ammo_rockets = start_ammo_rockets;
674                 warmup_start_ammo_cells = start_ammo_cells;
675                 warmup_start_ammo_plasma = start_ammo_plasma;
676                 warmup_start_ammo_fuel = start_ammo_fuel;
677                 warmup_start_health = start_health;
678                 warmup_start_armorvalue = start_armorvalue;
679                 warmup_start_weapons = start_weapons;
680                 warmup_start_weapons_default = start_weapons_default;
681                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
682
683                 if (!g_weaponarena && !g_ca && !g_freezetag)
684                 {
685                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
686                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
687                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
688                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
689                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
690                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
691                         warmup_start_health = cvar("g_warmup_start_health");
692                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
693                         warmup_start_weapons = '0 0 0';
694                         warmup_start_weapons_default = '0 0 0';
695                         warmup_start_weapons_defaultmask = '0 0 0';
696                         FOREACH(Weapons, it != WEP_Null, LAMBDA(
697                                 int w = want_weapon(it, g_warmup_allguns);
698                                 WepSet s = (it.m_wepset);
699                                 if(w & 1)
700                                         warmup_start_weapons |= s;
701                                 if(w & 2)
702                                         warmup_start_weapons_default |= s;
703                                 if(w & 4)
704                                         warmup_start_weapons_defaultmask |= s;
705                         ));
706                 }
707         }
708
709         if (g_jetpack)
710                 start_items |= ITEM_Jetpack.m_itemid;
711
712         MUTATOR_CALLHOOK(SetStartItems);
713
714         if (start_items & ITEM_Jetpack.m_itemid)
715         {
716                 start_items |= ITEM_JetpackRegen.m_itemid;
717                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
718                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
719         }
720
721         WepSet precache_weapons = start_weapons;
722         if (g_warmup_allguns != 1)
723                 precache_weapons |= warmup_start_weapons;
724         FOREACH(Weapons, it != WEP_Null, LAMBDA(
725                 if(precache_weapons & (it.m_wepset))
726                         it.wr_init(it);
727         ));
728
729         start_ammo_shells = max(0, start_ammo_shells);
730         start_ammo_nails = max(0, start_ammo_nails);
731         start_ammo_rockets = max(0, start_ammo_rockets);
732         start_ammo_cells = max(0, start_ammo_cells);
733         start_ammo_plasma = max(0, start_ammo_plasma);
734         start_ammo_fuel = max(0, start_ammo_fuel);
735
736         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
737         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
738         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
739         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
740         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
741         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
742 }
743
744 void precache_playermodel(string m)
745 {
746         float globhandle, i, n;
747         string f;
748
749         if(substring(m, -9,5) == "_lod1")
750                 return;
751         if(substring(m, -9,5) == "_lod2")
752                 return;
753         precache_model(m);
754         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
755         if(fexists(f))
756                 precache_model(f);
757         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
758         if(fexists(f))
759                 precache_model(f);
760
761         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
762         if (globhandle < 0)
763                 return;
764         n = search_getsize(globhandle);
765         for (i = 0; i < n; ++i)
766         {
767                 //print(search_getfilename(globhandle, i), "\n");
768                 f = search_getfilename(globhandle, i);
769                 PrecachePlayerSounds(f);
770         }
771         search_end(globhandle);
772 }
773 void precache_all_playermodels(string pattern)
774 {
775         int globhandle = search_begin(pattern, true, false);
776         if (globhandle < 0) return;
777         int n = search_getsize(globhandle);
778         for (int i = 0; i < n; ++i)
779         {
780                 string s = search_getfilename(globhandle, i);
781                 precache_playermodel(s);
782         }
783         search_end(globhandle);
784 }
785
786 void precache_playermodels(string s)
787 {
788         FOREACH_WORD(s, true, LAMBDA(precache_playermodel(it)));
789 }
790
791 void precache()
792 {
793     // gamemode related things
794
795     // Precache all player models if desired
796     if (autocvar_sv_precacheplayermodels)
797     {
798         PrecachePlayerSounds("sound/player/default.sounds");
799         precache_all_playermodels("models/player/*.zym");
800         precache_all_playermodels("models/player/*.dpm");
801         precache_all_playermodels("models/player/*.md3");
802         precache_all_playermodels("models/player/*.psk");
803         precache_all_playermodels("models/player/*.iqm");
804     }
805
806     if (autocvar_sv_defaultcharacter)
807     {
808                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
809                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
810                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
811                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
812                 precache_playermodels(autocvar_sv_defaultplayermodel);
813     }
814
815 #if 0
816     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
817
818     if (!this.noise && this.music) // quake 3 uses the music field
819         this.noise = this.music;
820
821     // plays music for the level if there is any
822     if (this.noise)
823     {
824         precache_sound (this.noise);
825         ambientsound ('0 0 0', this.noise, VOL_BASE, ATTEN_NONE);
826     }
827 #endif
828 }
829
830
831 void make_safe_for_remove(entity e)
832 {
833     if (e.initialize_entity)
834     {
835         entity ent, prev = NULL;
836         for (ent = initialize_entity_first; ent; )
837         {
838             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
839             {
840                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
841                 // skip it in linked list
842                 if (prev)
843                 {
844                     prev.initialize_entity_next = ent.initialize_entity_next;
845                     ent = prev.initialize_entity_next;
846                 }
847                 else
848                 {
849                     initialize_entity_first = ent.initialize_entity_next;
850                     ent = initialize_entity_first;
851                 }
852             }
853             else
854             {
855                 prev = ent;
856                 ent = ent.initialize_entity_next;
857             }
858         }
859     }
860 }
861
862 .float remove_except_protected_forbidden;
863 void remove_except_protected(entity e)
864 {
865         if(e.remove_except_protected_forbidden)
866                 error("not allowed to remove this at this point");
867         builtin_remove(e);
868 }
869
870 void remove_unsafely(entity e)
871 {
872     if(e.classname == "spike")
873         error("Removing spikes is forbidden (crylink bug), please report");
874     builtin_remove(e);
875 }
876
877 void remove_safely(entity e)
878 {
879     make_safe_for_remove(e);
880     builtin_remove(e);
881 }
882
883 void InitializeEntity(entity e, void(entity this) func, float order)
884 {
885     entity prev, cur;
886
887     if (!e || e.initialize_entity)
888     {
889         // make a proxy initializer entity
890         entity e_old = e;
891         e = new(initialize_entity);
892         e.enemy = e_old;
893     }
894
895     e.initialize_entity = func;
896     e.initialize_entity_order = order;
897
898     cur = initialize_entity_first;
899     prev = NULL;
900     for (;;)
901     {
902         if (!cur || cur.initialize_entity_order > order)
903         {
904             // insert between prev and cur
905             if (prev)
906                 prev.initialize_entity_next = e;
907             else
908                 initialize_entity_first = e;
909             e.initialize_entity_next = cur;
910             return;
911         }
912         prev = cur;
913         cur = cur.initialize_entity_next;
914     }
915 }
916 void InitializeEntitiesRun()
917 {
918     entity startoflist = initialize_entity_first;
919     initialize_entity_first = NULL;
920     delete_fn = remove_except_protected;
921     for (entity e = startoflist; e; e = e.initialize_entity_next)
922     {
923                 e.remove_except_protected_forbidden = 1;
924     }
925     for (entity e = startoflist; e; )
926     {
927                 e.remove_except_protected_forbidden = 0;
928         e.initialize_entity_order = 0;
929         entity next = e.initialize_entity_next;
930         e.initialize_entity_next = NULL;
931         var void(entity this) func = e.initialize_entity;
932         e.initialize_entity = func_null;
933         if (e.classname == "initialize_entity")
934         {
935             entity wrappee = e.enemy;
936             builtin_remove(e);
937             e = wrappee;
938         }
939         //dprint("Delayed initialization: ", e.classname, "\n");
940         if (func)
941         {
942                 func(e);
943         }
944         else
945         {
946             eprint(e);
947             backtrace(strcat("Null function in: ", e.classname, "\n"));
948         }
949         e = next;
950     }
951     delete_fn = remove_unsafely;
952 }
953
954 .float(entity) isEliminated;
955 bool EliminatedPlayers_SendEntity(entity this, entity to, float sendflags)
956 {
957         float i, f, b;
958         entity e;
959         WriteHeader(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
960         WriteByte(MSG_ENTITY, sendflags);
961
962         if(sendflags & 1)
963         {
964                 for(i = 1; i <= maxclients; i += 8)
965                 {
966                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
967                         {
968                                 if(eliminatedPlayers.isEliminated(e))
969                                         f |= b;
970                         }
971                         WriteByte(MSG_ENTITY, f);
972                 }
973         }
974
975         return true;
976 }
977
978 void EliminatedPlayers_Init(float(entity) isEliminated_func)
979 {
980         if(eliminatedPlayers)
981         {
982                 backtrace("Can't spawn eliminatedPlayers again!");
983                 return;
984         }
985         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
986         eliminatedPlayers.isEliminated = isEliminated_func;
987 }
988
989
990
991
992 void adaptor_think2use_hittype_splash(entity this) // for timed projectile detonation
993 {
994         if(!(IS_ONGROUND(this))) // if onground, we ARE touching something, but HITTYPE_SPLASH is to be networked if the damage causing projectile is not touching ANYTHING
995                 this.projectiledeathtype |= HITTYPE_SPLASH;
996         adaptor_think2use(this);
997 }
998
999 // deferred dropping
1000 void DropToFloor_Handler(entity this)
1001 {
1002     WITHSELF(this, builtin_droptofloor());
1003     this.dropped_origin = this.origin;
1004 }
1005
1006 void droptofloor(entity this)
1007 {
1008     InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1009 }
1010
1011
1012
1013 float trace_hits_box_a0, trace_hits_box_a1;
1014
1015 float trace_hits_box_1d(float end, float thmi, float thma)
1016 {
1017     if (end == 0)
1018     {
1019         // just check if x is in range
1020         if (0 < thmi)
1021             return false;
1022         if (0 > thma)
1023             return false;
1024     }
1025     else
1026     {
1027         // do the trace with respect to x
1028         // 0 -> end has to stay in thmi -> thma
1029         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1030         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1031         if (trace_hits_box_a0 > trace_hits_box_a1)
1032             return false;
1033     }
1034     return true;
1035 }
1036
1037 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1038 {
1039     end -= start;
1040     thmi -= start;
1041     thma -= start;
1042     // now it is a trace from 0 to end
1043
1044     trace_hits_box_a0 = 0;
1045     trace_hits_box_a1 = 1;
1046
1047     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1048         return false;
1049     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1050         return false;
1051     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1052         return false;
1053
1054     return true;
1055 }
1056
1057 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1058 {
1059     return trace_hits_box(start, end, thmi - ma, thma - mi);
1060 }
1061
1062 bool SUB_NoImpactCheck(entity this, entity toucher)
1063 {
1064         // zero hitcontents = this is not the real impact, but either the
1065         // mirror-impact of something hitting the projectile instead of the
1066         // projectile hitting the something, or a touchareagrid one. Neither of
1067         // these stop the projectile from moving, so...
1068         if(trace_dphitcontents == 0)
1069         {
1070                 LOG_TRACEF("A hit from a projectile happened with no hit contents! DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct. (edict: %i, classname: %s, origin: %v)", this, this.classname, this.origin);
1071                 checkclient(this);
1072         }
1073     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1074         return true;
1075     if (toucher == NULL && this.size != '0 0 0')
1076     {
1077         vector tic;
1078         tic = this.velocity * sys_frametime;
1079         tic = tic + normalize(tic) * vlen(this.maxs - this.mins);
1080         traceline(this.origin - tic, this.origin + tic, MOVE_NORMAL, this);
1081         if (trace_fraction >= 1)
1082         {
1083             LOG_TRACE("Odd... did not hit...?");
1084         }
1085         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1086         {
1087             LOG_TRACE("Detected and prevented the sky-grapple bug.");
1088             return true;
1089         }
1090     }
1091
1092     return false;
1093 }
1094
1095 #define SUB_OwnerCheck(ent,oth) ((oth) && ((oth) == (ent).owner))
1096
1097 void W_Crylink_Dequeue(entity e);
1098 bool WarpZone_Projectile_Touch_ImpactFilter_Callback(entity this, entity toucher)
1099 {
1100         if(SUB_OwnerCheck(this, toucher))
1101                 return true;
1102         if(SUB_NoImpactCheck(this, toucher))
1103         {
1104                 if(this.classname == "nade")
1105                         return false; // no checks here
1106                 else if(this.classname == "grapplinghook")
1107                         RemoveHook(this);
1108                 else if(this.classname == "spike")
1109                 {
1110                         W_Crylink_Dequeue(this);
1111                         delete(this);
1112                 }
1113                 else
1114                         delete(this);
1115                 return true;
1116         }
1117         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1118                 UpdateCSQCProjectile(this);
1119         return false;
1120 }
1121
1122 /** engine callback */
1123 void URI_Get_Callback(float id, float status, string data)
1124 {
1125         if(url_URI_Get_Callback(id, status, data))
1126         {
1127                 // handled
1128         }
1129         else if (id == URI_GET_DISCARD)
1130         {
1131                 // discard
1132         }
1133         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1134         {
1135                 // sv_cmd curl
1136                 Curl_URI_Get_Callback(id, status, data);
1137         }
1138         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1139         {
1140                 // online ban list
1141                 OnlineBanList_URI_Get_Callback(id, status, data);
1142         }
1143         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
1144         {
1145                 // handled by a mutator
1146         }
1147         else
1148         {
1149                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1150         }
1151 }
1152
1153 string uid2name(string myuid) {
1154         string s;
1155         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1156
1157         // FIXME remove this later after 0.6 release
1158         // convert old style broken records to correct style
1159         if(s == "")
1160         {
1161                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1162                 if(s != "")
1163                 {
1164                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1165                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
1166                 }
1167         }
1168
1169         if(s == "")
1170                 s = "^1Unregistered Player";
1171         return s;
1172 }
1173
1174 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1175 {
1176     float m, i;
1177     vector start, org, delta, end, enddown, mstart;
1178
1179     m = e.dphitcontentsmask;
1180     e.dphitcontentsmask = goodcontents | badcontents;
1181
1182     org = boundmin;
1183     delta = boundmax - boundmin;
1184
1185     start = end = org;
1186
1187     for (i = 0; i < attempts; ++i)
1188     {
1189         start.x = org.x + random() * delta.x;
1190         start.y = org.y + random() * delta.y;
1191         start.z = org.z + random() * delta.z;
1192
1193         // rule 1: start inside world bounds, and outside
1194         // solid, and don't start from somewhere where you can
1195         // fall down to evil
1196         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1197         if (trace_fraction >= 1)
1198             continue;
1199         if (trace_startsolid)
1200             continue;
1201         if (trace_dphitcontents & badcontents)
1202             continue;
1203         if (trace_dphitq3surfaceflags & badsurfaceflags)
1204             continue;
1205
1206         // rule 2: if we are too high, lower the point
1207         if (trace_fraction * delta.z > maxaboveground)
1208             start = trace_endpos + '0 0 1' * maxaboveground;
1209         enddown = trace_endpos;
1210
1211         // rule 3: make sure we aren't outside the map. This only works
1212         // for somewhat well formed maps. A good rule of thumb is that
1213         // the map should have a convex outside hull.
1214         // these can be traceLINES as we already verified the starting box
1215         mstart = start + 0.5 * (e.mins + e.maxs);
1216         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1217         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1218             continue;
1219         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1220         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1221             continue;
1222         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1223         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1224             continue;
1225         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1226         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1227             continue;
1228         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1229         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1230             continue;
1231
1232         // rule 4: we must "see" some spawnpoint or item
1233     entity sp = NULL;
1234     IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1235     {
1236         if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1237         {
1238                 sp = it;
1239                 break;
1240         }
1241     });
1242         if(!sp)
1243         {
1244                 IL_EACH(g_items, checkpvs(mstart, it),
1245                 {
1246                         if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1247                         {
1248                                 sp = it;
1249                                 break;
1250                         }
1251                 });
1252
1253                 if(!sp)
1254                         continue;
1255         }
1256
1257         // find a random vector to "look at"
1258         end.x = org.x + random() * delta.x;
1259         end.y = org.y + random() * delta.y;
1260         end.z = org.z + random() * delta.z;
1261         end = start + normalize(end - start) * vlen(delta);
1262
1263         // rule 4: start TO end must not be too short
1264         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1265         if (trace_startsolid)
1266             continue;
1267         if (trace_fraction < minviewdistance / vlen(delta))
1268             continue;
1269
1270         // rule 5: don't want to look at sky
1271         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1272             continue;
1273
1274         // rule 6: we must not end up in trigger_hurt
1275         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1276             continue;
1277
1278         break;
1279     }
1280
1281     e.dphitcontentsmask = m;
1282
1283     if (i < attempts)
1284     {
1285         setorigin(e, start);
1286         e.angles = vectoangles(end - start);
1287         LOG_TRACE("Needed ", ftos(i + 1), " attempts");
1288         return true;
1289     }
1290     else
1291         return false;
1292 }
1293
1294 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1295 {
1296         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1297 }
1298
1299 void write_recordmarker(entity pl, float tstart, float dt)
1300 {
1301     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1302
1303     // also write a marker into demo files for demotc-race-record-extractor to find
1304     stuffcmd(pl,
1305              strcat(
1306                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1307                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1308 }
1309
1310 void attach_sameorigin(entity e, entity to, string tag)
1311 {
1312     vector org, t_forward, t_left, t_up, e_forward, e_up;
1313     float tagscale;
1314
1315     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1316     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1317     t_forward = v_forward * tagscale;
1318     t_left = v_right * -tagscale;
1319     t_up = v_up * tagscale;
1320
1321     e.origin_x = org * t_forward;
1322     e.origin_y = org * t_left;
1323     e.origin_z = org * t_up;
1324
1325     // current forward and up directions
1326     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1327                 e.angles = AnglesTransform_FromVAngles(e.angles);
1328         else
1329                 e.angles = AnglesTransform_FromAngles(e.angles);
1330     fixedmakevectors(e.angles);
1331
1332     // untransform forward, up!
1333     e_forward.x = v_forward * t_forward;
1334     e_forward.y = v_forward * t_left;
1335     e_forward.z = v_forward * t_up;
1336     e_up.x = v_up * t_forward;
1337     e_up.y = v_up * t_left;
1338     e_up.z = v_up * t_up;
1339
1340     e.angles = fixedvectoangles2(e_forward, e_up);
1341     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1342                 e.angles = AnglesTransform_ToVAngles(e.angles);
1343         else
1344                 e.angles = AnglesTransform_ToAngles(e.angles);
1345
1346     setattachment(e, to, tag);
1347     setorigin(e, e.origin);
1348 }
1349
1350 void detach_sameorigin(entity e)
1351 {
1352     vector org;
1353     org = gettaginfo(e, 0);
1354     e.angles = fixedvectoangles2(v_forward, v_up);
1355     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1356                 e.angles = AnglesTransform_ToVAngles(e.angles);
1357         else
1358                 e.angles = AnglesTransform_ToAngles(e.angles);
1359     setorigin(e, org);
1360     setattachment(e, NULL, "");
1361     setorigin(e, e.origin);
1362 }
1363
1364 void follow_sameorigin(entity e, entity to)
1365 {
1366     set_movetype(e, MOVETYPE_FOLLOW); // make the hole follow
1367     e.aiment = to; // make the hole follow bmodel
1368     e.punchangle = to.angles; // the original angles of bmodel
1369     e.view_ofs = e.origin - to.origin; // relative origin
1370     e.v_angle = e.angles - to.angles; // relative angles
1371 }
1372
1373 void unfollow_sameorigin(entity e)
1374 {
1375     set_movetype(e, MOVETYPE_NONE);
1376 }
1377
1378 entity gettaginfo_relative_ent;
1379 vector gettaginfo_relative(entity e, float tag)
1380 {
1381     if (!gettaginfo_relative_ent)
1382     {
1383         gettaginfo_relative_ent = spawn();
1384         gettaginfo_relative_ent.effects = EF_NODRAW;
1385     }
1386     gettaginfo_relative_ent.model = e.model;
1387     gettaginfo_relative_ent.modelindex = e.modelindex;
1388     gettaginfo_relative_ent.frame = e.frame;
1389     return gettaginfo(gettaginfo_relative_ent, tag);
1390 }
1391
1392 .string aiment_classname;
1393 .float aiment_deadflag;
1394 void SetMovetypeFollow(entity ent, entity e)
1395 {
1396         // FIXME this may not be warpzone aware
1397         set_movetype(ent, MOVETYPE_FOLLOW); // make the hole follow
1398         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.
1399         ent.aiment = e; // make the hole follow bmodel
1400         ent.punchangle = e.angles; // the original angles of bmodel
1401         ent.view_ofs = ent.origin - e.origin; // relative origin
1402         ent.v_angle = ent.angles - e.angles; // relative angles
1403         ent.aiment_classname = strzone(e.classname);
1404         ent.aiment_deadflag = e.deadflag;
1405 }
1406 void UnsetMovetypeFollow(entity ent)
1407 {
1408         set_movetype(ent, MOVETYPE_FLY);
1409         PROJECTILE_MAKETRIGGER(ent);
1410         ent.aiment = NULL;
1411 }
1412 float LostMovetypeFollow(entity ent)
1413 {
1414 /*
1415         if(ent.move_movetype != MOVETYPE_FOLLOW)
1416                 if(ent.aiment)
1417                         error("???");
1418 */
1419         if(ent.aiment)
1420         {
1421                 if(ent.aiment.classname != ent.aiment_classname)
1422                         return 1;
1423                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1424                         return 1;
1425         }
1426         return 0;
1427 }
1428
1429 .bool pushable;
1430 bool isPushable(entity e)
1431 {
1432         if(e.pushable)
1433                 return true;
1434         if(IS_VEHICLE(e))
1435                 return false;
1436         if(e.iscreature)
1437                 return true;
1438         switch(e.classname)
1439         {
1440                 case "body":
1441                 case "droppedweapon":
1442                         return true;
1443                 case "bullet": // antilagged bullets can't hit this either
1444                         return false;
1445         }
1446         if (e.projectiledeathtype)
1447                 return true;
1448         return false;
1449 }