4962ddbe6ed6b414623ee595f632cffc742c4b6a
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / turrets / sv_turrets.qc
1 #include "sv_turrets.qh"
2 #ifdef SVQC
3 #include <server/autocvars.qh>
4
5 // Generic aiming
6 vector turret_aim_generic(entity this)
7 {
8
9         vector pre_pos, prep;
10         float distance, impact_time = 0, i, mintime;
11
12         turret_tag_fire_update(this);
13
14         if(this.aim_flags & TFL_AIM_SIMPLE)
15                 return real_origin(this.enemy);
16
17         mintime = max(this.attack_finished_single[0] - time,0) + sys_frametime;
18
19         // Baseline
20         pre_pos = real_origin(this.enemy);
21
22         // Lead?
23         if (this.aim_flags & TFL_AIM_LEAD)
24         {
25                 if (this.aim_flags & TFL_AIM_SHOTTIMECOMPENSATE)           // Need to conpensate for shot traveltime
26                 {
27                         prep = pre_pos;
28
29                         distance = vlen(prep - this.tur_shotorg);
30                         impact_time = distance / this.shot_speed;
31
32                         prep = pre_pos + (this.enemy.velocity * (impact_time + mintime));
33
34                         if(this.aim_flags & TFL_AIM_ZPREDICT)
35                         if(!IS_ONGROUND(this.enemy))
36                         if(this.enemy.move_movetype == MOVETYPE_WALK || this.enemy.move_movetype == MOVETYPE_TOSS || this.enemy.move_movetype == MOVETYPE_BOUNCE)
37                         {
38                                 float vz;
39                                 prep_z = pre_pos_z;
40                                 vz = this.enemy.velocity_z;
41                                 for(i = 0; i < impact_time; i += sys_frametime)
42                                 {
43                                         vz = vz - (autocvar_sv_gravity * sys_frametime);
44                                         prep_z = prep_z + vz * sys_frametime;
45                                 }
46                         }
47                         pre_pos = prep;
48                 }
49                 else
50                         pre_pos = pre_pos + this.enemy.velocity * mintime;
51         }
52
53         if(this.aim_flags & TFL_AIM_SPLASH)
54         {
55                 //tracebox(pre_pos + '0 0 32',this.enemy.mins,this.enemy.maxs,pre_pos -'0 0 64',MOVE_WORLDONLY,this.enemy);
56                 traceline(pre_pos + '0 0 32',pre_pos -'0 0 64',MOVE_WORLDONLY,this.enemy);
57                 if(trace_fraction != 1.0)
58                         pre_pos = trace_endpos;
59         }
60
61         return pre_pos;
62 }
63
64 float turret_targetscore_support(entity _turret,entity _target)
65 {
66         float score;            // Total score
67         float s_score = 0, d_score;
68
69         if (_turret.enemy == _target) s_score = 1;
70
71         d_score = min(_turret.target_range_optimal,tvt_dist) / max(_turret.target_range_optimal,tvt_dist);
72
73         score = (d_score * _turret.target_select_rangebias) +
74                         (s_score * _turret.target_select_samebias);
75
76         return score;
77 }
78
79 /*
80 * Generic bias aware score system.
81 */
82 float turret_targetscore_generic(entity _turret, entity _target)
83 {
84         float d_dist;      // Defendmode Distance
85         float score;            // Total score
86         float d_score;    // Distance score
87         float a_score;    // Angular score
88         float m_score = 0;  // missile score
89         float p_score = 0;  // player score
90         float ikr;                // ideal kill range
91
92         if (_turret.tur_defend)
93         {
94                 d_dist = vlen(real_origin(_target) - _turret.tur_defend.origin);
95                 ikr = vlen(_turret.origin - _turret.tur_defend.origin);
96                 d_score = 1 - d_dist / _turret.target_range;
97         }
98         else
99         {
100                 // Make a normlized value base on the targets distance from our optimal killzone
101                 ikr = _turret.target_range_optimal;
102                 d_score = min(ikr, tvt_dist) / max(ikr, tvt_dist);
103         }
104
105         a_score = 1 - tvt_thadf / _turret.aim_maxrotate;
106
107         if ((_turret.target_select_missilebias > 0) && (_target.flags & FL_PROJECTILE))
108                 m_score = 1;
109
110         if ((_turret.target_select_playerbias > 0) && IS_CLIENT(_target))
111                 p_score = 1;
112
113         d_score = max(d_score, 0);
114         a_score = max(a_score, 0);
115         m_score = max(m_score, 0);
116         p_score = max(p_score, 0);
117
118         score = (d_score * _turret.target_select_rangebias) +
119                         (a_score * _turret.target_select_anglebias) +
120                         (m_score * _turret.target_select_missilebias) +
121                         (p_score * _turret.target_select_playerbias);
122
123         if(vdist((_turret.tur_shotorg - real_origin(_target)), >, _turret.target_range))
124         {
125                 //dprint("Wtf?\n");
126                 score *= 0.001;
127         }
128
129 #ifdef TURRET_DEBUG
130         string sd,sa,sm,sp,ss;
131         string sdt,sat,smt,spt;
132
133         sd = ftos(d_score);
134         d_score *= _turret.target_select_rangebias;
135         sdt = ftos(d_score);
136
137         //sv = ftos(v_score);
138         //v_score *= _turret.target_select_samebias;
139         //svt = ftos(v_score);
140
141         sa = ftos(a_score);
142         a_score *= _turret.target_select_anglebias;
143         sat = ftos(a_score);
144
145         sm = ftos(m_score);
146         m_score *= _turret.target_select_missilebias;
147         smt = ftos(m_score);
148
149         sp = ftos(p_score);
150         p_score *= _turret.target_select_playerbias;
151         spt = ftos(p_score);
152
153
154         ss = ftos(score);
155         bprint("^3Target scores^7 \[  ",_turret.netname, "  \] ^3for^7 \[  ", _target.netname,"  \]\n");
156         bprint("^5Range:\[  ",sd,  "  \]^2+bias:\[  ",sdt,"  \]\n");
157         bprint("^5Angle:\[  ",sa,  "  \]^2+bias:\[  ",sat,"  \]\n");
158         bprint("^5Missile:\[  ",sm,"  \]^2+bias:\[  ",smt,"  \]\n");
159         bprint("^5Player:\[  ",sp, "  \]^2+bias:\[  ",spt,"  \]\n");
160         bprint("^3Total (w/bias):\[^1",ss,"\]\n");
161
162 #endif
163
164         return score;
165 }
166
167 // Generic damage handling
168 void turret_hide(entity this)
169 {
170         this.effects   |= EF_NODRAW;
171         this.nextthink = time + this.respawntime - 0.2;
172         setthink(this, turret_respawn);
173 }
174
175 void turret_die(entity this)
176 {
177         this.deadflag             = DEAD_DEAD;
178         this.tur_head.deadflag = this.deadflag;
179
180 // Unsolidify and hide real parts
181         this.solid                       = SOLID_NOT;
182         this.tur_head.solid      = this.solid;
183
184         this.event_damage                 = func_null;
185         this.event_heal = func_null;
186         this.takedamage                  = DAMAGE_NO;
187
188         SetResourceAmountExplicit(this, RESOURCE_HEALTH, 0);
189
190 // Go boom
191         //RadiusDamage (this,this, min(this.ammo,50),min(this.ammo,50) * 0.25,250,NULL,min(this.ammo,50)*5,DEATH_TURRET,NULL);
192
193         Turret tur = get_turretinfo(this.m_id);
194         if(this.damage_flags & TFL_DMG_DEATH_NORESPAWN)
195         {
196                 // do a simple explosion effect here, since CSQC can't do it on a to-be-removed entity
197                 sound(this, CH_SHOTS, SND_ROCKET_IMPACT, VOL_BASE, ATTEN_NORM);
198                 Send_Effect(EFFECT_ROCKET_EXPLODE, this.origin, '0 0 0', 1);
199
200                 tur.tr_death(tur, this);
201
202                 delete(this.tur_head);
203                 delete(this);
204         }
205         else
206         {
207                 // Setup respawn
208                 this.SendFlags    |= TNSF_STATUS;
209                 this.nextthink   = time + 0.2;
210                 setthink(this, turret_hide);
211
212                 tur.tr_death(tur, this);
213         }
214 }
215
216 void turret_damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector vforce)
217 {
218         // Enough already!
219         if(this.deadflag == DEAD_DEAD)
220                 return;
221
222         // Inactive turrets take no damage. (hm..)
223         if(!this.active)
224                 return;
225
226         if(SAME_TEAM(this, attacker))
227         {
228                 if(autocvar_g_friendlyfire)
229                         damage = damage * autocvar_g_friendlyfire;
230                 else
231                         return;
232         }
233
234         TakeResource(this, RESOURCE_HEALTH, damage);
235
236         // thorw head slightly off aim when hit?
237         if (this.damage_flags & TFL_DMG_HEADSHAKE)
238         {
239                 this.tur_head.angles_x = this.tur_head.angles_x + (-0.5 + random()) * damage;
240                 this.tur_head.angles_y = this.tur_head.angles_y + (-0.5 + random()) * damage;
241
242                 this.SendFlags  |= TNSF_ANG;
243         }
244
245         if (this.turret_flags & TUR_FLAG_MOVE)
246                 this.velocity = this.velocity + vforce;
247
248         if (GetResourceAmount(this, RESOURCE_HEALTH) <= 0)
249         {
250                 this.event_damage                 = func_null;
251                 this.tur_head.event_damage = func_null;
252                 this.event_heal = func_null;
253                 this.tur_head.event_heal = func_null;
254                 this.takedamage                  = DAMAGE_NO;
255                 this.nextthink = time;
256                 setthink(this, turret_die);
257         }
258
259         this.SendFlags  |= TNSF_STATUS;
260 }
261
262 bool turret_heal(entity targ, entity inflictor, float amount, float limit)
263 {
264         float true_limit = ((limit != RESOURCE_LIMIT_NONE) ? limit : targ.max_health);
265         if(GetResourceAmount(targ, RESOURCE_HEALTH) <= 0 || GetResourceAmount(targ, RESOURCE_HEALTH) >= true_limit)
266                 return false;
267
268         GiveResourceWithLimit(targ, RESOURCE_HEALTH, amount, true_limit);
269         targ.SendFlags |= TNSF_STATUS;
270         return true;
271 }
272
273 void turret_think(entity this);
274 void turret_respawn(entity this)
275 {
276         // Make sure all parts belong to the same team since
277         // this function doubles as "teamchange" function.
278         this.tur_head.team      = this.team;
279         this.effects                       &= ~EF_NODRAW;
280         this.deadflag                           = DEAD_NO;
281         this.effects                            = EF_LOWPRECISION;
282         this.solid                                      = SOLID_BBOX;
283         this.takedamage                         = DAMAGE_AIM;
284         this.event_damage                       = turret_damage;
285         this.event_heal                         = turret_heal;
286         this.avelocity                          = '0 0 0';
287         this.tur_head.avelocity         = this.avelocity;
288         this.tur_head.angles            = this.idle_aim;
289         SetResourceAmountExplicit(this, RESOURCE_HEALTH, this.max_health);
290         this.enemy                                      = NULL;
291         this.volly_counter                      = this.shot_volly;
292         this.ammo                                       = this.ammo_max;
293
294         this.nextthink = time + this.ticrate;
295         setthink(this, turret_think);
296
297         this.SendFlags = TNSF_FULL_UPDATE;
298
299         Turret tur = get_turretinfo(this.m_id);
300         tur.tr_setup(tur, this);
301 }
302
303
304 // Main functions
305 #define cvar_base "g_turrets_unit_"
306 .float clientframe;
307 void turrets_setframe(entity this, float _frame, float client_only)
308 {
309         if((client_only ? this.clientframe : this.frame ) != _frame)
310         {
311                 this.SendFlags |= TNSF_ANIM;
312                 this.anim_start_time = time;
313         }
314
315          if(client_only)
316                 this.clientframe = _frame;
317         else
318                 this.frame = _frame;
319
320 }
321
322 bool turret_send(entity this, entity to, float sf)
323 {
324
325         WriteHeader(MSG_ENTITY, ENT_CLIENT_TURRET);
326         WriteByte(MSG_ENTITY, sf);
327         if(sf & TNSF_SETUP)
328         {
329                 WriteByte(MSG_ENTITY, this.m_id);
330
331                 WriteVector(MSG_ENTITY, this.origin);
332
333                 WriteAngle(MSG_ENTITY, this.angles_x);
334                 WriteAngle(MSG_ENTITY, this.angles_y);
335         }
336
337         if(sf & TNSF_ANG)
338         {
339                 WriteShort(MSG_ENTITY, rint(this.tur_head.angles_x));
340                 WriteShort(MSG_ENTITY, rint(this.tur_head.angles_y));
341         }
342
343         if(sf & TNSF_AVEL)
344         {
345                 WriteShort(MSG_ENTITY, rint(this.tur_head.avelocity_x));
346                 WriteShort(MSG_ENTITY, rint(this.tur_head.avelocity_y));
347         }
348
349         if(sf & TNSF_MOVE)
350         {
351                 WriteVector(MSG_ENTITY, this.origin);
352
353                 WriteVector(MSG_ENTITY, this.velocity);
354
355                 WriteShort(MSG_ENTITY, rint(this.angles_y));
356         }
357
358         if(sf & TNSF_ANIM)
359         {
360                 WriteCoord(MSG_ENTITY, this.anim_start_time);
361                 WriteByte(MSG_ENTITY, this.frame);
362         }
363
364         if(sf & TNSF_STATUS)
365         {
366                 WriteByte(MSG_ENTITY, this.team);
367
368                 if(GetResourceAmount(this, RESOURCE_HEALTH) <= 0)
369                         WriteByte(MSG_ENTITY, 0);
370                 else
371                         WriteByte(MSG_ENTITY, ceil((GetResourceAmount(this, RESOURCE_HEALTH) / this.max_health) * 255));
372         }
373
374         return true;
375 }
376
377 void load_unit_settings(entity ent, bool is_reload)
378 {
379         string unitname = ent.netname;
380         string sbase;
381
382         if (ent == NULL)
383                 return;
384
385         if(!ent.turret_scale_damage)    ent.turret_scale_damage = 1;
386         if(!ent.turret_scale_range)             ent.turret_scale_range  = 1;
387         if(!ent.turret_scale_refire)    ent.turret_scale_refire = 1;
388         if(!ent.turret_scale_ammo)              ent.turret_scale_ammo   = 1;
389         if(!ent.turret_scale_aim)               ent.turret_scale_aim     = 1;
390         if(!ent.turret_scale_health)    ent.turret_scale_health = 1;
391         if(!ent.turret_scale_respawn)   ent.turret_scale_respawn = 1;
392
393         sbase = strcat(cvar_base,unitname);
394         if (is_reload)
395         {
396                 ent.enemy = NULL;
397                 ent.tur_head.avelocity = '0 0 0';
398
399                 ent.tur_head.angles = '0 0 0';
400         }
401
402         SetResourceAmountExplicit(ent, RESOURCE_HEALTH, cvar(strcat(sbase,"_health")) * ent.turret_scale_health);
403         ent.respawntime = cvar(strcat(sbase,"_respawntime")) * ent.turret_scale_respawn;
404
405         ent.shot_dmg             = cvar(strcat(sbase,"_shot_dmg")) * ent.turret_scale_damage;
406         ent.shot_refire   = cvar(strcat(sbase,"_shot_refire")) * ent.turret_scale_refire;
407         ent.shot_radius   = cvar(strcat(sbase,"_shot_radius")) * ent.turret_scale_damage;
408         ent.shot_speed          = cvar(strcat(sbase,"_shot_speed"));
409         ent.shot_spread   = cvar(strcat(sbase,"_shot_spread"));
410         ent.shot_force          = cvar(strcat(sbase,"_shot_force")) * ent.turret_scale_damage;
411         ent.shot_volly          = cvar(strcat(sbase,"_shot_volly"));
412         ent.shot_volly_refire = cvar(strcat(sbase,"_shot_volly_refire")) * ent.turret_scale_refire;
413
414         ent.target_range                 = cvar(strcat(sbase,"_target_range")) * ent.turret_scale_range;
415         ent.target_range_min     = cvar(strcat(sbase,"_target_range_min")) * ent.turret_scale_range;
416         ent.target_range_optimal = cvar(strcat(sbase,"_target_range_optimal")) * ent.turret_scale_range;
417         //ent.target_range_fire = cvar(strcat(sbase,"_target_range_fire")) * ent.turret_scale_range;
418
419         ent.target_select_rangebias = cvar(strcat(sbase,"_target_select_rangebias"));
420         ent.target_select_samebias  = cvar(strcat(sbase,"_target_select_samebias"));
421         ent.target_select_anglebias = cvar(strcat(sbase,"_target_select_anglebias"));
422         ent.target_select_playerbias = cvar(strcat(sbase,"_target_select_playerbias"));
423         //ent.target_select_fov = cvar(cvar_gets(sbase,"_target_select_fov"));
424
425         ent.ammo_max     = cvar(strcat(sbase,"_ammo_max")) * ent.turret_scale_ammo;
426         ent.ammo_recharge = cvar(strcat(sbase,"_ammo_recharge")) * ent.turret_scale_ammo;
427
428         ent.aim_firetolerance_dist = cvar(strcat(sbase,"_aim_firetolerance_dist"));
429         ent.aim_speed   = cvar(strcat(sbase,"_aim_speed")) * ent.turret_scale_aim;
430         ent.aim_maxrotate  = cvar(strcat(sbase,"_aim_maxrot"));
431         ent.aim_maxpitch = cvar(strcat(sbase,"_aim_maxpitch"));
432
433         ent.track_type          = cvar(strcat(sbase,"_track_type"));
434         ent.track_accel_pitch = cvar(strcat(sbase,"_track_accel_pitch"));
435         ent.track_accel_rotate  = cvar(strcat(sbase,"_track_accel_rot"));
436         ent.track_blendrate  = cvar(strcat(sbase,"_track_blendrate"));
437
438         if(is_reload) {
439                 Turret tur = get_turretinfo(ent.m_id);
440                 tur.tr_setup(tur, ent);
441         }
442 }
443
444 void turret_projectile_explode(entity this)
445 {
446
447         this.takedamage = DAMAGE_NO;
448         this.event_damage = func_null;
449 #ifdef TURRET_DEBUG
450         float d;
451         d = RadiusDamage (this, this.owner, this.owner.shot_dmg, 0, this.owner.shot_radius, this, NULL, this.owner.shot_force, this.totalfrags, DMG_NOWEP, NULL);
452         this.owner.tur_debug_dmg_t_h = this.owner.tur_debug_dmg_t_h + d;
453         this.owner.tur_debug_dmg_t_f = this.owner.tur_debug_dmg_t_f + this.owner.shot_dmg;
454 #else
455         RadiusDamage (this, this.realowner, this.owner.shot_dmg, 0, this.owner.shot_radius, this, NULL, this.owner.shot_force, this.totalfrags, DMG_NOWEP, NULL);
456 #endif
457         delete(this);
458 }
459
460 void turret_projectile_touch(entity this, entity toucher)
461 {
462         PROJECTILE_TOUCH(this, toucher);
463         turret_projectile_explode(this);
464 }
465
466 void turret_projectile_damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector vforce)
467 {
468         this.velocity  += vforce;
469         TakeResource(this, RESOURCE_HEALTH, damage);
470         //this.realowner = attacker; // Dont change realowner, it does not make much sense for turrets
471         if(GetResourceAmount(this, RESOURCE_HEALTH) <= 0)
472                 W_PrepareExplosionByDamage(this, this.owner, turret_projectile_explode);
473 }
474
475 entity turret_projectile(entity actor, Sound _snd, float _size, float _health, float _death, float _proj_type, float _cull, float _cli_anim)
476 {
477         TC(Sound, _snd);
478         entity proj;
479
480         sound (actor, CH_WEAPON_A, _snd, VOL_BASE, ATTEN_NORM);
481         proj                             = spawn ();
482         setorigin(proj, actor.tur_shotorg);
483         setsize(proj, '-0.5 -0.5 -0.5' * _size, '0.5 0.5 0.5' * _size);
484         proj.owner                = actor;
485         proj.realowner    = actor;
486         proj.bot_dodge    = true;
487         proj.bot_dodgerating = actor.shot_dmg;
488         setthink(proj, turret_projectile_explode);
489         settouch(proj, turret_projectile_touch);
490         proj.nextthink    = time + 9;
491         set_movetype(proj, MOVETYPE_FLYMISSILE);
492         proj.velocity           = normalize(actor.tur_shotdir_updated + randomvec() * actor.shot_spread) * actor.shot_speed;
493         proj.flags = FL_PROJECTILE;
494         IL_PUSH(g_projectiles, proj);
495         IL_PUSH(g_bot_dodge, proj);
496         proj.enemy                = actor.enemy;
497         proj.totalfrags  = _death;
498         PROJECTILE_MAKETRIGGER(proj);
499         if(_health)
500         {
501                 SetResourceAmountExplicit(proj, RESOURCE_HEALTH, _health);
502                 proj.takedamage  = DAMAGE_YES;
503                 proj.event_damage  = turret_projectile_damage;
504         }
505         else
506                 proj.flags |= FL_NOTARGET;
507
508         CSQCProjectile(proj, _cli_anim, _proj_type, _cull);
509
510         return proj;
511 }
512
513 /**
514 ** updates enemy distances, predicted impact point/time
515 ** and updated aim<->predict impact distance.
516 **/
517 void turret_do_updates(entity t_turret)
518 {
519         vector enemy_pos = real_origin(t_turret.enemy);
520
521         turret_tag_fire_update(t_turret);
522
523         t_turret.tur_shotdir_updated = v_forward;
524         t_turret.tur_dist_enemy = vlen(t_turret.tur_shotorg - enemy_pos);
525         t_turret.tur_dist_aimpos = vlen(t_turret.tur_shotorg - t_turret.tur_aimpos);
526
527         /*if((t_turret.firecheck_flags & TFL_FIRECHECK_VERIFIED) && (t_turret.enemy))
528         {
529                 oldpos = t_turret.enemy.origin;
530                 setorigin(t_turret.enemy, t_turret.tur_aimpos);
531                 tracebox(t_turret.tur_shotorg, '-1 -1 -1', '1 1 1', t_turret.tur_shotorg + (t_turret.tur_shotdir_updated * t_turret.tur_dist_aimpos), MOVE_NORMAL,t_turret);
532                 setorigin(t_turret.enemy, oldpos);
533
534                 if(trace_ent == t_turret.enemy)
535                         t_turret.tur_dist_impact_to_aimpos = 0;
536                 else
537                         t_turret.tur_dist_impact_to_aimpos = vlen(trace_endpos - t_turret.tur_aimpos);
538         }
539         else*/
540                 tracebox(t_turret.tur_shotorg, '-1 -1 -1','1 1 1', t_turret.tur_shotorg + (t_turret.tur_shotdir_updated * t_turret.tur_dist_aimpos), MOVE_NORMAL,t_turret);
541
542         t_turret.tur_dist_impact_to_aimpos = vlen(trace_endpos - t_turret.tur_aimpos) - (vlen(t_turret.enemy.maxs - t_turret.enemy.mins) * 0.5);
543         t_turret.tur_impactent                   = trace_ent;
544         t_turret.tur_impacttime                 = vlen(t_turret.tur_shotorg - trace_endpos) / t_turret.shot_speed;
545 }
546
547 /**
548 ** Handles head rotation according to
549 ** the units .track_type and .track_flags
550 **/
551 .float turret_framecounter;
552 void turret_track(entity this)
553 {
554         vector target_angle; // This is where we want to aim
555         vector move_angle;   // This is where we can aim
556         float f_tmp;
557         vector v1, v2;
558         v1 = this.tur_head.angles;
559         v2 = this.tur_head.avelocity;
560
561         if (this.track_flags == TFL_TRACK_NO)
562                 return;
563
564         if(!this.active)
565                 target_angle = this.idle_aim - ('1 0 0' * this.aim_maxpitch);
566         else if (this.enemy == NULL)
567         {
568                 if(time > this.lip)
569                         target_angle = this.idle_aim + this.angles;
570                 else
571                         target_angle = vectoangles(normalize(this.tur_aimpos - this.tur_shotorg));
572         }
573         else
574         {
575                 target_angle = vectoangles(normalize(this.tur_aimpos - this.tur_shotorg));
576         }
577
578         this.tur_head.angles_x = anglemods(this.tur_head.angles_x);
579         this.tur_head.angles_y = anglemods(this.tur_head.angles_y);
580
581         // Find the diffrence between where we currently aim and where we want to aim
582         //move_angle = target_angle - (this.angles + this.tur_head.angles);
583         //move_angle = shortangle_vxy(move_angle,(this.angles + this.tur_head.angles));
584
585         move_angle = AnglesTransform_ToAngles(AnglesTransform_LeftDivide(AnglesTransform_FromAngles(this.angles), AnglesTransform_FromAngles(target_angle))) - this.tur_head.angles;
586         move_angle = shortangle_vxy(move_angle, this.tur_head.angles);
587
588         switch(this.track_type)
589         {
590                 case TFL_TRACKTYPE_STEPMOTOR:
591                         f_tmp = this.aim_speed * this.ticrate; // dgr/sec -> dgr/tic
592                         if (this.track_flags & TFL_TRACK_PITCH)
593                         {
594                                 this.tur_head.angles_x += bound(-f_tmp,move_angle_x, f_tmp);
595                                 if(this.tur_head.angles_x > this.aim_maxpitch)
596                                         this.tur_head.angles_x = this.aim_maxpitch;
597
598                                 if(this.tur_head.angles_x  < -this.aim_maxpitch)
599                                         this.tur_head.angles_x = this.aim_maxpitch;
600                         }
601
602                         if (this.track_flags & TFL_TRACK_ROTATE)
603                         {
604                                 this.tur_head.angles_y += bound(-f_tmp, move_angle_y, f_tmp);
605                                 if(this.tur_head.angles_y > this.aim_maxrotate)
606                                         this.tur_head.angles_y = this.aim_maxrotate;
607
608                                 if(this.tur_head.angles_y  < -this.aim_maxrotate)
609                                         this.tur_head.angles_y = this.aim_maxrotate;
610                         }
611
612                         // CSQC
613                         this.SendFlags  |= TNSF_ANG;
614
615                         return;
616
617                 case TFL_TRACKTYPE_FLUIDINERTIA:
618                         f_tmp = this.aim_speed * this.ticrate; // dgr/sec -> dgr/tic
619                         move_angle_x = bound(-this.aim_speed, move_angle_x * this.track_accel_pitch * f_tmp, this.aim_speed);
620                         move_angle_y = bound(-this.aim_speed, move_angle_y * this.track_accel_rotate * f_tmp, this.aim_speed);
621                         move_angle = (this.tur_head.avelocity * this.track_blendrate) + (move_angle * (1 - this.track_blendrate));
622                         break;
623
624                 case TFL_TRACKTYPE_FLUIDPRECISE:
625
626                         move_angle_y = bound(-this.aim_speed, move_angle_y, this.aim_speed);
627                         move_angle_x = bound(-this.aim_speed, move_angle_x, this.aim_speed);
628
629                         break;
630         }
631
632         //  pitch
633         if (this.track_flags & TFL_TRACK_PITCH)
634         {
635                 this.tur_head.avelocity_x = move_angle_x;
636                 if((this.tur_head.angles_x + this.tur_head.avelocity_x * this.ticrate) > this.aim_maxpitch)
637                 {
638                         this.tur_head.avelocity_x = 0;
639                         this.tur_head.angles_x = this.aim_maxpitch;
640
641                         this.SendFlags  |= TNSF_ANG;
642                 }
643
644                 if((this.tur_head.angles_x + this.tur_head.avelocity_x * this.ticrate) < -this.aim_maxpitch)
645                 {
646                         this.tur_head.avelocity_x = 0;
647                         this.tur_head.angles_x = -this.aim_maxpitch;
648
649                         this.SendFlags  |= TNSF_ANG;
650                 }
651         }
652
653         //  rot
654         if (this.track_flags & TFL_TRACK_ROTATE)
655         {
656                 this.tur_head.avelocity_y = move_angle_y;
657
658                 if((this.tur_head.angles_y + this.tur_head.avelocity_y * this.ticrate) > this.aim_maxrotate)
659                 {
660                         this.tur_head.avelocity_y = 0;
661                         this.tur_head.angles_y = this.aim_maxrotate;
662
663                         this.SendFlags  |= TNSF_ANG;
664                 }
665
666                 if((this.tur_head.angles_y + this.tur_head.avelocity_y * this.ticrate) < -this.aim_maxrotate)
667                 {
668                         this.tur_head.avelocity_y = 0;
669                         this.tur_head.angles_y = -this.aim_maxrotate;
670
671                         this.SendFlags  |= TNSF_ANG;
672                 }
673         }
674
675         this.SendFlags  |= TNSF_AVEL;
676
677         // Force a angle update every 10'th frame
678         this.turret_framecounter += 1;
679         if(this.turret_framecounter >= 10)
680         {
681                 this.SendFlags |= TNSF_ANG;
682                 this.turret_framecounter = 0;
683         }
684 }
685
686 /*
687  + TFL_TARGETSELECT_NO
688  + TFL_TARGETSELECT_LOS
689  + TFL_TARGETSELECT_PLAYERS
690  + TFL_TARGETSELECT_MISSILES
691  + TFL_TARGETSELECT_VEHICLES
692  - TFL_TARGETSELECT_TRIGGERTARGET
693  + TFL_TARGETSELECT_ANGLELIMITS
694  + TFL_TARGETSELECT_RANGELIMITS
695  + TFL_TARGETSELECT_TEAMCHECK
696  - TFL_TARGETSELECT_NOBUILTIN
697  + TFL_TARGETSELECT_OWNTEAM
698 */
699
700 /**
701 ** Evaluate a entity for target valitity based on validate_flags
702 ** NOTE: the caller must check takedamage before calling this, to inline this check.
703 **/
704 float turret_validate_target(entity e_turret, entity e_target, float validate_flags)
705 {
706         vector v_tmp;
707
708         //if(!validate_flags & TFL_TARGETSELECT_NOBUILTIN)
709         //      return -0.5;
710
711         if(!e_target)
712                 return -2;
713
714         if(e_target.owner == e_turret)
715                 return -0.5;
716
717         if(!checkpvs(e_target.origin, e_turret))
718                 return -1;
719
720         if(e_target.alpha != 0 && e_target.alpha <= 0.3)
721                 return -1;
722
723         if(MUTATOR_CALLHOOK(TurretValidateTarget, e_turret, e_target, validate_flags))
724                 return M_ARGV(3, float);
725
726         if (validate_flags & TFL_TARGETSELECT_NO)
727                 return -4;
728
729         // If only this was used more..
730         if (e_target.flags & FL_NOTARGET)
731                 return -5;
732
733         // Cant touch this
734         if (GetResourceAmount(e_target, RESOURCE_HEALTH) <= 0)
735                 return -6;
736         else if(STAT(FROZEN, e_target) > 0)
737                 return -6;
738
739         // vehicle
740         if(IS_VEHICLE(e_target))
741         {
742                 if ((validate_flags & TFL_TARGETSELECT_VEHICLES) && !e_target.owner)
743                         return -7;
744         }
745
746         // player
747         if (IS_CLIENT(e_target))
748         {
749                 if(!(validate_flags & TFL_TARGETSELECT_PLAYERS))
750                         return -7;
751
752                 if (IS_DEAD(e_target))
753                         return -8;
754         }
755
756         // enemy turrets
757         if(validate_flags & TFL_TARGETSELECT_NOTURRETS)
758         if(e_target.owner.tur_head == e_target)
759         if(e_target.team != e_turret.team) // Dont break support units.
760                 return -9;
761
762         // Missile
763         if (e_target.flags & FL_PROJECTILE)
764         if(!(validate_flags & TFL_TARGETSELECT_MISSILES))
765                 return -10;
766
767         if (validate_flags & TFL_TARGETSELECT_MISSILESONLY)
768         if(!(e_target.flags & FL_PROJECTILE))
769                 return -10.5;
770
771         // Team check
772         if (validate_flags & TFL_TARGETSELECT_TEAMCHECK)
773         {
774                 if (validate_flags & TFL_TARGETSELECT_OWNTEAM)
775                 {
776                         if (e_target.team != e_turret.team)
777                                 return -11;
778
779                         if (e_turret.team != e_target.owner.team)
780                                 return -12;
781                 }
782                 else
783                 {
784                         if (e_target.team == e_turret.team)
785                                 return -13;
786
787                         if (e_turret.team == e_target.owner.team)
788                                 return -14;
789                 }
790         }
791
792         // Range limits?
793         tvt_dist = vlen(e_turret.origin - real_origin(e_target));
794         if (validate_flags & TFL_TARGETSELECT_RANGELIMITS)
795         {
796                 if (tvt_dist < e_turret.target_range_min)
797                         return -15;
798
799                 if (tvt_dist > e_turret.target_range)
800                         return -16;
801         }
802
803         // Can we even aim this thing?
804         tvt_thadv = angleofs3(e_turret.tur_head.origin, e_turret.angles + e_turret.tur_head.angles, e_target.origin);
805         tvt_tadv = shortangle_vxy(angleofs(e_turret, e_target), e_turret.angles);
806         tvt_thadf = vlen(tvt_thadv);
807         tvt_tadf = vlen(tvt_tadv);
808
809         /*
810         if(validate_flags & TFL_TARGETSELECT_FOV)
811         {
812                 if(e_turret.target_select_fov < tvt_thadf)
813                         return -21;
814         }
815         */
816
817         if (validate_flags & TFL_TARGETSELECT_ANGLELIMITS)
818         {
819                 if (fabs(tvt_tadv_x) > e_turret.aim_maxpitch)
820                         return -17;
821
822                 if (fabs(tvt_tadv_y) > e_turret.aim_maxrotate)
823                         return -18;
824         }
825
826         // Line of sight?
827         if (validate_flags & TFL_TARGETSELECT_LOS)
828         {
829                 v_tmp = real_origin(e_target) + ((e_target.mins + e_target.maxs) * 0.5);
830
831                 traceline(e_turret.origin + '0 0 16', v_tmp, 0, e_turret);
832
833                 if(vdist(v_tmp - trace_endpos, >, e_turret.aim_firetolerance_dist))
834                         return -19;
835         }
836
837         if (e_target.classname == "grapplinghook")
838                 return -20;
839
840         /*
841         if (e_target.classname == "func_button")
842                 return -21;
843         */
844
845 #ifdef TURRET_DEBUG_TARGETSELECT
846         LOG_TRACE("Target:",e_target.netname," is a valid target for ",e_turret.netname);
847 #endif
848
849         return 1;
850 }
851
852 entity turret_select_target(entity this)
853 {
854         entity e;               // target looper entity
855         float  score;   // target looper entity score
856         entity e_enemy;  // currently best scoreing target
857         float  m_score;  // currently best scoreing target's score
858
859         m_score = 0;
860         if(this.enemy && this.enemy.takedamage && turret_validate_target(this,this.enemy,this.target_validate_flags) > 0)
861         {
862                 e_enemy = this.enemy;
863                 m_score = this.turret_score_target(this,e_enemy) * this.target_select_samebias;
864         }
865         else
866                 e_enemy = this.enemy = NULL;
867
868         e = findradius(this.origin, this.target_range);
869
870         // Nothing to aim at?
871         if (!e)
872                 return NULL;
873
874         while (e)
875         {
876                 if(e.takedamage)
877                 {
878                         float f = turret_validate_target(this, e, this.target_select_flags);
879                         //dprint("F is: ", ftos(f), "\n");
880                         if ( f > 0)
881                         {
882                                 score = this.turret_score_target(this,e);
883                                 if ((score > m_score) && (score > 0))
884                                 {
885                                         e_enemy = e;
886                                         m_score = score;
887                                 }
888                         }
889                 }
890                 e = e.chain;
891         }
892
893         return e_enemy;
894 }
895
896
897 /*
898  + = implemented
899  - = not implemented
900
901  + TFL_FIRECHECK_NO
902  + TFL_FIRECHECK_WORLD
903  + TFL_FIRECHECK_DEAD
904  + TFL_FIRECHECK_DISTANCES
905  - TFL_FIRECHECK_LOS
906  + TFL_FIRECHECK_AIMDIST
907  + TFL_FIRECHECK_REALDIST
908  - TFL_FIRECHECK_ANGLEDIST
909  - TFL_FIRECHECK_TEAMCECK
910  + TFL_FIRECHECK_AFF
911  + TFL_FIRECHECK_AMMO_OWN
912  + TFL_FIRECHECK_AMMO_OTHER
913  + TFL_FIRECHECK_REFIRE
914 */
915
916 /**
917 ** Preforms pre-fire checks based on the uints firecheck_flags
918 **/
919 bool turret_firecheck(entity this)
920 {
921         // This one just dont care =)
922         if (this.firecheck_flags & TFL_FIRECHECK_NO)
923                 return true;
924
925         if (this.enemy == NULL)
926                 return false;
927
928         // Ready?
929         if (this.firecheck_flags & TFL_FIRECHECK_REFIRE)
930                 if (this.attack_finished_single[0] > time) return false;
931
932         // Special case: volly fire turret that has to fire a full volly if a shot was fired.
933         if (this.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
934                 if (this.volly_counter != this.shot_volly)
935                         if(this.ammo >= this.shot_dmg)
936                                 return true;
937
938         // Lack of zombies makes shooting dead things unnecessary :P
939         if (this.firecheck_flags & TFL_FIRECHECK_DEAD)
940                 if (IS_DEAD(this.enemy))
941                         return false;
942
943         // Own ammo?
944         if (this.firecheck_flags & TFL_FIRECHECK_AMMO_OWN)
945                 if (this.ammo < this.shot_dmg)
946                         return false;
947
948         // Other's ammo? (support-supply units)
949         if (this.firecheck_flags & TFL_FIRECHECK_AMMO_OTHER)
950                 if (this.enemy.ammo >= this.enemy.ammo_max)
951                         return false;
952
953         // Target of opertunity?
954         if(turret_validate_target(this, this.tur_impactent, this.target_validate_flags) > 0)
955         {
956                 this.enemy = this.tur_impactent;
957                 return true;
958         }
959
960         if (this.firecheck_flags & TFL_FIRECHECK_DISTANCES)
961         {
962                 // To close?
963                 if (this.tur_dist_aimpos < this.target_range_min)
964                         if(turret_validate_target(this, this.tur_impactent, this.target_validate_flags) > 0)
965                                 return true; // Target of opertunity?
966                         else
967                                 return false;
968         }
969
970         // Try to avoid FF?
971         if (this.firecheck_flags & TFL_FIRECHECK_AFF)
972                 if (this.tur_impactent.team == this.team)
973                         return false;
974
975         // aim<->predicted impact
976         if (this.firecheck_flags & TFL_FIRECHECK_AIMDIST)
977                 if (this.tur_dist_impact_to_aimpos > this.aim_firetolerance_dist)
978                         return false;
979
980         // Volly status
981         if (this.shot_volly > 1)
982                 if (this.volly_counter == this.shot_volly)
983                         if (this.ammo < (this.shot_dmg * this.shot_volly))
984                                 return false;
985
986         /*if(this.firecheck_flags & TFL_FIRECHECK_VERIFIED)
987                 if(this.tur_impactent != this.enemy)
988                         return false;*/
989
990         return true;
991 }
992
993 bool turret_checkfire(entity this)
994 {
995         if(MUTATOR_CALLHOOK(Turret_CheckFire, this))
996                 return M_ARGV(1, bool);
997
998         return this.turret_firecheckfunc(this);
999 }
1000
1001 void turret_fire(entity this)
1002 {
1003         if (autocvar_g_turrets_nofire != 0)
1004                 return;
1005
1006         if(MUTATOR_CALLHOOK(TurretFire, this))
1007                 return;
1008
1009         Turret info = get_turretinfo(this.m_id);
1010         info.tr_attack(info, this);
1011
1012         this.attack_finished_single[0] = time + this.shot_refire;
1013         this.ammo -= this.shot_dmg;
1014         this.volly_counter = this.volly_counter - 1;
1015
1016         if (this.volly_counter <= 0)
1017         {
1018                 this.volly_counter = this.shot_volly;
1019
1020                 if (this.shoot_flags & TFL_SHOOT_CLEARTARGET)
1021                         this.enemy = NULL;
1022
1023                 if (this.shot_volly > 1)
1024                         this.attack_finished_single[0] = time + this.shot_volly_refire;
1025         }
1026
1027 #ifdef TURRET_DEBUG
1028         if (this.enemy) paint_target3(this.tur_aimpos, 64, this.tur_debug_rvec, this.tur_impacttime + 0.25);
1029 #endif
1030 }
1031
1032 void turret_think(entity this)
1033 {
1034         this.nextthink = time + this.ticrate;
1035
1036         MUTATOR_CALLHOOK(TurretThink, this);
1037
1038 #ifdef TURRET_DEBUG
1039         if (this.tur_debug_tmr1 < time)
1040         {
1041                 if (this.enemy) paint_target (this.enemy,128,this.tur_debug_rvec,0.9);
1042                 paint_target(this,256,this.tur_debug_rvec,0.9);
1043                 this.tur_debug_tmr1 = time + 1;
1044         }
1045 #endif
1046
1047         // Handle ammo
1048         if (!(this.spawnflags & TSF_NO_AMMO_REGEN))
1049         if (this.ammo < this.ammo_max)
1050                 this.ammo = min(this.ammo + this.ammo_recharge, this.ammo_max);
1051
1052         // Inactive turrets needs to run the think loop,
1053         // So they can handle animation and wake up if need be.
1054         if(!this.active)
1055         {
1056                 turret_track(this);
1057                 return;
1058         }
1059
1060         // This is typicaly used for zaping every target in range
1061         // turret_fusionreactor uses this to recharge friendlys.
1062         if (this.shoot_flags & TFL_SHOOT_HITALLVALID)
1063         {
1064                 // Do a this.turret_fire for every valid target.
1065                 entity e = findradius(this.origin,this.target_range);
1066                 while (e)
1067                 {
1068                         if(e.takedamage)
1069                         {
1070                                 if (turret_validate_target(this,e,this.target_validate_flags))
1071                                 {
1072                                         this.enemy = e;
1073
1074                                         turret_do_updates(this);
1075
1076                                         if (turret_checkfire(this))
1077                                                 turret_fire(this);
1078                                 }
1079                         }
1080
1081                         e = e.chain;
1082                 }
1083                 this.enemy = NULL;
1084         }
1085         else if(this.shoot_flags & TFL_SHOOT_CUSTOM)
1086         {
1087                 // This one is doing something.. oddball. assume its handles what needs to be handled.
1088
1089                 // Predict?
1090                 if(!(this.aim_flags & TFL_AIM_NO))
1091                         this.tur_aimpos = turret_aim_generic(this);
1092
1093                 // Turn & pitch?
1094                 if(!(this.track_flags & TFL_TRACK_NO))
1095                         turret_track(this);
1096
1097                 turret_do_updates(this);
1098
1099                 // Fire?
1100                 if (turret_checkfire(this))
1101                         turret_fire(this);
1102         }
1103         else
1104         {
1105                 // Special case for volly always. if it fired once it must compleate the volly.
1106                 if(this.shoot_flags & TFL_SHOOT_VOLLYALWAYS)
1107                         if(this.volly_counter != this.shot_volly)
1108                         {
1109                                 // Predict or whatnot
1110                                 if(!(this.aim_flags & TFL_AIM_NO))
1111                                         this.tur_aimpos = turret_aim_generic(this);
1112
1113                                 // Turn & pitch
1114                                 if(!(this.track_flags & TFL_TRACK_NO))
1115                                         turret_track(this);
1116
1117                                 turret_do_updates(this);
1118
1119                                 // Fire!
1120                                 if (turret_checkfire(this))
1121                                         turret_fire(this);
1122
1123                                 Turret tur = get_turretinfo(this.m_id);
1124                                 tur.tr_think(tur, this);
1125
1126                                 return;
1127                         }
1128
1129                 // Check if we have a vailid enemy, and try to find one if we dont.
1130
1131                 // g_turrets_targetscan_maxdelay forces a target re-scan at least this often
1132                 float do_target_scan = 0;
1133                 if((this.target_select_time + autocvar_g_turrets_targetscan_maxdelay) < time)
1134                         do_target_scan = 1;
1135
1136                 // Old target (if any) invalid?
1137                 if(this.target_validate_time < time)
1138                 if (turret_validate_target(this, this.enemy, this.target_validate_flags) <= 0)
1139                 {
1140                         this.enemy = NULL;
1141                         this.target_validate_time = time + 0.5;
1142                         do_target_scan = 1;
1143                 }
1144
1145                 // But never more often then g_turrets_targetscan_mindelay!
1146                 if (this.target_select_time + autocvar_g_turrets_targetscan_mindelay > time)
1147                         do_target_scan = 0;
1148
1149                 if(do_target_scan)
1150                 {
1151                         this.enemy = turret_select_target(this);
1152                         this.target_select_time = time;
1153                 }
1154
1155                 // No target, just go to idle, do any custom stuff and bail.
1156                 if (this.enemy == NULL)
1157                 {
1158                         // Turn & pitch
1159                         if(!(this.track_flags & TFL_TRACK_NO))
1160                                 turret_track(this);
1161
1162                         Turret tur = get_turretinfo(this.m_id);
1163                         tur.tr_think(tur, this);
1164
1165                         // And bail.
1166                         return;
1167                 }
1168                 else
1169                         this.lip = time + autocvar_g_turrets_aimidle_delay; // Keep track of the last time we had a target.
1170
1171                 // Predict?
1172                 if(!(this.aim_flags & TFL_AIM_NO))
1173                         this.tur_aimpos = turret_aim_generic(this);
1174
1175                 // Turn & pitch?
1176                 if(!(this.track_flags & TFL_TRACK_NO))
1177                         turret_track(this);
1178
1179                 turret_do_updates(this);
1180
1181                 // Fire?
1182                 if (turret_checkfire(this))
1183                         turret_fire(this);
1184         }
1185
1186         Turret tur = get_turretinfo(this.m_id);
1187         tur.tr_think(tur, this);
1188 }
1189
1190 /*
1191         When .used a turret switch team to activator.team.
1192         If activator is NULL, the turret go inactive.
1193 */
1194 void turret_use(entity this, entity actor, entity trigger)
1195 {
1196         LOG_TRACE("Turret ",this.netname, " used by ", actor.classname);
1197
1198         this.team = actor.team;
1199
1200         if(this.team == 0)
1201                 this.active = ACTIVE_NOT;
1202         else
1203                 this.active = ACTIVE_ACTIVE;
1204
1205 }
1206
1207 void turret_link(entity this)
1208 {
1209         Net_LinkEntity(this, true, 0, turret_send);
1210         setthink(this, turret_think);
1211         this.nextthink = time;
1212         this.tur_head.effects = EF_NODRAW;
1213 }
1214
1215 void turrets_manager_think(entity this)
1216 {
1217         this.nextthink = time + 1;
1218
1219         if (autocvar_g_turrets_reloadcvars == 1)
1220         {
1221                 IL_EACH(g_turrets, true,
1222                 {
1223                         load_unit_settings(it, true);
1224                         Turret tur = get_turretinfo(it.m_id);
1225                         tur.tr_think(tur, it);
1226                 });
1227                 cvar_set("g_turrets_reloadcvars", "0");
1228         }
1229 }
1230
1231 void turret_initparams(entity tur)
1232 {
1233         #define TRY(x) (x) ? (x)
1234         tur.respawntime                 = max  (-1,              (TRY(tur.respawntime)               :  60                                         ));
1235         tur.shot_refire                 = bound(0.01,            (TRY(tur.shot_refire)               :  1                                          ), 9999);
1236         tur.shot_dmg                    = max  (1,               (TRY(tur.shot_dmg)                  :  tur.shot_refire * 50                       ));
1237         tur.shot_radius                 = max  (1,               (TRY(tur.shot_radius)               :  tur.shot_dmg * 0.5                         ));
1238         tur.shot_speed                  = max  (1,               (TRY(tur.shot_speed)                :  2500                                       ));
1239         tur.shot_spread                 = bound(0.0001,          (TRY(tur.shot_spread)               :  0.0125                                     ), 500);
1240         tur.shot_force                  = bound(0.001,           (TRY(tur.shot_force)                :  tur.shot_dmg * 0.5 + tur.shot_radius * 0.5 ), 5000);
1241         tur.shot_volly                  = bound(1,               (TRY(tur.shot_volly)                :  1                                          ), floor(tur.ammo_max / tur.shot_dmg));
1242         tur.shot_volly_refire           = bound(tur.shot_refire, (TRY(tur.shot_volly_refire)         :  tur.shot_refire * tur.shot_volly           ), 60);
1243         tur.target_range                = bound(0,               (TRY(tur.target_range)              :  tur.shot_speed * 0.5                       ), max_shot_distance);
1244         tur.target_range_min            = bound(0,               (TRY(tur.target_range_min)          :  tur.shot_radius * 2                        ), max_shot_distance);
1245         tur.target_range_optimal        = bound(0,               (TRY(tur.target_range_optimal)      :  tur.target_range * 0.5                     ), max_shot_distance);
1246         tur.aim_maxrotate               = bound(0,               (TRY(tur.aim_maxrotate)             :  90                                         ), 360);
1247         tur.aim_maxpitch                = bound(0,               (TRY(tur.aim_maxpitch)              :  20                                         ), 90);
1248         tur.aim_speed                   = bound(0.1,             (TRY(tur.aim_speed)                 :  36                                         ), 1000);
1249         tur.aim_firetolerance_dist      = bound(0.1,             (TRY(tur.aim_firetolerance_dist)    :  5 + (tur.shot_radius * 2)                  ), max_shot_distance);
1250         tur.target_select_rangebias     = bound(-10,             (TRY(tur.target_select_rangebias)   :  1                                          ), 10);
1251         tur.target_select_samebias      = bound(-10,             (TRY(tur.target_select_samebias)    :  1                                          ), 10);
1252         tur.target_select_anglebias     = bound(-10,             (TRY(tur.target_select_anglebias)   :  1                                          ), 10);
1253         tur.target_select_missilebias   = bound(-10,             (TRY(tur.target_select_missilebias) :  1                                          ), 10);
1254         tur.target_select_playerbias    = bound(-10,             (TRY(tur.target_select_playerbias)  :  1                                          ), 10);
1255         tur.ammo_max                    = max  (tur.shot_dmg,    (TRY(tur.ammo_max)                  :  tur.shot_dmg * 10                          ));
1256         tur.ammo_recharge               = max  (0,               (TRY(tur.ammo_recharge)             :  tur.shot_dmg * 0.5                         ));
1257         #undef TRY
1258 }
1259
1260 bool turret_closetotarget(entity this, vector targ)
1261 {
1262         vector path_extra_size = '64 64 64';
1263         return boxesoverlap(targ - path_extra_size, targ + path_extra_size, this.absmin - path_extra_size, this.absmax + path_extra_size);
1264 }
1265
1266 void turret_findtarget(entity this)
1267 {
1268         entity e = find(NULL, classname, "turret_manager");
1269         if(!e)
1270         {
1271                 e = new(turret_manager);
1272                 setthink(e, turrets_manager_think);
1273                 e.nextthink = time + 2;
1274         }
1275
1276         entity targ = find(NULL, targetname, this.target);
1277         if(targ.classname == "turret_checkpoint")
1278                 return; // turrets don't defend checkpoints?
1279
1280         if (!targ)
1281         {
1282                 this.target = "";
1283                 LOG_TRACE("Turret has invalid defendpoint!");
1284         }
1285
1286         this.tur_defend = targ;
1287         this.idle_aim = this.tur_head.angles + angleofs(this.tur_head, targ);
1288 }
1289
1290 bool turret_initialize(entity this, Turret tur)
1291 {
1292         if(!autocvar_g_turrets)
1293                 return false;
1294
1295         if(tur.m_id == 0)
1296                 return false; // invalid turret
1297
1298         // if tur_head exists, we can assume this turret re-spawned
1299         if(!this.tur_head) {
1300                 tur.tr_precache(tur);
1301                 IL_PUSH(g_turrets, this);
1302                 IL_PUSH(g_bot_targets, this);
1303         }
1304
1305         if(!(this.spawnflags & TSF_SUSPENDED))
1306                 droptofloor(this);
1307
1308         this.netname = tur.netname;
1309         load_unit_settings(this, 0);
1310
1311         if(!this.team || !teamplay)             { this.team = FLOAT_MAX; }
1312         if(!this.ticrate)                               { this.ticrate = ((this.turret_flags & TUR_FLAG_SUPPORT) ? 0.2 : 0.1); }
1313         if(!GetResourceAmount(this, RESOURCE_HEALTH)) { SetResourceAmountExplicit(this, RESOURCE_HEALTH, 1000); }
1314         if(!this.shot_refire)                   { this.shot_refire = 1; }
1315         if(!this.tur_shotorg)                   { this.tur_shotorg = '50 0 50'; }
1316         if(!this.turret_flags)                  { this.turret_flags = TUR_FLAG_SPLASH | TUR_FLAG_MEDPROJ | TUR_FLAG_PLAYER; }
1317         if(!this.damage_flags)                  { this.damage_flags = TFL_DMG_YES | TFL_DMG_RETALIATE | TFL_DMG_AIMSHAKE; }
1318         if(!this.aim_flags)                             { this.aim_flags = TFL_AIM_LEAD | TFL_AIM_SHOTTIMECOMPENSATE; }
1319         if(!this.track_type)                    { this.track_type = TFL_TRACKTYPE_STEPMOTOR; }
1320         if(!this.track_flags)                   { this.track_flags = TFL_TRACK_PITCH | TFL_TRACK_ROTATE; }
1321         if(!this.ammo_flags)                    { this.ammo_flags = TFL_AMMO_ENERGY | TFL_AMMO_RECHARGE; }
1322         if(!this.target_select_flags)   { this.target_select_flags = TFL_TARGETSELECT_LOS | TFL_TARGETSELECT_TEAMCHECK | TFL_TARGETSELECT_RANGELIMITS | TFL_TARGETSELECT_ANGLELIMITS; }
1323         if(!this.firecheck_flags)               { this.firecheck_flags = TFL_FIRECHECK_DEAD | TFL_FIRECHECK_DISTANCES | TFL_FIRECHECK_LOS
1324                                                                                                                    | TFL_FIRECHECK_AIMDIST | TFL_FIRECHECK_TEAMCHECK | TFL_FIRECHECK_AMMO_OWN | TFL_FIRECHECK_REFIRE; }
1325
1326         if(this.track_type != TFL_TRACKTYPE_STEPMOTOR)
1327         {
1328                 // Fluid / Ineria mode. Looks mutch nicer.
1329                 // Can reduce aim preformance alot, needs a bit diffrent aimspeed
1330
1331                 this.aim_speed = bound(0.1, ((!this.aim_speed) ? 180 : this.aim_speed), 1000);
1332
1333                 if(!this.track_accel_pitch)             { this.track_accel_pitch = 0.5; }
1334                 if(!this.track_accel_rotate)    { this.track_accel_rotate = 0.5; }
1335                 if(!this.track_blendrate)               { this.track_blendrate = 0.35; }
1336         }
1337
1338         turret_initparams(this);
1339
1340         this.turret_flags = TUR_FLAG_ISTURRET | (tur.spawnflags);
1341
1342         if(this.turret_flags & TUR_FLAG_SPLASH)
1343                 this.aim_flags |= TFL_AIM_SPLASH;
1344
1345         if(this.turret_flags & TUR_FLAG_MISSILE)
1346                 this.target_select_flags |= TFL_TARGETSELECT_MISSILES;
1347
1348         if(this.turret_flags & TUR_FLAG_PLAYER)
1349                 this.target_select_flags |= TFL_TARGETSELECT_PLAYERS;
1350
1351         if(this.spawnflags & TSL_NO_RESPAWN)
1352                 this.damage_flags |= TFL_DMG_DEATH_NORESPAWN;
1353
1354         if (this.turret_flags & TUR_FLAG_SUPPORT)
1355                 this.turret_score_target = turret_targetscore_support;
1356         else
1357                 this.turret_score_target = turret_targetscore_generic;
1358
1359         ++turret_count;
1360
1361         _setmodel(this, tur.model);
1362         setsize(this, tur.m_mins, tur.m_maxs);
1363
1364         this.m_id                                       = tur.m_id;
1365         this.classname                          = "turret_main";
1366         this.active                                     = ACTIVE_ACTIVE;
1367         this.effects                            = EF_NODRAW;
1368         this.netname                            = tur.turret_name;
1369         this.ticrate                            = bound(sys_frametime, this.ticrate, 60);
1370         this.max_health                         = GetResourceAmount(this, RESOURCE_HEALTH);
1371         this.target_validate_flags      = this.target_select_flags;
1372         this.ammo                                       = this.ammo_max;
1373         this.ammo_recharge                 *= this.ticrate;
1374         this.solid                                      = SOLID_BBOX;
1375         this.takedamage                         = DAMAGE_AIM;
1376         set_movetype(this, MOVETYPE_NOCLIP);
1377         this.view_ofs                           = '0 0 0';
1378         this.idle_aim                           = '0 0 0';
1379         this.turret_firecheckfunc       = turret_firecheck;
1380         this.event_damage                       = turret_damage;
1381         this.event_heal                         = turret_heal;
1382         this.use                                        = turret_use;
1383         this.bot_attack                         = true;
1384         this.nextthink                          = time + 1;
1385         this.nextthink                     += turret_count * sys_frametime;
1386
1387         this.tur_head = new(turret_head);
1388         _setmodel(this.tur_head, tur.head_model);
1389         setsize(this.tur_head, '0 0 0', '0 0 0');
1390         setorigin(this.tur_head, '0 0 0');
1391         setattachment(this.tur_head, this, "tag_head");
1392
1393         this.tur_head.netname           = this.tur_head.classname;
1394         this.tur_head.team                      = this.team;
1395         this.tur_head.owner                     = this;
1396         this.tur_head.takedamage        = DAMAGE_NO;
1397         this.tur_head.solid                     = SOLID_NOT;
1398         set_movetype(this.tur_head, this.move_movetype);
1399
1400         this.weaponentities[0] = this; // lol
1401
1402         if(!this.tur_defend && this.target != "")
1403                 InitializeEntity(this, turret_findtarget, INITPRIO_FINDTARGET);
1404
1405 #ifdef TURRET_DEBUG
1406         this.tur_debug_start = this.nextthink;
1407         while(vdist(this.tur_debug_rvec, <, 2))
1408                 this.tur_debug_rvec = randomvec() * 4;
1409
1410         this.tur_debug_rvec_x = fabs(this.tur_debug_rvec_x);
1411         this.tur_debug_rvec_y = fabs(this.tur_debug_rvec_y);
1412         this.tur_debug_rvec_z = fabs(this.tur_debug_rvec_z);
1413 #endif
1414
1415         turret_link(this);
1416         turret_respawn(this);
1417         turret_tag_fire_update(this);
1418
1419         tur.tr_setup(tur, this);
1420
1421         if(MUTATOR_CALLHOOK(TurretSpawn, this))
1422                 return false;
1423
1424         return true;
1425 }
1426 #endif