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