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