]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/weapons/weaponsystem.qc
Weapons: independent `weapon_think` and `weapon_nextthink`
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / weapons / weaponsystem.qc
1 #include "weaponsystem.qh"
2
3 #include "selection.qh"
4
5 #include "../command/common.qh"
6 #include "../mutators/all.qh"
7 #include "../round_handler.qh"
8 #include "../t_items.qh"
9 #include "../../common/animdecide.qh"
10 #include "../../common/constants.qh"
11 #include "../../common/monsters/all.qh"
12 #include "../../common/notifications.qh"
13 #include "../../common/util.qh"
14 #include "../../common/weapons/all.qh"
15 #include "../../lib/csqcmodel/sv_model.qh"
16
17 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float algn)
18 {
19         switch (algn)
20         {
21                 default: case 3: break; // right alignment
22                 case 4: vecs.y = -vecs.y;
23                         break;              // left
24                 case 1: case 2: vecs.y = 0;
25                         vecs.z -= 2;
26                         break;              // center
27         }
28
29         return vecs;
30 }
31
32 vector shotorg_adjust_values(vector vecs, bool y_is_right, bool visual, int algn)
33 {
34         string s;
35
36         if (visual)
37         {
38                 vecs = shotorg_adjustfromclient(vecs, y_is_right, algn);
39         }
40         else if (autocvar_g_shootfromeye)
41         {
42                 vecs.y = vecs.z = 0;
43         }
44         else if (autocvar_g_shootfromcenter)
45         {
46                 vecs.y = 0;
47                 vecs.z -= 2;
48         }
49         else if ((s = autocvar_g_shootfromfixedorigin) != "")
50         {
51                 vector v = stov(s);
52                 if (y_is_right) v.y = -v.y;
53                 if (v.x != 0) vecs.x = v.x;
54                 vecs.y = v.y;
55                 vecs.z = v.z;
56         }
57         else  // just do the same as top
58         {
59                 vecs = shotorg_adjustfromclient(vecs, y_is_right, algn);
60         }
61
62         return vecs;
63 }
64
65 vector shotorg_adjust(vector vecs, bool y_is_right, bool visual, int algn)
66 {
67         return shotorg_adjust_values(vecs, y_is_right, visual, algn);
68 }
69
70 .int state;
71
72 .float weapon_frametime;
73
74 float W_WeaponRateFactor()
75 {
76         float t = 1.0 / g_weaponratefactor;
77
78         MUTATOR_CALLHOOK(WeaponRateFactor, t);
79         t = weapon_rate;
80
81         return t;
82 }
83
84 float W_WeaponSpeedFactor()
85 {
86         float t = 1.0 * g_weaponspeedfactor;
87
88         MUTATOR_CALLHOOK(WeaponSpeedFactor, t);
89         t = ret_float;
90
91         return t;
92 }
93
94
95 void weapon_thinkf(entity actor, .entity weaponentity, float fr, float t, void(Weapon thiswep, entity actor,
96     .entity weaponentity, int fire) func);
97
98 bool CL_Weaponentity_CustomizeEntityForClient()
99 {
100         SELFPARAM();
101         this.viewmodelforclient = this.owner;
102         if (IS_SPEC(other) && other.enemy == this.owner) this.viewmodelforclient = other;
103         return true;
104 }
105
106 /*
107  * supported formats:
108  *
109  * 1. simple animated model, muzzle flash handling on h_ model:
110  *    h_tuba.dpm, h_tuba.dpm.framegroups - invisible model controlling the animation
111  *      tags:
112  *        shot = muzzle end (shot origin, also used for muzzle flashes)
113  *        shell = casings ejection point (must be on the right hand side of the gun)
114  *        weapon = attachment for v_tuba.md3
115  *    v_tuba.md3 - first and third person model
116  *    g_tuba.md3 - pickup model
117  *
118  * 2. simple animated model, muzzle flash handling on v_ model:
119  *    h_tuba.dpm, h_tuba.dpm.framegroups - invisible model controlling the animation
120  *      tags:
121  *        weapon = attachment for v_tuba.md3
122  *    v_tuba.md3 - first and third person model
123  *      tags:
124  *        shot = muzzle end (shot origin, also used for muzzle flashes)
125  *        shell = casings ejection point (must be on the right hand side of the gun)
126  *    g_tuba.md3 - pickup model
127  *
128  * 3. fully animated model, muzzle flash handling on h_ model:
129  *    h_tuba.dpm, h_tuba.dpm.framegroups - animated first person model
130  *      tags:
131  *        shot = muzzle end (shot origin, also used for muzzle flashes)
132  *        shell = casings ejection point (must be on the right hand side of the gun)
133  *        handle = corresponding to the origin of v_tuba.md3 (used for muzzle flashes)
134  *    v_tuba.md3 - third person model
135  *    g_tuba.md3 - pickup model
136  *
137  * 4. fully animated model, muzzle flash handling on v_ model:
138  *    h_tuba.dpm, h_tuba.dpm.framegroups - animated first person model
139  *      tags:
140  *        shot = muzzle end (shot origin)
141  *        shell = casings ejection point (must be on the right hand side of the gun)
142  *    v_tuba.md3 - third person model
143  *      tags:
144  *        shot = muzzle end (for muzzle flashes)
145  *    g_tuba.md3 - pickup model
146  */
147
148 // writes:
149 //   this.origin, this.angles
150 //   this.weaponentity
151 //   this.movedir, this.view_ofs
152 //   attachment stuff
153 //   anim stuff
154 // to free:
155 //   call again with ""
156 //   remove the ent
157 void CL_WeaponEntity_SetModel(entity this, .entity weaponentity, string name)
158 {
159         if (name != "")
160         {
161                 // if there is a child entity, hide it until we're sure we use it
162                 if (this.(weaponentity)) this.(weaponentity).model = "";
163                 _setmodel(this, W_Model(strcat("v_", name, ".md3")));
164                 int v_shot_idx = gettagindex(this, "shot");  // used later
165                 if (!v_shot_idx) v_shot_idx = gettagindex(this, "tag_shot");
166
167                 _setmodel(this, W_Model(strcat("h_", name, ".iqm")));
168                 // preset some defaults that work great for renamed zym files (which don't need an animinfo)
169                 this.anim_fire1  = animfixfps(this, '0 1 0.01', '0 0 0');
170                 this.anim_fire2  = animfixfps(this, '1 1 0.01', '0 0 0');
171                 this.anim_idle   = animfixfps(this, '2 1 0.01', '0 0 0');
172                 this.anim_reload = animfixfps(this, '3 1 0.01', '0 0 0');
173
174                 // if we have a "weapon" tag, let's attach the v_ model to it ("invisible hand" style model)
175                 // if we don't, this is a "real" animated model
176                 if (gettagindex(this, "weapon"))
177                 {
178                         if (!this.(weaponentity)) this.(weaponentity) = new(weaponentity);
179                         _setmodel(this.(weaponentity), W_Model(strcat("v_", name, ".md3")));
180                         setattachment(this.(weaponentity), this, "weapon");
181                 }
182                 else if (gettagindex(this, "tag_weapon"))
183                 {
184                         if (!this.(weaponentity)) this.(weaponentity) = new(weaponentity);
185                         _setmodel(this.(weaponentity), W_Model(strcat("v_", name, ".md3")));
186                         setattachment(this.(weaponentity), this, "tag_weapon");
187                 }
188                 else
189                 {
190                         if (this.(weaponentity)) remove(this.(weaponentity));
191                         this.(weaponentity) = NULL;
192                 }
193
194                 setorigin(this, '0 0 0');
195                 this.angles = '0 0 0';
196                 this.frame = 0;
197                 this.viewmodelforclient = NULL;
198
199                 float idx;
200
201                 if (v_shot_idx)  // v_ model attached to invisible h_ model
202                 {
203                         this.movedir = gettaginfo(this.(weaponentity), v_shot_idx);
204                 }
205                 else
206                 {
207                         idx = gettagindex(this, "shot");
208                         if (!idx) idx = gettagindex(this, "tag_shot");
209                         if (idx)
210                         {
211                                 this.movedir = gettaginfo(this, idx);
212                         }
213                         else
214                         {
215                                 LOG_INFO("WARNING: weapon model ", this.model,
216                                         " does not support the 'shot' tag, will display shots TOTALLY wrong\n");
217                                 this.movedir = '0 0 0';
218                         }
219                 }
220
221                 if (this.(weaponentity))  // v_ model attached to invisible h_ model
222                 {
223                         idx = gettagindex(this.(weaponentity), "shell");
224                         if (!idx) idx = gettagindex(this.(weaponentity), "tag_shell");
225                         if (idx) this.spawnorigin = gettaginfo(this.(weaponentity), idx);
226                 }
227                 else
228                 {
229                         idx = 0;
230                 }
231                 if (!idx)
232                 {
233                         idx = gettagindex(this, "shell");
234                         if (!idx) idx = gettagindex(this, "tag_shell");
235                         if (idx)
236                         {
237                                 this.spawnorigin = gettaginfo(this, idx);
238                         }
239                         else
240                         {
241                                 LOG_INFO("WARNING: weapon model ", this.model,
242                                         " does not support the 'shell' tag, will display casings wrong\n");
243                                 this.spawnorigin = this.movedir;
244                         }
245                 }
246
247                 if (v_shot_idx)
248                 {
249                         this.oldorigin = '0 0 0';  // use regular attachment
250                 }
251                 else
252                 {
253                         if (this.(weaponentity))
254                         {
255                                 idx = gettagindex(this, "weapon");
256                                 if (!idx) idx = gettagindex(this, "tag_weapon");
257                         }
258                         else
259                         {
260                                 idx = gettagindex(this, "handle");
261                                 if (!idx) idx = gettagindex(this, "tag_handle");
262                         }
263                         if (idx)
264                         {
265                                 this.oldorigin = this.movedir - gettaginfo(this, idx);
266                         }
267                         else
268                         {
269                                 LOG_INFO("WARNING: weapon model ", this.model,
270                                         " does not support the 'handle' tag and neither does the v_ model support the 'shot' tag, will display muzzle flashes TOTALLY wrong\n");
271                                 this.oldorigin = '0 0 0';  // there is no way to recover from this
272                         }
273                 }
274
275                 this.viewmodelforclient = this.owner;
276         }
277         else
278         {
279                 this.model = "";
280                 if (this.(weaponentity)) remove(this.(weaponentity));
281                 this.(weaponentity) = NULL;
282                 this.movedir = '0 0 0';
283                 this.spawnorigin = '0 0 0';
284                 this.oldorigin = '0 0 0';
285                 this.anim_fire1  = '0 1 0.01';
286                 this.anim_fire2  = '0 1 0.01';
287                 this.anim_idle   = '0 1 0.01';
288                 this.anim_reload = '0 1 0.01';
289         }
290
291         this.view_ofs = '0 0 0';
292
293         if (this.movedir.x >= 0)
294         {
295                 vector v0 = this.movedir;
296                 this.movedir = shotorg_adjust(v0, false, false, this.owner.cvar_cl_gunalign);
297                 this.view_ofs = shotorg_adjust(v0, false, true, this.owner.cvar_cl_gunalign) - v0;
298         }
299         this.owner.stat_shotorg = compressShotOrigin(this.movedir);
300         this.movedir = decompressShotOrigin(this.owner.stat_shotorg); // make them match perfectly
301
302         this.spawnorigin += this.view_ofs;                            // offset the casings origin by the same amount
303
304         // check if an instant weapon switch occurred
305         setorigin(this, this.view_ofs);
306         // reset animstate now
307         this.wframe = WFRAME_IDLE;
308         setanim(this, this.anim_idle, true, false, true);
309 }
310
311 vector CL_Weapon_GetShotOrg(float wpn)
312 {
313         entity wi = Weapons_from(wpn);
314         entity e = spawn();
315         .entity weaponentity = weaponentities[0];
316         CL_WeaponEntity_SetModel(e, weaponentity, wi.mdl);
317         vector ret = e.movedir;
318         CL_WeaponEntity_SetModel(e, weaponentity, "");
319         remove(e);
320         return ret;
321 }
322
323 ..entity weaponentity_fld;
324
325 void CL_Weaponentity_Think()
326 {
327         SELFPARAM();
328         this.nextthink = time;
329         if (intermission_running) this.frame = this.anim_idle.x;
330         .entity weaponentity = this.weaponentity_fld;
331         if (this.owner.(weaponentity) != this)
332         {
333                 if (this.(weaponentity)) remove(this.(weaponentity));
334                 remove(this);
335                 return;
336         }
337         if (this.owner.deadflag != DEAD_NO)
338         {
339                 this.model = "";
340                 if (this.(weaponentity)) this.(weaponentity).model = "";
341                 return;
342         }
343         if (this.weaponname != this.owner.weaponname || this.dmg != this.owner.modelindex
344             || this.deadflag != this.owner.deadflag)
345         {
346                 this.weaponname = this.owner.weaponname;
347                 this.dmg = this.owner.modelindex;
348                 this.deadflag = this.owner.deadflag;
349
350                 CL_WeaponEntity_SetModel(this, weaponentity, this.owner.weaponname);
351         }
352
353         int tb = (this.effects & (EF_TELEPORT_BIT | EF_RESTARTANIM_BIT));
354         this.effects = this.owner.effects & EFMASK_CHEAP;
355         this.effects &= ~EF_LOWPRECISION;
356         this.effects &= ~EF_FULLBRIGHT;  // can mask team color, so get rid of it
357         this.effects &= ~EF_TELEPORT_BIT;
358         this.effects &= ~EF_RESTARTANIM_BIT;
359         this.effects |= tb;
360         if (weaponentity != weaponentities[0]) this.effects |= EF_NODRAW;
361
362         if (this.owner.alpha == default_player_alpha) this.alpha = default_weapon_alpha;
363         else if (this.owner.alpha != 0) this.alpha = this.owner.alpha;
364         else this.alpha = 1;
365
366         this.glowmod = this.owner.weaponentity_glowmod;
367         this.colormap = this.owner.colormap;
368         if (this.(weaponentity))
369         {
370                 this.(weaponentity).effects = this.effects;
371                 this.(weaponentity).alpha = this.alpha;
372                 this.(weaponentity).colormap = this.colormap;
373                 this.(weaponentity).glowmod = this.glowmod;
374         }
375
376         this.angles = '0 0 0';
377
378         float f = this.weapon_nextthink - time;
379         if (this.state == WS_RAISE && !intermission_running)
380         {
381                 entity newwep = Weapons_from(this.owner.switchweapon);
382                 f = f * g_weaponratefactor / max(f, newwep.switchdelay_raise);
383                 this.angles_x = -90 * f * f;
384         }
385         else if (this.state == WS_DROP && !intermission_running)
386         {
387                 entity oldwep = Weapons_from(this.owner.weapon);
388                 f = 1 - f * g_weaponratefactor / max(f, oldwep.switchdelay_drop);
389                 this.angles_x = -90 * f * f;
390         }
391         else if (this.state == WS_CLEAR)
392         {
393                 f = 1;
394                 this.angles_x = -90 * f * f;
395         }
396 }
397
398 void CL_ExteriorWeaponentity_Think()
399 {
400         SELFPARAM();
401         this.nextthink = time;
402         if (this.owner.exteriorweaponentity != this)
403         {
404                 remove(this);
405                 return;
406         }
407         if (this.owner.deadflag != DEAD_NO)
408         {
409                 this.model = "";
410                 return;
411         }
412         if (this.weaponname != this.owner.weaponname || this.dmg != this.owner.modelindex
413             || this.deadflag != this.owner.deadflag)
414         {
415                 this.weaponname = this.owner.weaponname;
416                 this.dmg = this.owner.modelindex;
417                 this.deadflag = this.owner.deadflag;
418                 if (this.owner.weaponname != "") _setmodel(this, W_Model(strcat("v_", this.owner.weaponname, ".md3")));
419                 else this.model = "";
420
421                 int tag_found;
422                 if ((tag_found = gettagindex(this.owner, "tag_weapon")))
423                 {
424                         this.tag_index = tag_found;
425                         this.tag_entity = this.owner;
426                 }
427                 else
428                 {
429                         setattachment(this, this.owner, "bip01 r hand");
430                 }
431         }
432         this.effects = this.owner.effects;
433         this.effects |= EF_LOWPRECISION;
434         this.effects = this.effects & EFMASK_CHEAP;  // eat performance
435         if (this.owner.alpha == default_player_alpha) this.alpha = default_weapon_alpha;
436         else if (this.owner.alpha != 0) this.alpha = this.owner.alpha;
437         else this.alpha = 1;
438
439         this.glowmod = this.owner.weaponentity_glowmod;
440         this.colormap = this.owner.colormap;
441
442         CSQCMODEL_AUTOUPDATE(this);
443 }
444
445 // spawning weaponentity for client
446 void CL_SpawnWeaponentity(entity e, .entity weaponentity)
447 {
448         entity view = e.(weaponentity) = new(weaponentity);
449         view.solid = SOLID_NOT;
450         view.owner = e;
451         setmodel(view, MDL_Null);  // precision set when changed
452         setorigin(view, '0 0 0');
453         view.angles = '0 0 0';
454         view.viewmodelforclient = e;
455         view.flags = 0;
456         view.weaponentity_fld = weaponentity;
457         view.think = CL_Weaponentity_Think;
458         view.customizeentityforclient = CL_Weaponentity_CustomizeEntityForClient;
459         view.nextthink = time;
460
461         if (weaponentity == weaponentities[0])
462         {
463                 entity exterior = e.exteriorweaponentity = spawn();
464                 exterior.classname = "exteriorweaponentity";
465                 exterior.solid = SOLID_NOT;
466                 exterior.exteriorweaponentity = exterior;
467                 exterior.owner = e;
468                 setorigin(exterior, '0 0 0');
469                 exterior.angles = '0 0 0';
470                 exterior.think = CL_ExteriorWeaponentity_Think;
471                 exterior.nextthink = time;
472
473                 CSQCMODEL_AUTOINIT(exterior);
474         }
475 }
476
477 // Weapon subs
478 void w_clear(Weapon thiswep, entity actor, .entity weaponentity, int fire)
479 {
480         if (actor.weapon != -1)
481         {
482                 actor.weapon = 0;
483                 actor.switchingweapon = 0;
484         }
485         entity this = actor.(weaponentity);
486         if (this)
487         {
488                 this.state = WS_CLEAR;
489                 this.effects = 0;
490         }
491 }
492
493 void w_ready(Weapon thiswep, entity actor, .entity weaponentity, int fire)
494 {
495         entity this = actor.(weaponentity);
496         if (this) this.state = WS_READY;
497         weapon_thinkf(actor, weaponentity, WFRAME_IDLE, 1000000, w_ready);
498 }
499
500 .float prevdryfire;
501 .float prevwarntime;
502 bool weapon_prepareattack_checkammo(Weapon thiswep, entity actor, bool secondary)
503 {
504         if ((actor.items & IT_UNLIMITED_WEAPON_AMMO)) return true;
505         bool ammo = false;
506         if (secondary) WITH(entity, self, actor, ammo = thiswep.wr_checkammo2(thiswep));
507         else WITH(entity, self, actor, ammo = thiswep.wr_checkammo1(thiswep));
508         if (ammo) return true;
509         // always keep the Mine Layer if we placed mines, so that we can detonate them
510         if (thiswep == WEP_MINE_LAYER)
511                 for (entity mine; (mine = find(mine, classname, "mine")); )
512                         if (mine.owner == actor) return false;
513
514         if (thiswep == WEP_SHOTGUN)
515                 if (!secondary && WEP_CVAR(shotgun, secondary) == 1) return false;             // no clicking, just allow
516
517         if (thiswep == Weapons_from(actor.switchweapon) && time - actor.prevdryfire > 1) // only play once BEFORE starting to switch weapons
518         {
519                 sound(actor, CH_WEAPON_A, SND_DRYFIRE, VOL_BASE, ATTEN_NORM);
520                 actor.prevdryfire = time;
521         }
522
523         // check if the other firing mode has enough ammo
524         bool ammo_other = false;
525         if (secondary) WITH(entity, self, actor, ammo_other = thiswep.wr_checkammo1(thiswep));
526         else WITH(entity, self, actor, ammo_other = thiswep.wr_checkammo2(thiswep));
527         if (ammo_other)
528         {
529                 if (time - actor.prevwarntime > 1)
530                 {
531                         Send_Notification(
532                                 NOTIF_ONE,
533                                 actor,
534                                 MSG_MULTI,
535                                 ITEM_WEAPON_PRIMORSEC,
536                                 thiswep.m_id,
537                                 secondary,
538                                 (1 - secondary)
539                                          );
540                 }
541                 actor.prevwarntime = time;
542         }
543         else  // this weapon is totally unable to fire, switch to another one
544         {
545                 W_SwitchToOtherWeapon(actor);
546         }
547
548         return false;
549 }
550
551 .float race_penalty;
552 bool weapon_prepareattack_check(Weapon thiswep, entity actor, .entity weaponentity, bool secondary, float attacktime)
553 {
554         if (!weapon_prepareattack_checkammo(thiswep, actor, secondary)) return false;
555
556         // if sv_ready_restart_after_countdown is set, don't allow the player to shoot
557         // if all players readied up and the countdown is running
558         if (time < game_starttime || time < actor.race_penalty) return false;
559
560         if (timeout_status == TIMEOUT_ACTIVE)  // don't allow the player to shoot while game is paused
561                 return false;
562
563         // do not even think about shooting if switching
564         if (actor.switchweapon != actor.weapon) return false;
565
566         if (attacktime >= 0)
567         {
568                 int slot = weaponslot(weaponentity);
569                 // don't fire if previous attack is not finished
570                 if (ATTACK_FINISHED(actor, slot) > time + actor.weapon_frametime * 0.5) return false;
571                 entity this = actor.(weaponentity);
572                 // don't fire while changing weapon
573                 if (this.state != WS_READY) return false;
574         }
575         return true;
576 }
577
578 void weapon_prepareattack_do(entity actor, .entity weaponentity, bool secondary, float attacktime)
579 {
580         entity this = actor.(weaponentity);
581         this.state = WS_INUSE;
582
583         actor.spawnshieldtime = min(actor.spawnshieldtime, time);  // kill spawn shield when you fire
584
585         // if the weapon hasn't been firing continuously, reset the timer
586         if (attacktime >= 0)
587         {
588                 int slot = weaponslot(weaponentity);
589                 if (ATTACK_FINISHED(actor, slot) < time - actor.weapon_frametime * 1.5)
590                 {
591                         ATTACK_FINISHED(actor, slot) = time;
592                         // dprint("resetting attack finished to ", ftos(time), "\n");
593                 }
594                 ATTACK_FINISHED(actor, slot) = ATTACK_FINISHED(actor, slot) + attacktime * W_WeaponRateFactor();
595         }
596         actor.bulletcounter += 1;
597         // dprint("attack finished ", ftos(ATTACK_FINISHED(actor, slot)), "\n");
598 }
599
600 bool weapon_prepareattack(Weapon thiswep, entity actor, .entity weaponentity, bool secondary, float attacktime)
601 {
602         if (weapon_prepareattack_check(thiswep, actor, weaponentity, secondary, attacktime))
603         {
604                 weapon_prepareattack_do(actor, weaponentity, secondary, attacktime);
605                 return true;
606         }
607         return false;
608 }
609
610 void weapon_thinkf(entity actor, .entity weaponentity, float fr, float t, void(Weapon thiswep, entity actor,
611         .entity weaponentity, int fire) func)
612 {
613         entity this = actor.(weaponentity);
614         bool restartanim;
615         if (fr == WFRAME_DONTCHANGE)
616         {
617                 fr = this.wframe;
618                 restartanim = false;
619         }
620         else if (fr == WFRAME_IDLE)
621         {
622                 restartanim = false;
623         }
624         else
625         {
626                 restartanim = true;
627         }
628
629         vector of = v_forward;
630         vector or = v_right;
631         vector ou = v_up;
632
633         if (this)
634         {
635                 this.wframe = fr;
636                 vector a = '0 0 0';
637                 if (fr == WFRAME_IDLE) a = this.anim_idle;
638                 else if (fr == WFRAME_FIRE1) a = this.anim_fire1;
639                 else if (fr == WFRAME_FIRE2) a = this.anim_fire2;
640                 else  // if (fr == WFRAME_RELOAD)
641                         a = this.anim_reload;
642                 a.z *= g_weaponratefactor;
643                 setanim(this, a, restartanim == false, restartanim, restartanim);
644         }
645
646         v_forward = of;
647         v_right = or;
648         v_up = ou;
649
650         if (this.weapon_think == w_ready && func != w_ready && this.state == WS_RAISE) backtrace(
651                         "Tried to override initial weapon think function - should this really happen?");
652
653         t *= W_WeaponRateFactor();
654
655         // VorteX: haste can be added here
656         if (this.weapon_think == w_ready)
657         {
658                 this.weapon_nextthink = time;
659                 // dprint("started firing at ", ftos(time), "\n");
660         }
661         if (this.weapon_nextthink < time - actor.weapon_frametime * 1.5
662             || this.weapon_nextthink > time + actor.weapon_frametime * 1.5)
663         {
664                 this.weapon_nextthink = time;
665                 // dprint("reset weapon animation timer at ", ftos(time), "\n");
666         }
667         this.weapon_nextthink = this.weapon_nextthink + t;
668         this.weapon_think = func;
669         // dprint("next ", ftos(this.weapon_nextthink), "\n");
670
671         if ((fr == WFRAME_FIRE1 || fr == WFRAME_FIRE2) && t)
672         {
673                 if ((actor.weapon == WEP_SHOCKWAVE.m_id || actor.weapon == WEP_SHOTGUN.m_id)
674                     && fr == WFRAME_FIRE2) animdecide_setaction(actor, ANIMACTION_MELEE, restartanim);
675                 else animdecide_setaction(actor, ANIMACTION_SHOOT, restartanim);
676         }
677         else
678         {
679                 if (actor.anim_upper_action == ANIMACTION_SHOOT
680                     || actor.anim_upper_action == ANIMACTION_MELEE) actor.anim_upper_action = 0;
681         }
682 }
683
684 bool forbidWeaponUse(entity player)
685 {
686         if (time < game_starttime && !autocvar_sv_ready_restart_after_countdown) return true;
687         if (round_handler_IsActive() && !round_handler_IsRoundStarted()) return true;
688         if (player.player_blocked) return true;
689         if (player.frozen) return true;
690         if (player.weapon_blocked) return true;
691         return false;
692 }
693
694 .bool hook_switchweapon;
695
696 void W_WeaponFrame(entity actor)
697 {
698         .entity weaponentity = weaponentities[0]; // TODO: unhardcode
699         entity this = actor.(weaponentity);
700         if (frametime) actor.weapon_frametime = frametime;
701
702         if (!this || actor.health < 1) return; // Dead player can't use weapons and injure impulse commands
703
704
705         if (forbidWeaponUse(actor))
706         {
707                 if (actor.(weaponentity).state != WS_CLEAR)
708                 {
709                         Weapon wpn = Weapons_from(actor.weapon);
710                         w_ready(wpn, actor, weaponentity, (actor.BUTTON_ATCK ? 1 : 0) | (actor.BUTTON_ATCK2 ? 2 : 0));
711                         return;
712                 }
713         }
714
715         if (actor.switchweapon == 0)
716         {
717                 actor.weapon = 0;
718                 actor.switchingweapon = 0;
719                 this.state = WS_CLEAR;
720                 actor.weaponname = "";
721                 // actor.items &= ~IT_AMMO;
722                 return;
723         }
724
725         makevectors(actor.v_angle);
726         vector fo = v_forward;  // save them in case the weapon think functions change it
727         vector ri = v_right;
728         vector up = v_up;
729
730         // Change weapon
731         if (actor.weapon != actor.switchweapon)
732         {
733                 switch (this.state)
734                 {
735                         default:
736                                 LOG_WARNINGF("unhandled weaponentity (%i) state for player (%i): %d\n", this, actor, this.state);
737                                 break;
738                         case WS_INUSE:
739                         case WS_RAISE:
740                                 break;
741                         case WS_CLEAR:
742                         {
743                                 // end switching!
744                                 actor.switchingweapon = actor.switchweapon;
745                                 entity newwep = Weapons_from(actor.switchweapon);
746
747                                 // the two weapon entities will notice this has changed and update their models
748                                 actor.weapon = actor.switchweapon;
749                                 actor.weaponname = newwep.mdl;
750                                 actor.bulletcounter = 0;
751                                 actor.ammo_field = newwep.ammo_field;
752                                 newwep.wr_setup(newwep);
753                                 this.state = WS_RAISE;
754
755                                 // set our clip load to the load of the weapon we switched to, if it's reloadable
756                                 if ((newwep.spawnflags & WEP_FLAG_RELOADABLE) && newwep.reloading_ammo)  // prevent accessing undefined cvars
757                                 {
758                                         actor.clip_load = actor.(weapon_load[actor.switchweapon]);
759                                         actor.clip_size = newwep.reloading_ammo;
760                                 }
761                                 else
762                                 {
763                                         actor.clip_load = actor.clip_size = 0;
764                                 }
765
766                                 weapon_thinkf(actor, weaponentity, WFRAME_IDLE, newwep.switchdelay_raise, w_ready);
767                                 break;
768                         }
769                         case WS_DROP:
770                         {
771                                 // in dropping phase we can switch at any time
772                                 actor.switchingweapon = actor.switchweapon;
773                                 break;
774                         }
775                         case WS_READY:
776                         {
777                                 // start switching!
778                                 actor.switchingweapon = actor.switchweapon;
779                                 entity oldwep = Weapons_from(actor.weapon);
780
781                                 // set up weapon switch think in the future, and start drop anim
782                                 if (
783 #if INDEPENDENT_ATTACK_FINISHED
784                                             true
785 #else
786                                             ATTACK_FINISHED(actor, slot) <= time + actor.weapon_frametime * 0.5
787 #endif
788                                    )
789                                 {
790                                         sound(actor, CH_WEAPON_SINGLE, SND_WEAPON_SWITCH, VOL_BASE, ATTN_NORM);
791                                         this.state = WS_DROP;
792                                         weapon_thinkf(actor, weaponentity, WFRAME_DONTCHANGE, oldwep.switchdelay_drop, w_clear);
793                                 }
794                                 break;
795                         }
796                 }
797         }
798
799         // LordHavoc: network timing test code
800         // if (actor.button0)
801         //      print(ftos(frametime), " ", ftos(time), " >= ", ftos(ATTACK_FINISHED(actor, slot)), " >= ", ftos(this.weapon_nextthink), "\n");
802
803         int w = actor.weapon;
804
805         // call the think code which may fire the weapon
806         // and do so multiple times to resolve framerate dependency issues if the
807         // server framerate is very low and the weapon fire rate very high
808         for (int c = 0; c < W_TICSPERFRAME; ++c)
809         {
810                 if (w && !(actor.weapons & WepSet_FromWeapon(w)))
811                 {
812                         if (actor.weapon == actor.switchweapon) W_SwitchWeapon_Force(actor, w_getbestweapon(actor));
813                         w = 0;
814                 }
815
816                 v_forward = fo;
817                 v_right = ri;
818                 v_up = up;
819
820                 bool block_weapon = false;
821                 {
822                         bool key_pressed = actor.BUTTON_HOOK && !actor.vehicle;
823                         Weapon off = actor.offhand;
824                         if (off && !(actor.weapons & WEPSET(HOOK)))
825                         {
826                                 if (off.offhand_think) off.offhand_think(off, actor, key_pressed);
827                         }
828                         else
829                         {
830                                 if (key_pressed && actor.switchweapon != WEP_HOOK.m_id && !actor.hook_switchweapon) W_SwitchWeapon(
831                                                 WEP_HOOK.m_id);
832                                 actor.hook_switchweapon = key_pressed;
833                                 Weapon h = WEP_HOOK;
834                                 block_weapon = (actor.weapon == h.m_id && (actor.BUTTON_ATCK || key_pressed));
835                                 h.wr_think(h, actor, weaponentity, block_weapon ? 1 : 0);
836                         }
837                 }
838
839                 v_forward = fo;
840                 v_right = ri;
841                 v_up = up;
842
843                 if (!block_weapon)
844                 {
845                         if (w)
846                         {
847                                 Weapon e = Weapons_from(actor.weapon);
848                                 e.wr_think(e, actor, weaponentity, (actor.BUTTON_ATCK ? 1 : 0) | (actor.BUTTON_ATCK2 ? 2 : 0));
849                         }
850                         else
851                         {
852                                 Weapon w = Weapons_from(actor.weapon);
853                                 w.wr_gonethink(w);
854                         }
855                 }
856
857                 if (time + actor.weapon_frametime * 0.5 >= this.weapon_nextthink)
858                 {
859                         if (this.weapon_think)
860                         {
861                                 v_forward = fo;
862                                 v_right = ri;
863                                 v_up = up;
864                                 Weapon wpn = Weapons_from(actor.weapon);
865                                 this.weapon_think(wpn, actor, weaponentity,
866                                         (actor.BUTTON_ATCK ? 1 : 0) | (actor.BUTTON_ATCK2 ? 2 : 0));
867                         }
868                         else
869                         {
870                                 bprint("\{1}^1ERROR: undefined weapon think function for ", actor.netname, "\n");
871                         }
872                 }
873         }
874 }
875
876 void W_AttachToShotorg(entity actor, entity flash, vector offset)
877 {
878         .entity weaponentity = weaponentities[0];
879         flash.owner = actor;
880         flash.angles_z = random() * 360;
881
882         entity this = actor.(weaponentity);
883         if (gettagindex(this, "shot")) setattachment(flash, this, "shot");
884         else setattachment(flash, this, "tag_shot");
885         setorigin(flash, offset);
886
887         entity xflash = spawn();
888         copyentity(flash, xflash);
889
890         flash.viewmodelforclient = actor;
891
892         if (this.oldorigin.x > 0)
893         {
894                 setattachment(xflash, actor.exteriorweaponentity, "");
895                 setorigin(xflash, this.oldorigin + offset);
896         }
897         else
898         {
899                 if (gettagindex(actor.exteriorweaponentity, "shot")) setattachment(xflash, actor.exteriorweaponentity, "shot");
900                 else setattachment(xflash, actor.exteriorweaponentity, "tag_shot");
901                 setorigin(xflash, offset);
902         }
903 }
904
905 void W_DecreaseAmmo(Weapon wep, entity actor, float ammo_use)
906 {
907         if (cvar("g_overkill"))
908         {
909                 if (actor.ok_use_ammocharge)
910                 {
911                         ok_DecreaseCharge(actor, actor.weapon);
912                         return;  // TODO
913                 }
914         }
915
916         if ((actor.items & IT_UNLIMITED_WEAPON_AMMO) && !wep.reloading_ammo) return;
917
918         // if this weapon is reloadable, decrease its load. Else decrease the player's ammo
919         if (wep.reloading_ammo)
920         {
921                 actor.clip_load -= ammo_use;
922                 actor.(weapon_load[actor.weapon]) = actor.clip_load;
923         }
924         else if (wep.ammo_field != ammo_none)
925         {
926                 actor.(wep.ammo_field) -= ammo_use;
927                 if (actor.(wep.ammo_field) < 0)
928                 {
929                         backtrace(sprintf(
930                                 "W_DecreaseAmmo(%.2f): '%s' subtracted too much %s from '%s', resulting with '%.2f' left... "
931                                 "Please notify Samual immediately with a copy of this backtrace!\n",
932                                 ammo_use,
933                                 wep.netname,
934                                 GetAmmoPicture(wep.ammo_field),
935                                 actor.netname,
936                                 actor.(wep.ammo_field)
937                                              ));
938                 }
939         }
940 }
941
942 // weapon reloading code
943
944 .float reload_ammo_amount, reload_ammo_min, reload_time;
945 .float reload_complain;
946 .string reload_sound;
947
948 void W_ReloadedAndReady(Weapon thiswep, entity actor, .entity weaponentity, int fire)
949 {
950         // finish the reloading process, and do the ammo transfer
951
952         actor.clip_load = actor.old_clip_load;  // restore the ammo counter, in case we still had ammo in the weapon before reloading
953
954         // if the gun uses no ammo, max out weapon load, else decrease ammo as we increase weapon load
955         if (!actor.reload_ammo_min || actor.items & IT_UNLIMITED_WEAPON_AMMO || actor.ammo_field == ammo_none)
956         {
957                 actor.clip_load = actor.reload_ammo_amount;
958         }
959         else
960         {
961                 // make sure we don't add more ammo than we have
962                 float load = min(actor.reload_ammo_amount - actor.clip_load, actor.(actor.ammo_field));
963                 actor.clip_load += load;
964                 actor.(actor.ammo_field) -= load;
965         }
966         actor.(weapon_load[actor.weapon]) = actor.clip_load;
967
968         // do not set ATTACK_FINISHED in reload code any more. This causes annoying delays if eg: You start reloading a weapon,
969         // then quickly switch to another weapon and back. Reloading is canceled, but the reload delay is still there,
970         // so your weapon is disabled for a few seconds without reason
971
972         // ATTACK_FINISHED(actor, slot) -= actor.reload_time - 1;
973
974         Weapon wpn = Weapons_from(actor.weapon);
975         w_ready(wpn, actor, weaponentity, (actor.BUTTON_ATCK ? 1 : 0) | (actor.BUTTON_ATCK2 ? 2 : 0));
976 }
977
978 void W_Reload(entity actor, float sent_ammo_min, string sent_sound)
979 {
980         .entity weaponentity = weaponentities[0];
981         // set global values to work with
982         entity e = Weapons_from(actor.weapon);
983
984         if (cvar("g_overkill"))
985                 if (actor.ok_use_ammocharge) return;
986         // TODO
987
988         actor.reload_ammo_min = sent_ammo_min;
989         actor.reload_ammo_amount = e.reloading_ammo;
990         actor.reload_time = e.reloading_time;
991         actor.reload_sound = sent_sound;
992
993         // don't reload weapons that don't have the RELOADABLE flag
994         if (!(e.spawnflags & WEP_FLAG_RELOADABLE))
995         {
996                 LOG_TRACE(
997                         "Warning: Attempted to reload a weapon that does not have the WEP_FLAG_RELOADABLE flag. Fix your code!\n");
998                 return;
999         }
1000
1001         // return if reloading is disabled for this weapon
1002         if (!actor.reload_ammo_amount) return;
1003
1004         // our weapon is fully loaded, no need to reload
1005         if (actor.clip_load >= actor.reload_ammo_amount) return;
1006
1007         // no ammo, so nothing to load
1008         if (actor.ammo_field != ammo_none)
1009         {
1010                 if (!actor.(actor.ammo_field) && actor.reload_ammo_min)
1011                 {
1012                         if (!(actor.items & IT_UNLIMITED_WEAPON_AMMO))
1013                         {
1014                                 if (IS_REAL_CLIENT(actor) && actor.reload_complain < time)
1015                                 {
1016                                         play2(actor, SND(UNAVAILABLE));
1017                                         sprint(actor, strcat("You don't have enough ammo to reload the ^2", WEP_NAME(actor.weapon), "\n"));
1018                                         actor.reload_complain = time + 1;
1019                                 }
1020                                 // switch away if the amount of ammo is not enough to keep using this weapon
1021                                 Weapon w = Weapons_from(actor.weapon);
1022                                 if (!(w.wr_checkammo1(w) + w.wr_checkammo2(w)))
1023                                 {
1024                                         actor.clip_load = -1;  // reload later
1025                                         W_SwitchToOtherWeapon(actor);
1026                                 }
1027                                 return;
1028                         }
1029                 }
1030         }
1031
1032         entity this = actor.(weaponentity);
1033         if (this)
1034         {
1035                 if (this.wframe == WFRAME_RELOAD) return;
1036
1037                 // allow switching away while reloading, but this will cause a new reload!
1038                 this.state = WS_READY;
1039         }
1040
1041         // now begin the reloading process
1042
1043         _sound(actor, CH_WEAPON_SINGLE, actor.reload_sound, VOL_BASE, ATTEN_NORM);
1044
1045         // do not set ATTACK_FINISHED in reload code any more. This causes annoying delays if eg: You start reloading a weapon,
1046         // then quickly switch to another weapon and back. Reloading is canceled, but the reload delay is still there,
1047         // so your weapon is disabled for a few seconds without reason
1048
1049         // ATTACK_FINISHED(actor, slot) = max(time, ATTACK_FINISHED(actor, slot)) + actor.reload_time + 1;
1050
1051         weapon_thinkf(actor, weaponentity, WFRAME_RELOAD, actor.reload_time, W_ReloadedAndReady);
1052
1053         if (actor.clip_load < 0) actor.clip_load = 0;
1054         actor.old_clip_load = actor.clip_load;
1055         actor.clip_load = actor.(weapon_load[actor.weapon]) = -1;
1056 }
1057
1058 void W_DropEvent(.void(Weapon) event, entity player, float weapon_type, entity weapon_item)
1059 {
1060         Weapon w = Weapons_from(weapon_type);
1061         weapon_dropevent_item = weapon_item;
1062         WITH(entity, self, player, w.event(w));
1063 }