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