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