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