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