Fix MSVC++ 2015 warnings about variable scope and some narrowing conversions without...
[xonotic/darkplaces.git] / cl_input.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cl.input.c  -- builds an intended movement command to send to the server
21
22 // Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All
23 // rights reserved.
24
25 #include "quakedef.h"
26 #include "csprogs.h"
27 #include "thread.h"
28
29 /*
30 ===============================================================================
31
32 KEY BUTTONS
33
34 Continuous button event tracking is complicated by the fact that two different
35 input sources (say, mouse button 1 and the control key) can both press the
36 same button, but the button should only be released when both of the
37 pressing key have been released.
38
39 When a key event issues a button command (+forward, +attack, etc), it appends
40 its key number as a parameter to the command so it can be matched up with
41 the release.
42
43 state bit 0 is the current state of the key
44 state bit 1 is edge triggered on the up to down transition
45 state bit 2 is edge triggered on the down to up transition
46
47 ===============================================================================
48 */
49
50
51 kbutton_t       in_mlook, in_klook;
52 kbutton_t       in_left, in_right, in_forward, in_back;
53 kbutton_t       in_lookup, in_lookdown, in_moveleft, in_moveright;
54 kbutton_t       in_strafe, in_speed, in_jump, in_attack, in_use;
55 kbutton_t       in_up, in_down;
56 // LordHavoc: added 6 new buttons
57 kbutton_t       in_button3, in_button4, in_button5, in_button6, in_button7, in_button8;
58 //even more
59 kbutton_t       in_button9, in_button10, in_button11, in_button12, in_button13, in_button14, in_button15, in_button16;
60
61 int                     in_impulse;
62
63
64
65 static void KeyDown (kbutton_t *b)
66 {
67         int k;
68         const char *c;
69
70         c = Cmd_Argv(1);
71         if (c[0])
72                 k = atoi(c);
73         else
74                 k = -1;         // typed manually at the console for continuous down
75
76         if (k == b->down[0] || k == b->down[1])
77                 return;         // repeating key
78
79         if (!b->down[0])
80                 b->down[0] = k;
81         else if (!b->down[1])
82                 b->down[1] = k;
83         else
84         {
85                 Con_Print("Three keys down for a button!\n");
86                 return;
87         }
88
89         if (b->state & 1)
90                 return;         // still down
91         b->state |= 1 + 2;      // down + impulse down
92 }
93
94 static void KeyUp (kbutton_t *b)
95 {
96         int k;
97         const char *c;
98
99         c = Cmd_Argv(1);
100         if (c[0])
101                 k = atoi(c);
102         else
103         { // typed manually at the console, assume for unsticking, so clear all
104                 b->down[0] = b->down[1] = 0;
105                 b->state = 4;   // impulse up
106                 return;
107         }
108
109         if (b->down[0] == k)
110                 b->down[0] = 0;
111         else if (b->down[1] == k)
112                 b->down[1] = 0;
113         else
114                 return;         // key up without coresponding down (menu pass through)
115         if (b->down[0] || b->down[1])
116                 return;         // some other key is still holding it down
117
118         if (!(b->state & 1))
119                 return;         // still up (this should not happen)
120         b->state &= ~1;         // now up
121         b->state |= 4;          // impulse up
122 }
123
124 static void IN_KLookDown (void) {KeyDown(&in_klook);}
125 static void IN_KLookUp (void) {KeyUp(&in_klook);}
126 static void IN_MLookDown (void) {KeyDown(&in_mlook);}
127 static void IN_MLookUp (void)
128 {
129         KeyUp(&in_mlook);
130         if ( !(in_mlook.state&1) && lookspring.value)
131                 V_StartPitchDrift();
132 }
133 static void IN_UpDown(void) {KeyDown(&in_up);}
134 static void IN_UpUp(void) {KeyUp(&in_up);}
135 static void IN_DownDown(void) {KeyDown(&in_down);}
136 static void IN_DownUp(void) {KeyUp(&in_down);}
137 static void IN_LeftDown(void) {KeyDown(&in_left);}
138 static void IN_LeftUp(void) {KeyUp(&in_left);}
139 static void IN_RightDown(void) {KeyDown(&in_right);}
140 static void IN_RightUp(void) {KeyUp(&in_right);}
141 static void IN_ForwardDown(void) {KeyDown(&in_forward);}
142 static void IN_ForwardUp(void) {KeyUp(&in_forward);}
143 static void IN_BackDown(void) {KeyDown(&in_back);}
144 static void IN_BackUp(void) {KeyUp(&in_back);}
145 static void IN_LookupDown(void) {KeyDown(&in_lookup);}
146 static void IN_LookupUp(void) {KeyUp(&in_lookup);}
147 static void IN_LookdownDown(void) {KeyDown(&in_lookdown);}
148 static void IN_LookdownUp(void) {KeyUp(&in_lookdown);}
149 static void IN_MoveleftDown(void) {KeyDown(&in_moveleft);}
150 static void IN_MoveleftUp(void) {KeyUp(&in_moveleft);}
151 static void IN_MoverightDown(void) {KeyDown(&in_moveright);}
152 static void IN_MoverightUp(void) {KeyUp(&in_moveright);}
153
154 static void IN_SpeedDown(void) {KeyDown(&in_speed);}
155 static void IN_SpeedUp(void) {KeyUp(&in_speed);}
156 static void IN_StrafeDown(void) {KeyDown(&in_strafe);}
157 static void IN_StrafeUp(void) {KeyUp(&in_strafe);}
158
159 static void IN_AttackDown(void) {KeyDown(&in_attack);}
160 static void IN_AttackUp(void) {KeyUp(&in_attack);}
161
162 static void IN_UseDown(void) {KeyDown(&in_use);}
163 static void IN_UseUp(void) {KeyUp(&in_use);}
164
165 // LordHavoc: added 6 new buttons
166 static void IN_Button3Down(void) {KeyDown(&in_button3);}
167 static void IN_Button3Up(void) {KeyUp(&in_button3);}
168 static void IN_Button4Down(void) {KeyDown(&in_button4);}
169 static void IN_Button4Up(void) {KeyUp(&in_button4);}
170 static void IN_Button5Down(void) {KeyDown(&in_button5);}
171 static void IN_Button5Up(void) {KeyUp(&in_button5);}
172 static void IN_Button6Down(void) {KeyDown(&in_button6);}
173 static void IN_Button6Up(void) {KeyUp(&in_button6);}
174 static void IN_Button7Down(void) {KeyDown(&in_button7);}
175 static void IN_Button7Up(void) {KeyUp(&in_button7);}
176 static void IN_Button8Down(void) {KeyDown(&in_button8);}
177 static void IN_Button8Up(void) {KeyUp(&in_button8);}
178
179 static void IN_Button9Down(void) {KeyDown(&in_button9);}
180 static void IN_Button9Up(void) {KeyUp(&in_button9);}
181 static void IN_Button10Down(void) {KeyDown(&in_button10);}
182 static void IN_Button10Up(void) {KeyUp(&in_button10);}
183 static void IN_Button11Down(void) {KeyDown(&in_button11);}
184 static void IN_Button11Up(void) {KeyUp(&in_button11);}
185 static void IN_Button12Down(void) {KeyDown(&in_button12);}
186 static void IN_Button12Up(void) {KeyUp(&in_button12);}
187 static void IN_Button13Down(void) {KeyDown(&in_button13);}
188 static void IN_Button13Up(void) {KeyUp(&in_button13);}
189 static void IN_Button14Down(void) {KeyDown(&in_button14);}
190 static void IN_Button14Up(void) {KeyUp(&in_button14);}
191 static void IN_Button15Down(void) {KeyDown(&in_button15);}
192 static void IN_Button15Up(void) {KeyUp(&in_button15);}
193 static void IN_Button16Down(void) {KeyDown(&in_button16);}
194 static void IN_Button16Up(void) {KeyUp(&in_button16);}
195
196 static void IN_JumpDown (void) {KeyDown(&in_jump);}
197 static void IN_JumpUp (void) {KeyUp(&in_jump);}
198
199 static void IN_Impulse (void) {in_impulse=atoi(Cmd_Argv(1));}
200
201 in_bestweapon_info_t in_bestweapon_info[IN_BESTWEAPON_MAX];
202
203 static void IN_BestWeapon_Register(const char *name, int impulse, int weaponbit, int activeweaponcode, int ammostat, int ammomin)
204 {
205         int i;
206         for(i = 0; i < IN_BESTWEAPON_MAX && in_bestweapon_info[i].impulse; ++i)
207                 if(in_bestweapon_info[i].impulse == impulse)
208                         break;
209         if(i >= IN_BESTWEAPON_MAX)
210         {
211                 Con_Printf("no slot left for weapon definition; increase IN_BESTWEAPON_MAX\n");
212                 return; // sorry
213         }
214         strlcpy(in_bestweapon_info[i].name, name, sizeof(in_bestweapon_info[i].name));
215         in_bestweapon_info[i].impulse = impulse;
216         if(weaponbit != -1)
217                 in_bestweapon_info[i].weaponbit = weaponbit;
218         if(activeweaponcode != -1)
219                 in_bestweapon_info[i].activeweaponcode = activeweaponcode;
220         if(ammostat != -1)
221                 in_bestweapon_info[i].ammostat = ammostat;
222         if(ammomin != -1)
223                 in_bestweapon_info[i].ammomin = ammomin;
224 }
225
226 void IN_BestWeapon_ResetData (void)
227 {
228         memset(in_bestweapon_info, 0, sizeof(in_bestweapon_info));
229         IN_BestWeapon_Register("1", 1, IT_AXE, IT_AXE, STAT_SHELLS, 0);
230         IN_BestWeapon_Register("2", 2, IT_SHOTGUN, IT_SHOTGUN, STAT_SHELLS, 1);
231         IN_BestWeapon_Register("3", 3, IT_SUPER_SHOTGUN, IT_SUPER_SHOTGUN, STAT_SHELLS, 1);
232         IN_BestWeapon_Register("4", 4, IT_NAILGUN, IT_NAILGUN, STAT_NAILS, 1);
233         IN_BestWeapon_Register("5", 5, IT_SUPER_NAILGUN, IT_SUPER_NAILGUN, STAT_NAILS, 1);
234         IN_BestWeapon_Register("6", 6, IT_GRENADE_LAUNCHER, IT_GRENADE_LAUNCHER, STAT_ROCKETS, 1);
235         IN_BestWeapon_Register("7", 7, IT_ROCKET_LAUNCHER, IT_ROCKET_LAUNCHER, STAT_ROCKETS, 1);
236         IN_BestWeapon_Register("8", 8, IT_LIGHTNING, IT_LIGHTNING, STAT_CELLS, 1);
237         IN_BestWeapon_Register("9", 9, 128, 128, STAT_CELLS, 1); // generic energy weapon for mods
238         IN_BestWeapon_Register("p", 209, 128, 128, STAT_CELLS, 1); // dpmod plasma gun
239         IN_BestWeapon_Register("w", 210, 8388608, 8388608, STAT_CELLS, 1); // dpmod plasma wave cannon
240         IN_BestWeapon_Register("l", 225, HIT_LASER_CANNON, HIT_LASER_CANNON, STAT_CELLS, 1); // hipnotic laser cannon
241         IN_BestWeapon_Register("h", 226, HIT_MJOLNIR, HIT_MJOLNIR, STAT_CELLS, 0); // hipnotic mjolnir hammer
242 }
243
244 static void IN_BestWeapon_Register_f (void)
245 {
246         if(Cmd_Argc() == 7)
247         {
248                 IN_BestWeapon_Register(
249                         Cmd_Argv(1),
250                         atoi(Cmd_Argv(2)),
251                         atoi(Cmd_Argv(3)),
252                         atoi(Cmd_Argv(4)),
253                         atoi(Cmd_Argv(5)),
254                         atoi(Cmd_Argv(6))
255                 );
256         }
257         else if(Cmd_Argc() == 2 && !strcmp(Cmd_Argv(1), "clear"))
258         {
259                 memset(in_bestweapon_info, 0, sizeof(in_bestweapon_info));
260         }
261         else if(Cmd_Argc() == 2 && !strcmp(Cmd_Argv(1), "quake"))
262         {
263                 IN_BestWeapon_ResetData();
264         }
265         else
266         {
267                 Con_Printf("Usage: %s weaponshortname impulse itemcode activeweaponcode ammostat ammomin; %s clear; %s quake\n", Cmd_Argv(0), Cmd_Argv(0), Cmd_Argv(0));
268         }
269 }
270
271 static void IN_BestWeapon (void)
272 {
273         int i, n;
274         const char *t;
275         if (Cmd_Argc() < 2)
276         {
277                 Con_Printf("bestweapon requires 1 or more parameters\n");
278                 return;
279         }
280         for (i = 1;i < Cmd_Argc();i++)
281         {
282                 t = Cmd_Argv(i);
283                 // figure out which weapon this character refers to
284                 for (n = 0;n < IN_BESTWEAPON_MAX && in_bestweapon_info[n].impulse;n++)
285                 {
286                         if (!strcmp(in_bestweapon_info[n].name, t))
287                         {
288                                 // we found out what weapon this character refers to
289                                 // check if the inventory contains the weapon and enough ammo
290                                 if ((cl.stats[STAT_ITEMS] & in_bestweapon_info[n].weaponbit) && (cl.stats[in_bestweapon_info[n].ammostat] >= in_bestweapon_info[n].ammomin))
291                                 {
292                                         // we found one of the weapons the player wanted
293                                         // send an impulse to switch to it
294                                         in_impulse = in_bestweapon_info[n].impulse;
295                                         return;
296                                 }
297                                 break;
298                         }
299                 }
300                 // if we couldn't identify the weapon we just ignore it and continue checking for other weapons
301         }
302         // if we couldn't find any of the weapons, there's nothing more we can do...
303 }
304
305 #if 0
306 void IN_CycleWeapon (void)
307 {
308         int i, n;
309         int first = -1;
310         qboolean found = false;
311         const char *t;
312         if (Cmd_Argc() < 2)
313         {
314                 Con_Printf("bestweapon requires 1 or more parameters\n");
315                 return;
316         }
317         for (i = 1;i < Cmd_Argc();i++)
318         {
319                 t = Cmd_Argv(i);
320                 // figure out which weapon this character refers to
321                 for (n = 0;n < IN_BESTWEAPON_MAX && in_bestweapon_info[n].impulse;n++)
322                 {
323                         if (!strcmp(in_bestweapon_info[n].name, t))
324                         {
325                                 // we found out what weapon this character refers to
326                                 // check if the inventory contains the weapon and enough ammo
327                                 if ((cl.stats[STAT_ITEMS] & in_bestweapon_info[n].weaponbit) && (cl.stats[in_bestweapon_info[n].ammostat] >= in_bestweapon_info[n].ammomin))
328                                 {
329                                         // we found one of the weapons the player wanted
330                                         if(first == -1)
331                                                 first = n;
332                                         if(found)
333                                         {
334                                                 in_impulse = in_bestweapon_info[n].impulse;
335                                                 return;
336                                         }
337                                         if(cl.stats[STAT_ACTIVEWEAPON] == in_bestweapon_info[n].activeweaponcode)
338                                                 found = true;
339                                 }
340                                 break;
341                         }
342                 }
343                 // if we couldn't identify the weapon we just ignore it and continue checking for other weapons
344         }
345         if(first != -1)
346         {
347                 in_impulse = in_bestweapon_info[first].impulse;
348                 return;
349         }
350         // if we couldn't find any of the weapons, there's nothing more we can do...
351 }
352 #endif
353
354 /*
355 ===============
356 CL_KeyState
357
358 Returns 0.25 if a key was pressed and released during the frame,
359 0.5 if it was pressed and held
360 0 if held then released, and
361 1.0 if held for the entire time
362 ===============
363 */
364 float CL_KeyState (kbutton_t *key)
365 {
366         float           val;
367         qboolean        impulsedown, impulseup, down;
368
369         impulsedown = (key->state & 2) != 0;
370         impulseup = (key->state & 4) != 0;
371         down = (key->state & 1) != 0;
372         val = 0;
373
374         if (impulsedown && !impulseup)
375         {
376                 if (down)
377                         val = 0.5;      // pressed and held this frame
378                 else
379                         val = 0;        //      I_Error ();
380         }
381         if (impulseup && !impulsedown)
382         {
383                 if (down)
384                         val = 0;        //      I_Error ();
385                 else
386                         val = 0;        // released this frame
387         }
388         if (!impulsedown && !impulseup)
389         {
390                 if (down)
391                         val = 1.0;      // held the entire frame
392                 else
393                         val = 0;        // up the entire frame
394         }
395         if (impulsedown && impulseup)
396         {
397                 if (down)
398                         val = 0.75;     // released and re-pressed this frame
399                 else
400                         val = 0.25;     // pressed and released this frame
401         }
402
403         key->state &= 1;                // clear impulses
404
405         return val;
406 }
407
408
409
410
411 //==========================================================================
412
413 cvar_t cl_upspeed = {CVAR_SAVE, "cl_upspeed","400","vertical movement speed (while swimming or flying)"};
414 cvar_t cl_forwardspeed = {CVAR_SAVE, "cl_forwardspeed","400","forward movement speed"};
415 cvar_t cl_backspeed = {CVAR_SAVE, "cl_backspeed","400","backward movement speed"};
416 cvar_t cl_sidespeed = {CVAR_SAVE, "cl_sidespeed","350","strafe movement speed"};
417
418 cvar_t cl_movespeedkey = {CVAR_SAVE, "cl_movespeedkey","2.0","how much +speed multiplies keyboard movement speed"};
419 cvar_t cl_movecliptokeyboard = {0, "cl_movecliptokeyboard", "0", "if set to 1, any move is clipped to the nine keyboard states; if set to 2, only the direction is clipped, not the amount"};
420
421 cvar_t cl_yawspeed = {CVAR_SAVE, "cl_yawspeed","140","keyboard yaw turning speed"};
422 cvar_t cl_pitchspeed = {CVAR_SAVE, "cl_pitchspeed","150","keyboard pitch turning speed"};
423
424 cvar_t cl_anglespeedkey = {CVAR_SAVE, "cl_anglespeedkey","1.5","how much +speed multiplies keyboard turning speed"};
425
426 cvar_t cl_movement = {CVAR_SAVE, "cl_movement", "0", "enables clientside prediction of your player movement"};
427 cvar_t cl_movement_replay = {0, "cl_movement_replay", "1", "use engine prediction"};
428 cvar_t cl_movement_nettimeout = {CVAR_SAVE, "cl_movement_nettimeout", "0.3", "stops predicting moves when server is lagging badly (avoids major performance problems), timeout in seconds"};
429 cvar_t cl_movement_minping = {CVAR_SAVE, "cl_movement_minping", "0", "whether to use prediction when ping is lower than this value in milliseconds"};
430 cvar_t cl_movement_track_canjump = {CVAR_SAVE, "cl_movement_track_canjump", "1", "track if the player released the jump key between two jumps to decide if he is able to jump or not; when off, this causes some \"sliding\" slightly above the floor when the jump key is held too long; if the mod allows repeated jumping by holding space all the time, this has to be set to zero too"};
431 cvar_t cl_movement_maxspeed = {0, "cl_movement_maxspeed", "320", "how fast you can move (should match sv_maxspeed)"};
432 cvar_t cl_movement_maxairspeed = {0, "cl_movement_maxairspeed", "30", "how fast you can move while in the air (should match sv_maxairspeed)"};
433 cvar_t cl_movement_stopspeed = {0, "cl_movement_stopspeed", "100", "speed below which you will be slowed rapidly to a stop rather than sliding endlessly (should match sv_stopspeed)"};
434 cvar_t cl_movement_friction = {0, "cl_movement_friction", "4", "how fast you slow down (should match sv_friction)"};
435 cvar_t cl_movement_wallfriction = {0, "cl_movement_wallfriction", "1", "how fast you slow down while sliding along a wall (should match sv_wallfriction)"};
436 cvar_t cl_movement_waterfriction = {0, "cl_movement_waterfriction", "-1", "how fast you slow down (should match sv_waterfriction), if less than 0 the cl_movement_friction variable is used instead"};
437 cvar_t cl_movement_edgefriction = {0, "cl_movement_edgefriction", "1", "how much to slow down when you may be about to fall off a ledge (should match edgefriction)"};
438 cvar_t cl_movement_stepheight = {0, "cl_movement_stepheight", "18", "how tall a step you can step in one instant (should match sv_stepheight)"};
439 cvar_t cl_movement_accelerate = {0, "cl_movement_accelerate", "10", "how fast you accelerate (should match sv_accelerate)"};
440 cvar_t cl_movement_airaccelerate = {0, "cl_movement_airaccelerate", "-1", "how fast you accelerate while in the air (should match sv_airaccelerate), if less than 0 the cl_movement_accelerate variable is used instead"};
441 cvar_t cl_movement_wateraccelerate = {0, "cl_movement_wateraccelerate", "-1", "how fast you accelerate while in water (should match sv_wateraccelerate), if less than 0 the cl_movement_accelerate variable is used instead"};
442 cvar_t cl_movement_jumpvelocity = {0, "cl_movement_jumpvelocity", "270", "how fast you move upward when you begin a jump (should match the quakec code)"};
443 cvar_t cl_movement_airaccel_qw = {0, "cl_movement_airaccel_qw", "1", "ratio of QW-style air control as opposed to simple acceleration (reduces speed gain when zigzagging) (should match sv_airaccel_qw); when < 0, the speed is clamped against the maximum allowed forward speed after the move"};
444 cvar_t cl_movement_airaccel_sideways_friction = {0, "cl_movement_airaccel_sideways_friction", "0", "anti-sideways movement stabilization (should match sv_airaccel_sideways_friction); when < 0, only so much friction is applied that braking (by accelerating backwards) cannot be stronger"};
445
446 cvar_t in_pitch_min = {0, "in_pitch_min", "-90", "how far you can aim upward (quake used -70)"};
447 cvar_t in_pitch_max = {0, "in_pitch_max", "90", "how far you can aim downward (quake used 80)"};
448
449 cvar_t m_filter = {CVAR_SAVE, "m_filter","0", "smoothes mouse movement, less responsive but smoother aiming"};
450 cvar_t m_accelerate = {CVAR_SAVE, "m_accelerate","1", "mouse acceleration factor (try 2)"};
451 cvar_t m_accelerate_minspeed = {CVAR_SAVE, "m_accelerate_minspeed","5000", "below this speed, no acceleration is done"};
452 cvar_t m_accelerate_maxspeed = {CVAR_SAVE, "m_accelerate_maxspeed","10000", "above this speed, full acceleration is done"};
453 cvar_t m_accelerate_filter = {CVAR_SAVE, "m_accelerate_filter","0.1", "mouse acceleration factor filtering"};
454
455 cvar_t cl_netfps = {CVAR_SAVE, "cl_netfps","72", "how many input packets to send to server each second"};
456 cvar_t cl_netrepeatinput = {CVAR_SAVE, "cl_netrepeatinput", "1", "how many packets in a row can be lost without movement issues when using cl_movement (technically how many input messages to repeat in each packet that have not yet been acknowledged by the server), only affects DP7 and later servers (Quake uses 0, QuakeWorld uses 2, and just for comparison Quake3 uses 1)"};
457 cvar_t cl_netimmediatebuttons = {CVAR_SAVE, "cl_netimmediatebuttons", "1", "sends extra packets whenever your buttons change or an impulse is used (basically: whenever you click fire or change weapon)"};
458
459 cvar_t cl_nodelta = {0, "cl_nodelta", "0", "disables delta compression of non-player entities in QW network protocol"};
460
461 cvar_t cl_csqc_generatemousemoveevents = {0, "cl_csqc_generatemousemoveevents", "1", "enables calls to CSQC_InputEvent with type 2, for compliance with EXT_CSQC spec"};
462
463 extern cvar_t v_flipped;
464
465 /*
466 ================
467 CL_AdjustAngles
468
469 Moves the local angle positions
470 ================
471 */
472 static void CL_AdjustAngles (void)
473 {
474         float   speed;
475         float   up, down;
476
477         if (in_speed.state & 1)
478                 speed = cl.realframetime * cl_anglespeedkey.value;
479         else
480                 speed = cl.realframetime;
481
482         if (!(in_strafe.state & 1))
483         {
484                 cl.viewangles[YAW] -= speed*cl_yawspeed.value*CL_KeyState (&in_right);
485                 cl.viewangles[YAW] += speed*cl_yawspeed.value*CL_KeyState (&in_left);
486         }
487         if (in_klook.state & 1)
488         {
489                 V_StopPitchDrift ();
490                 cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * CL_KeyState (&in_forward);
491                 cl.viewangles[PITCH] += speed*cl_pitchspeed.value * CL_KeyState (&in_back);
492         }
493
494         up = CL_KeyState (&in_lookup);
495         down = CL_KeyState(&in_lookdown);
496
497         cl.viewangles[PITCH] -= speed*cl_pitchspeed.value * up;
498         cl.viewangles[PITCH] += speed*cl_pitchspeed.value * down;
499
500         if (up || down)
501                 V_StopPitchDrift ();
502
503         cl.viewangles[YAW] = ANGLEMOD(cl.viewangles[YAW]);
504         cl.viewangles[PITCH] = ANGLEMOD(cl.viewangles[PITCH]);
505         if (cl.viewangles[YAW] >= 180)
506                 cl.viewangles[YAW] -= 360;
507         if (cl.viewangles[PITCH] >= 180)
508                 cl.viewangles[PITCH] -= 360;
509         // TODO: honor serverinfo minpitch and maxpitch values in PROTOCOL_QUAKEWORLD
510         // TODO: honor proquake pq_fullpitch cvar when playing on proquake server (server stuffcmd's this to 0 usually)
511         cl.viewangles[PITCH] = bound(in_pitch_min.value, cl.viewangles[PITCH], in_pitch_max.value);
512         cl.viewangles[ROLL] = bound(-180, cl.viewangles[ROLL], 180);
513 }
514
515 int cl_ignoremousemoves = 2;
516
517 /*
518 ================
519 CL_Input
520
521 Send the intended movement message to the server
522 ================
523 */
524 void CL_Input (void)
525 {
526         float mx, my;
527         static float old_mouse_x = 0, old_mouse_y = 0;
528
529         // clamp before the move to prevent starting with bad angles
530         CL_AdjustAngles ();
531
532         if(v_flipped.integer)
533                 cl.viewangles[YAW] = -cl.viewangles[YAW];
534
535         // reset some of the command fields
536         cl.cmd.forwardmove = 0;
537         cl.cmd.sidemove = 0;
538         cl.cmd.upmove = 0;
539
540         // get basic movement from keyboard
541         if (in_strafe.state & 1)
542         {
543                 cl.cmd.sidemove += cl_sidespeed.value * CL_KeyState (&in_right);
544                 cl.cmd.sidemove -= cl_sidespeed.value * CL_KeyState (&in_left);
545         }
546
547         cl.cmd.sidemove += cl_sidespeed.value * CL_KeyState (&in_moveright);
548         cl.cmd.sidemove -= cl_sidespeed.value * CL_KeyState (&in_moveleft);
549
550         cl.cmd.upmove += cl_upspeed.value * CL_KeyState (&in_up);
551         cl.cmd.upmove -= cl_upspeed.value * CL_KeyState (&in_down);
552
553         if (! (in_klook.state & 1) )
554         {
555                 cl.cmd.forwardmove += cl_forwardspeed.value * CL_KeyState (&in_forward);
556                 cl.cmd.forwardmove -= cl_backspeed.value * CL_KeyState (&in_back);
557         }
558
559         // adjust for speed key
560         if (in_speed.state & 1)
561         {
562                 cl.cmd.forwardmove *= cl_movespeedkey.value;
563                 cl.cmd.sidemove *= cl_movespeedkey.value;
564                 cl.cmd.upmove *= cl_movespeedkey.value;
565         }
566
567         // allow mice or other external controllers to add to the move
568         IN_Move ();
569
570         // send mouse move to csqc
571         if (cl.csqc_loaded && cl_csqc_generatemousemoveevents.integer)
572         {
573                 if (cl.csqc_wantsmousemove)
574                 {
575                         // event type 3 is a DP_CSQC thing
576                         static int oldwindowmouse[2];
577                         if (oldwindowmouse[0] != in_windowmouse_x || oldwindowmouse[1] != in_windowmouse_y)
578                         {
579                                 CL_VM_InputEvent(3, in_windowmouse_x * vid_conwidth.value / vid.width, in_windowmouse_y * vid_conheight.value / vid.height);
580                                 oldwindowmouse[0] = in_windowmouse_x;
581                                 oldwindowmouse[1] = in_windowmouse_y;
582                         }
583                 }
584                 else
585                 {
586                         if (in_mouse_x || in_mouse_y)
587                                 CL_VM_InputEvent(2, in_mouse_x, in_mouse_y);
588                 }
589         }
590
591         // apply m_accelerate if it is on
592         if(m_accelerate.value > 1)
593         {
594                 static float averagespeed = 0;
595                 float speed, f, mi, ma;
596
597                 speed = sqrt(in_mouse_x * in_mouse_x + in_mouse_y * in_mouse_y) / cl.realframetime;
598                 if(m_accelerate_filter.value > 0)
599                         f = bound(0, cl.realframetime / m_accelerate_filter.value, 1);
600                 else
601                         f = 1;
602                 averagespeed = speed * f + averagespeed * (1 - f);
603
604                 mi = max(1, m_accelerate_minspeed.value);
605                 ma = max(m_accelerate_minspeed.value + 1, m_accelerate_maxspeed.value);
606
607                 if(averagespeed <= mi)
608                 {
609                         f = 1;
610                 }
611                 else if(averagespeed >= ma)
612                 {
613                         f = m_accelerate.value;
614                 }
615                 else
616                 {
617                         f = averagespeed;
618                         f = (f - mi) / (ma - mi) * (m_accelerate.value - 1) + 1;
619                 }
620
621                 in_mouse_x *= f;
622                 in_mouse_y *= f;
623         }
624
625         // apply m_filter if it is on
626         mx = in_mouse_x;
627         my = in_mouse_y;
628         if (m_filter.integer)
629         {
630                 in_mouse_x = (mx + old_mouse_x) * 0.5;
631                 in_mouse_y = (my + old_mouse_y) * 0.5;
632         }
633         old_mouse_x = mx;
634         old_mouse_y = my;
635
636         // ignore a mouse move if mouse was activated/deactivated this frame
637         if (cl_ignoremousemoves)
638         {
639                 cl_ignoremousemoves--;
640                 in_mouse_x = old_mouse_x = 0;
641                 in_mouse_y = old_mouse_y = 0;
642         }
643
644         // if not in menu, apply mouse move to viewangles/movement
645         if (!key_consoleactive && key_dest == key_game && !cl.csqc_wantsmousemove && cl_prydoncursor.integer <= 0)
646         {
647                 float modulatedsensitivity = sensitivity.value * cl.sensitivityscale;
648                 if (in_strafe.state & 1)
649                 {
650                         // strafing mode, all looking is movement
651                         V_StopPitchDrift();
652                         cl.cmd.sidemove += m_side.value * in_mouse_x * modulatedsensitivity;
653                         if (noclip_anglehack)
654                                 cl.cmd.upmove -= m_forward.value * in_mouse_y * modulatedsensitivity;
655                         else
656                                 cl.cmd.forwardmove -= m_forward.value * in_mouse_y * modulatedsensitivity;
657                 }
658                 else if ((in_mlook.state & 1) || freelook.integer)
659                 {
660                         // mouselook, lookstrafe causes turning to become strafing
661                         V_StopPitchDrift();
662                         if (lookstrafe.integer)
663                                 cl.cmd.sidemove += m_side.value * in_mouse_x * modulatedsensitivity;
664                         else
665                                 cl.viewangles[YAW] -= m_yaw.value * in_mouse_x * modulatedsensitivity * cl.viewzoom;
666                         cl.viewangles[PITCH] += m_pitch.value * in_mouse_y * modulatedsensitivity * cl.viewzoom;
667                 }
668                 else
669                 {
670                         // non-mouselook, yaw turning and forward/back movement
671                         cl.viewangles[YAW] -= m_yaw.value * in_mouse_x * modulatedsensitivity * cl.viewzoom;
672                         cl.cmd.forwardmove -= m_forward.value * in_mouse_y * modulatedsensitivity;
673                 }
674         }
675         else // don't pitch drift when csqc is controlling the mouse
676         {
677                 // mouse interacting with the scene, mostly stationary view
678                 V_StopPitchDrift();
679                 // update prydon cursor
680                 cl.cmd.cursor_screen[0] = in_windowmouse_x * 2.0 / vid.width - 1.0;
681                 cl.cmd.cursor_screen[1] = in_windowmouse_y * 2.0 / vid.height - 1.0;
682         }
683
684         if(v_flipped.integer)
685         {
686                 cl.viewangles[YAW] = -cl.viewangles[YAW];
687                 cl.cmd.sidemove = -cl.cmd.sidemove;
688         }
689
690         // clamp after the move to prevent rendering with bad angles
691         CL_AdjustAngles ();
692
693         if(cl_movecliptokeyboard.integer)
694         {
695                 vec_t f = 1;
696                 if (in_speed.state & 1)
697                         f *= cl_movespeedkey.value;
698                 if(cl_movecliptokeyboard.integer == 2)
699                 {
700                         // digital direction, analog amount
701                         vec_t wishvel_x, wishvel_y;
702                         wishvel_x = fabs(cl.cmd.forwardmove);
703                         wishvel_y = fabs(cl.cmd.sidemove);
704                         if(wishvel_x != 0 && wishvel_y != 0 && wishvel_x != wishvel_y)
705                         {
706                                 vec_t wishspeed = sqrt(wishvel_x * wishvel_x + wishvel_y * wishvel_y);
707                                 if(wishvel_x >= 2 * wishvel_y)
708                                 {
709                                         // pure X motion
710                                         if(cl.cmd.forwardmove > 0)
711                                                 cl.cmd.forwardmove = wishspeed;
712                                         else
713                                                 cl.cmd.forwardmove = -wishspeed;
714                                         cl.cmd.sidemove = 0;
715                                 }
716                                 else if(wishvel_y >= 2 * wishvel_x)
717                                 {
718                                         // pure Y motion
719                                         cl.cmd.forwardmove = 0;
720                                         if(cl.cmd.sidemove > 0)
721                                                 cl.cmd.sidemove = wishspeed;
722                                         else
723                                                 cl.cmd.sidemove = -wishspeed;
724                                 }
725                                 else
726                                 {
727                                         // diagonal
728                                         if(cl.cmd.forwardmove > 0)
729                                                 cl.cmd.forwardmove = 0.70710678118654752440 * wishspeed;
730                                         else
731                                                 cl.cmd.forwardmove = -0.70710678118654752440 * wishspeed;
732                                         if(cl.cmd.sidemove > 0)
733                                                 cl.cmd.sidemove = 0.70710678118654752440 * wishspeed;
734                                         else
735                                                 cl.cmd.sidemove = -0.70710678118654752440 * wishspeed;
736                                 }
737                         }
738                 }
739                 else if(cl_movecliptokeyboard.integer)
740                 {
741                         // digital direction, digital amount
742                         if(cl.cmd.sidemove >= cl_sidespeed.value * f * 0.5)
743                                 cl.cmd.sidemove = cl_sidespeed.value * f;
744                         else if(cl.cmd.sidemove <= -cl_sidespeed.value * f * 0.5)
745                                 cl.cmd.sidemove = -cl_sidespeed.value * f;
746                         else
747                                 cl.cmd.sidemove = 0;
748                         if(cl.cmd.forwardmove >= cl_forwardspeed.value * f * 0.5)
749                                 cl.cmd.forwardmove = cl_forwardspeed.value * f;
750                         else if(cl.cmd.forwardmove <= -cl_backspeed.value * f * 0.5)
751                                 cl.cmd.forwardmove = -cl_backspeed.value * f;
752                         else
753                                 cl.cmd.forwardmove = 0;
754                 }
755         }
756 }
757
758 #include "cl_collision.h"
759
760 static void CL_UpdatePrydonCursor(void)
761 {
762         vec3_t temp;
763
764         if (cl_prydoncursor.integer <= 0)
765                 VectorClear(cl.cmd.cursor_screen);
766
767         /*
768         if (cl.cmd.cursor_screen[0] < -1)
769         {
770                 cl.viewangles[YAW] -= m_yaw.value * (cl.cmd.cursor_screen[0] - -1) * vid.width * sensitivity.value * cl.viewzoom;
771                 cl.cmd.cursor_screen[0] = -1;
772         }
773         if (cl.cmd.cursor_screen[0] > 1)
774         {
775                 cl.viewangles[YAW] -= m_yaw.value * (cl.cmd.cursor_screen[0] - 1) * vid.width * sensitivity.value * cl.viewzoom;
776                 cl.cmd.cursor_screen[0] = 1;
777         }
778         if (cl.cmd.cursor_screen[1] < -1)
779         {
780                 cl.viewangles[PITCH] += m_pitch.value * (cl.cmd.cursor_screen[1] - -1) * vid.height * sensitivity.value * cl.viewzoom;
781                 cl.cmd.cursor_screen[1] = -1;
782         }
783         if (cl.cmd.cursor_screen[1] > 1)
784         {
785                 cl.viewangles[PITCH] += m_pitch.value * (cl.cmd.cursor_screen[1] - 1) * vid.height * sensitivity.value * cl.viewzoom;
786                 cl.cmd.cursor_screen[1] = 1;
787         }
788         */
789         cl.cmd.cursor_screen[0] = bound(-1, cl.cmd.cursor_screen[0], 1);
790         cl.cmd.cursor_screen[1] = bound(-1, cl.cmd.cursor_screen[1], 1);
791         cl.cmd.cursor_screen[2] = 1;
792
793         // calculate current view matrix
794         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, cl.cmd.cursor_start);
795         // calculate direction vector of cursor in viewspace by using frustum slopes
796         VectorSet(temp, cl.cmd.cursor_screen[2] * 1000000, (v_flipped.integer ? -1 : 1) * cl.cmd.cursor_screen[0] * -r_refdef.view.frustum_x * 1000000, cl.cmd.cursor_screen[1] * -r_refdef.view.frustum_y * 1000000);
797         Matrix4x4_Transform(&r_refdef.view.matrix, temp, cl.cmd.cursor_end);
798         // trace from view origin to the cursor
799         if (cl_prydoncursor_notrace.integer)
800         {
801                 cl.cmd.cursor_fraction = 1.0f;
802                 VectorCopy(cl.cmd.cursor_end, cl.cmd.cursor_impact);
803                 VectorClear(cl.cmd.cursor_normal);
804                 cl.cmd.cursor_entitynumber = 0;
805         }
806         else
807                 cl.cmd.cursor_fraction = CL_SelectTraceLine(cl.cmd.cursor_start, cl.cmd.cursor_end, cl.cmd.cursor_impact, cl.cmd.cursor_normal, &cl.cmd.cursor_entitynumber, (chase_active.integer || cl.intermission) ? &cl.entities[cl.playerentity].render : NULL);
808 }
809
810 #define NUMOFFSETS 27
811 static vec3_t offsets[NUMOFFSETS] =
812 {
813 // 1 no nudge (just return the original if this test passes)
814         { 0.000,  0.000,  0.000},
815 // 6 simple nudges
816         { 0.000,  0.000,  0.125}, { 0.000,  0.000, -0.125},
817         {-0.125,  0.000,  0.000}, { 0.125,  0.000,  0.000},
818         { 0.000, -0.125,  0.000}, { 0.000,  0.125,  0.000},
819 // 4 diagonal flat nudges
820         {-0.125, -0.125,  0.000}, { 0.125, -0.125,  0.000},
821         {-0.125,  0.125,  0.000}, { 0.125,  0.125,  0.000},
822 // 8 diagonal upward nudges
823         {-0.125,  0.000,  0.125}, { 0.125,  0.000,  0.125},
824         { 0.000, -0.125,  0.125}, { 0.000,  0.125,  0.125},
825         {-0.125, -0.125,  0.125}, { 0.125, -0.125,  0.125},
826         {-0.125,  0.125,  0.125}, { 0.125,  0.125,  0.125},
827 // 8 diagonal downward nudges
828         {-0.125,  0.000, -0.125}, { 0.125,  0.000, -0.125},
829         { 0.000, -0.125, -0.125}, { 0.000,  0.125, -0.125},
830         {-0.125, -0.125, -0.125}, { 0.125, -0.125, -0.125},
831         {-0.125,  0.125, -0.125}, { 0.125,  0.125, -0.125},
832 };
833
834 static qboolean CL_ClientMovement_Unstick(cl_clientmovement_state_t *s)
835 {
836         int i;
837         vec3_t neworigin;
838         for (i = 0;i < NUMOFFSETS;i++)
839         {
840                 VectorAdd(offsets[i], s->origin, neworigin);
841                 if (!CL_TraceBox(neworigin, cl.playercrouchmins, cl.playercrouchmaxs, neworigin, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true).startsolid)
842                 {
843                         VectorCopy(neworigin, s->origin);
844                         return true;
845                 }
846         }
847         // if all offsets failed, give up
848         return false;
849 }
850
851 static void CL_ClientMovement_UpdateStatus(cl_clientmovement_state_t *s)
852 {
853         vec_t f;
854         vec3_t origin1, origin2;
855         trace_t trace;
856
857         // make sure player is not stuck
858         CL_ClientMovement_Unstick(s);
859
860         // set crouched
861         if (s->cmd.crouch)
862         {
863                 // wants to crouch, this always works..
864                 if (!s->crouched)
865                         s->crouched = true;
866         }
867         else
868         {
869                 // wants to stand, if currently crouching we need to check for a
870                 // low ceiling first
871                 if (s->crouched)
872                 {
873                         trace = CL_TraceBox(s->origin, cl.playerstandmins, cl.playerstandmaxs, s->origin, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true);
874                         if (!trace.startsolid)
875                                 s->crouched = false;
876                 }
877         }
878         if (s->crouched)
879         {
880                 VectorCopy(cl.playercrouchmins, s->mins);
881                 VectorCopy(cl.playercrouchmaxs, s->maxs);
882         }
883         else
884         {
885                 VectorCopy(cl.playerstandmins, s->mins);
886                 VectorCopy(cl.playerstandmaxs, s->maxs);
887         }
888
889         // set onground
890         VectorSet(origin1, s->origin[0], s->origin[1], s->origin[2] + 1);
891         VectorSet(origin2, s->origin[0], s->origin[1], s->origin[2] - 1); // -2 causes clientside doublejump bug at above 150fps, raising that to 300fps :)
892         trace = CL_TraceBox(origin1, s->mins, s->maxs, origin2, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true);
893         if(trace.fraction < 1 && trace.plane.normal[2] > 0.7)
894         {
895                 s->onground = true;
896
897                 // this code actually "predicts" an impact; so let's clip velocity first
898                 f = DotProduct(s->velocity, trace.plane.normal);
899                 if(f < 0) // only if moving downwards actually
900                         VectorMA(s->velocity, -f, trace.plane.normal, s->velocity);
901         }
902         else
903                 s->onground = false;
904
905         // set watertype/waterlevel
906         VectorSet(origin1, s->origin[0], s->origin[1], s->origin[2] + s->mins[2] + 1);
907         s->waterlevel = WATERLEVEL_NONE;
908         s->watertype = CL_TracePoint(origin1, MOVE_NOMONSTERS, s->self, 0, true, false, NULL, false).startsupercontents & SUPERCONTENTS_LIQUIDSMASK;
909         if (s->watertype)
910         {
911                 s->waterlevel = WATERLEVEL_WETFEET;
912                 origin1[2] = s->origin[2] + (s->mins[2] + s->maxs[2]) * 0.5f;
913                 if (CL_TracePoint(origin1, MOVE_NOMONSTERS, s->self, 0, true, false, NULL, false).startsupercontents & SUPERCONTENTS_LIQUIDSMASK)
914                 {
915                         s->waterlevel = WATERLEVEL_SWIMMING;
916                         origin1[2] = s->origin[2] + 22;
917                         if (CL_TracePoint(origin1, MOVE_NOMONSTERS, s->self, 0, true, false, NULL, false).startsupercontents & SUPERCONTENTS_LIQUIDSMASK)
918                                 s->waterlevel = WATERLEVEL_SUBMERGED;
919                 }
920         }
921
922         // water jump prediction
923         if (s->onground || s->velocity[2] <= 0 || s->waterjumptime <= 0)
924                 s->waterjumptime = 0;
925 }
926
927 static void CL_ClientMovement_Move(cl_clientmovement_state_t *s)
928 {
929         int bump;
930         double t;
931         vec_t f;
932         vec3_t neworigin;
933         vec3_t currentorigin2;
934         vec3_t neworigin2;
935         vec3_t primalvelocity;
936         trace_t trace;
937         trace_t trace2;
938         trace_t trace3;
939         CL_ClientMovement_UpdateStatus(s);
940         VectorCopy(s->velocity, primalvelocity);
941         for (bump = 0, t = s->cmd.frametime;bump < 8 && VectorLength2(s->velocity) > 0;bump++)
942         {
943                 VectorMA(s->origin, t, s->velocity, neworigin);
944                 trace = CL_TraceBox(s->origin, s->mins, s->maxs, neworigin, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true);
945                 if (trace.fraction < 1 && trace.plane.normal[2] == 0)
946                 {
947                         // may be a step or wall, try stepping up
948                         // first move forward at a higher level
949                         VectorSet(currentorigin2, s->origin[0], s->origin[1], s->origin[2] + cl.movevars_stepheight);
950                         VectorSet(neworigin2, neworigin[0], neworigin[1], s->origin[2] + cl.movevars_stepheight);
951                         trace2 = CL_TraceBox(currentorigin2, s->mins, s->maxs, neworigin2, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true);
952                         if (!trace2.startsolid)
953                         {
954                                 // then move down from there
955                                 VectorCopy(trace2.endpos, currentorigin2);
956                                 VectorSet(neworigin2, trace2.endpos[0], trace2.endpos[1], s->origin[2]);
957                                 trace3 = CL_TraceBox(currentorigin2, s->mins, s->maxs, neworigin2, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true);
958                                 //Con_Printf("%f %f %f %f : %f %f %f %f : %f %f %f %f\n", trace.fraction, trace.endpos[0], trace.endpos[1], trace.endpos[2], trace2.fraction, trace2.endpos[0], trace2.endpos[1], trace2.endpos[2], trace3.fraction, trace3.endpos[0], trace3.endpos[1], trace3.endpos[2]);
959                                 // accept the new trace if it made some progress
960                                 if (fabs(trace3.endpos[0] - trace.endpos[0]) >= 0.03125 || fabs(trace3.endpos[1] - trace.endpos[1]) >= 0.03125)
961                                 {
962                                         trace = trace2;
963                                         VectorCopy(trace3.endpos, trace.endpos);
964                                 }
965                         }
966                 }
967
968                 // check if it moved at all
969                 if (trace.fraction >= 0.001)
970                         VectorCopy(trace.endpos, s->origin);
971
972                 // check if it moved all the way
973                 if (trace.fraction == 1)
974                         break;
975
976                 // this is only really needed for nogravityonground combined with gravityunaffectedbyticrate
977                 // <LordHavoc> I'm pretty sure I commented it out solely because it seemed redundant
978                 // this got commented out in a change that supposedly makes the code match QW better
979                 // so if this is broken, maybe put it in an if(cls.protocol != PROTOCOL_QUAKEWORLD) block
980                 if (trace.plane.normal[2] > 0.7)
981                         s->onground = true;
982
983                 t -= t * trace.fraction;
984
985                 f = DotProduct(s->velocity, trace.plane.normal);
986                 VectorMA(s->velocity, -f, trace.plane.normal, s->velocity);
987         }
988         if (s->waterjumptime > 0)
989                 VectorCopy(primalvelocity, s->velocity);
990 }
991
992
993 static void CL_ClientMovement_Physics_Swim(cl_clientmovement_state_t *s)
994 {
995         vec_t wishspeed;
996         vec_t f;
997         vec3_t wishvel;
998         vec3_t wishdir;
999
1000         // water jump only in certain situations
1001         // this mimics quakeworld code
1002         if (s->cmd.jump && s->waterlevel == 2 && s->velocity[2] >= -180)
1003         {
1004                 vec3_t forward;
1005                 vec3_t yawangles;
1006                 vec3_t spot;
1007                 VectorSet(yawangles, 0, s->cmd.viewangles[1], 0);
1008                 AngleVectors(yawangles, forward, NULL, NULL);
1009                 VectorMA(s->origin, 24, forward, spot);
1010                 spot[2] += 8;
1011                 if (CL_TracePoint(spot, MOVE_NOMONSTERS, s->self, 0, true, false, NULL, false).startsolid)
1012                 {
1013                         spot[2] += 24;
1014                         if (!CL_TracePoint(spot, MOVE_NOMONSTERS, s->self, 0, true, false, NULL, false).startsolid)
1015                         {
1016                                 VectorScale(forward, 50, s->velocity);
1017                                 s->velocity[2] = 310;
1018                                 s->waterjumptime = 2;
1019                                 s->onground = false;
1020                                 s->cmd.canjump = false;
1021                         }
1022                 }
1023         }
1024
1025         if (!(s->cmd.forwardmove*s->cmd.forwardmove + s->cmd.sidemove*s->cmd.sidemove + s->cmd.upmove*s->cmd.upmove))
1026         {
1027                 // drift towards bottom
1028                 VectorSet(wishvel, 0, 0, -60);
1029         }
1030         else
1031         {
1032                 // swim
1033                 vec3_t forward;
1034                 vec3_t right;
1035                 vec3_t up;
1036                 // calculate movement vector
1037                 AngleVectors(s->cmd.viewangles, forward, right, up);
1038                 VectorSet(up, 0, 0, 1);
1039                 VectorMAMAM(s->cmd.forwardmove, forward, s->cmd.sidemove, right, s->cmd.upmove, up, wishvel);
1040         }
1041
1042         // split wishvel into wishspeed and wishdir
1043         wishspeed = VectorLength(wishvel);
1044         if (wishspeed)
1045                 VectorScale(wishvel, 1 / wishspeed, wishdir);
1046         else
1047                 VectorSet( wishdir, 0.0, 0.0, 0.0 );
1048         wishspeed = min(wishspeed, cl.movevars_maxspeed) * 0.7;
1049
1050         if (s->crouched)
1051                 wishspeed *= 0.5;
1052
1053         if (s->waterjumptime <= 0)
1054         {
1055                 // water friction
1056                 f = 1 - s->cmd.frametime * cl.movevars_waterfriction * (cls.protocol == PROTOCOL_QUAKEWORLD ? s->waterlevel : 1);
1057                 f = bound(0, f, 1);
1058                 VectorScale(s->velocity, f, s->velocity);
1059
1060                 // water acceleration
1061                 f = wishspeed - DotProduct(s->velocity, wishdir);
1062                 if (f > 0)
1063                 {
1064                         f = min(cl.movevars_wateraccelerate * s->cmd.frametime * wishspeed, f);
1065                         VectorMA(s->velocity, f, wishdir, s->velocity);
1066                 }
1067
1068                 // holding jump button swims upward slowly
1069                 if (s->cmd.jump)
1070                 {
1071                         if (s->watertype & SUPERCONTENTS_LAVA)
1072                                 s->velocity[2] =  50;
1073                         else if (s->watertype & SUPERCONTENTS_SLIME)
1074                                 s->velocity[2] =  80;
1075                         else
1076                         {
1077                                 if (IS_NEXUIZ_DERIVED(gamemode))
1078                                         s->velocity[2] = 200;
1079                                 else
1080                                         s->velocity[2] = 100;
1081                         }
1082                 }
1083         }
1084
1085         CL_ClientMovement_Move(s);
1086 }
1087
1088 static vec_t CL_IsMoveInDirection(vec_t forward, vec_t side, vec_t angle)
1089 {
1090         if(forward == 0 && side == 0)
1091                 return 0; // avoid division by zero
1092         angle -= RAD2DEG(atan2(side, forward));
1093         angle = (ANGLEMOD(angle + 180) - 180) / 45;
1094         if(angle >  1)
1095                 return 0;
1096         if(angle < -1)
1097                 return 0;
1098         return 1 - fabs(angle);
1099 }
1100
1101 static vec_t CL_GeomLerp(vec_t a, vec_t lerp, vec_t b)
1102 {
1103         if(a == 0)
1104         {
1105                 if(lerp < 1)
1106                         return 0;
1107                 else
1108                         return b;
1109         }
1110         if(b == 0)
1111         {
1112                 if(lerp > 0)
1113                         return 0;
1114                 else
1115                         return a;
1116         }
1117         return a * pow(fabs(b / a), lerp);
1118 }
1119
1120 static void CL_ClientMovement_Physics_CPM_PM_Aircontrol(cl_clientmovement_state_t *s, vec3_t wishdir, vec_t wishspeed)
1121 {
1122         vec_t zspeed, speed, dot, k;
1123
1124 #if 0
1125         // this doesn't play well with analog input
1126         if(s->cmd.forwardmove == 0 || s->cmd.sidemove != 0)
1127                 return;
1128         k = 32;
1129 #else
1130         k = 32 * (2 * CL_IsMoveInDirection(s->cmd.forwardmove, s->cmd.sidemove, 0) - 1);
1131         if(k <= 0)
1132                 return;
1133 #endif
1134
1135         k *= bound(0, wishspeed / cl.movevars_maxairspeed, 1);
1136
1137         zspeed = s->velocity[2];
1138         s->velocity[2] = 0;
1139         speed = VectorNormalizeLength(s->velocity);
1140
1141         dot = DotProduct(s->velocity, wishdir);
1142
1143         if(dot > 0) { // we can't change direction while slowing down
1144                 k *= pow(dot, cl.movevars_aircontrol_power)*s->cmd.frametime;
1145                 speed = max(0, speed - cl.movevars_aircontrol_penalty * sqrt(max(0, 1 - dot*dot)) * k/32);
1146                 k *= cl.movevars_aircontrol;
1147                 VectorMAM(speed, s->velocity, k, wishdir, s->velocity);
1148                 VectorNormalize(s->velocity);
1149         }
1150
1151         VectorScale(s->velocity, speed, s->velocity);
1152         s->velocity[2] = zspeed;
1153 }
1154
1155 static float CL_ClientMovement_Physics_AdjustAirAccelQW(float accelqw, float factor)
1156 {
1157         return
1158                 (accelqw < 0 ? -1 : +1)
1159                 *
1160                 bound(0.000001, 1 - (1 - fabs(accelqw)) * factor, 1);
1161 }
1162
1163 static void CL_ClientMovement_Physics_PM_Accelerate(cl_clientmovement_state_t *s, vec3_t wishdir, vec_t wishspeed, vec_t wishspeed0, vec_t accel, vec_t accelqw, vec_t stretchfactor, vec_t sidefric, vec_t speedlimit)
1164 {
1165         vec_t vel_straight;
1166         vec_t vel_z;
1167         vec3_t vel_perpend;
1168         vec_t step;
1169         vec3_t vel_xy;
1170         vec_t vel_xy_current;
1171         vec_t vel_xy_backward, vel_xy_forward;
1172         vec_t speedclamp;
1173
1174         if(stretchfactor > 0)
1175                 speedclamp = stretchfactor;
1176         else if(accelqw < 0)
1177                 speedclamp = 1;
1178         else
1179                 speedclamp = -1; // no clamping
1180
1181         if(accelqw < 0)
1182                 accelqw = -accelqw;
1183
1184         if(cl.moveflags & MOVEFLAG_Q2AIRACCELERATE)
1185                 wishspeed0 = wishspeed; // don't need to emulate this Q1 bug
1186
1187         vel_straight = DotProduct(s->velocity, wishdir);
1188         vel_z = s->velocity[2];
1189         VectorCopy(s->velocity, vel_xy); vel_xy[2] -= vel_z;
1190         VectorMA(vel_xy, -vel_straight, wishdir, vel_perpend);
1191
1192         step = accel * s->cmd.frametime * wishspeed0;
1193
1194         vel_xy_current  = VectorLength(vel_xy);
1195         if(speedlimit > 0)
1196                 accelqw = CL_ClientMovement_Physics_AdjustAirAccelQW(accelqw, (speedlimit - bound(wishspeed, vel_xy_current, speedlimit)) / max(1, speedlimit - wishspeed));
1197         vel_xy_forward  = vel_xy_current + bound(0, wishspeed - vel_xy_current, step) * accelqw + step * (1 - accelqw);
1198         vel_xy_backward = vel_xy_current - bound(0, wishspeed + vel_xy_current, step) * accelqw - step * (1 - accelqw);
1199         if(vel_xy_backward < 0)
1200                 vel_xy_backward = 0; // not that it REALLY occurs that this would cause wrong behaviour afterwards
1201
1202         vel_straight    = vel_straight   + bound(0, wishspeed - vel_straight,   step) * accelqw + step * (1 - accelqw);
1203
1204         if(sidefric < 0 && VectorLength2(vel_perpend))
1205                 // negative: only apply so much sideways friction to stay below the speed you could get by "braking"
1206         {
1207                 vec_t f, fmin;
1208                 f = max(0, 1 + s->cmd.frametime * wishspeed * sidefric);
1209                 fmin = (vel_xy_backward*vel_xy_backward - vel_straight*vel_straight) / VectorLength2(vel_perpend);
1210                 // assume: fmin > 1
1211                 // vel_xy_backward*vel_xy_backward - vel_straight*vel_straight > vel_perpend*vel_perpend
1212                 // vel_xy_backward*vel_xy_backward > vel_straight*vel_straight + vel_perpend*vel_perpend
1213                 // vel_xy_backward*vel_xy_backward > vel_xy * vel_xy
1214                 // obviously, this cannot be
1215                 if(fmin <= 0)
1216                         VectorScale(vel_perpend, f, vel_perpend);
1217                 else
1218                 {
1219                         fmin = sqrt(fmin);
1220                         VectorScale(vel_perpend, max(fmin, f), vel_perpend);
1221                 }
1222         }
1223         else
1224                 VectorScale(vel_perpend, max(0, 1 - s->cmd.frametime * wishspeed * sidefric), vel_perpend);
1225
1226         VectorMA(vel_perpend, vel_straight, wishdir, s->velocity);
1227
1228         if(speedclamp >= 0)
1229         {
1230                 vec_t vel_xy_preclamp;
1231                 vel_xy_preclamp = VectorLength(s->velocity);
1232                 if(vel_xy_preclamp > 0) // prevent division by zero
1233                 {
1234                         vel_xy_current += (vel_xy_forward - vel_xy_current) * speedclamp;
1235                         if(vel_xy_current < vel_xy_preclamp)
1236                                 VectorScale(s->velocity, (vel_xy_current / vel_xy_preclamp), s->velocity);
1237                 }
1238         }
1239
1240         s->velocity[2] += vel_z;
1241 }
1242
1243 static void CL_ClientMovement_Physics_PM_AirAccelerate(cl_clientmovement_state_t *s, vec3_t wishdir, vec_t wishspeed)
1244 {
1245     vec3_t curvel, wishvel, acceldir, curdir;
1246     float addspeed, accelspeed, curspeed;
1247     float dot;
1248
1249     float airforwardaccel = cl.movevars_warsowbunny_airforwardaccel;
1250     float bunnyaccel = cl.movevars_warsowbunny_accel;
1251     float bunnytopspeed = cl.movevars_warsowbunny_topspeed;
1252     float turnaccel = cl.movevars_warsowbunny_turnaccel;
1253     float backtosideratio = cl.movevars_warsowbunny_backtosideratio;
1254
1255     if( !wishspeed )
1256         return;
1257
1258     VectorCopy( s->velocity, curvel );
1259     curvel[2] = 0;
1260     curspeed = VectorLength( curvel );
1261
1262     if( wishspeed > curspeed * 1.01f )
1263     {
1264         float faccelspeed = curspeed + airforwardaccel * cl.movevars_maxairspeed * s->cmd.frametime;
1265         if( faccelspeed < wishspeed )
1266             wishspeed = faccelspeed;
1267     }
1268     else
1269     {
1270         float f = ( bunnytopspeed - curspeed ) / ( bunnytopspeed - cl.movevars_maxairspeed );
1271         if( f < 0 )
1272             f = 0;
1273         wishspeed = max( curspeed, cl.movevars_maxairspeed ) + bunnyaccel * f * cl.movevars_maxairspeed * s->cmd.frametime;
1274     }
1275     VectorScale( wishdir, wishspeed, wishvel );
1276     VectorSubtract( wishvel, curvel, acceldir );
1277     addspeed = VectorNormalizeLength( acceldir );
1278
1279     accelspeed = turnaccel * cl.movevars_maxairspeed /* wishspeed */ * s->cmd.frametime;
1280     if( accelspeed > addspeed )
1281         accelspeed = addspeed;
1282
1283     if( backtosideratio < 1.0f )
1284     {
1285         VectorNormalize2( curvel, curdir );
1286         dot = DotProduct( acceldir, curdir );
1287         if( dot < 0 )
1288             VectorMA( acceldir, -( 1.0f - backtosideratio ) * dot, curdir, acceldir );
1289     }
1290
1291     VectorMA( s->velocity, accelspeed, acceldir, s->velocity );
1292 }
1293
1294 static void CL_ClientMovement_Physics_Walk(cl_clientmovement_state_t *s)
1295 {
1296         vec_t friction;
1297         vec_t wishspeed;
1298         vec_t addspeed;
1299         vec_t accelspeed;
1300         vec_t f;
1301         vec_t gravity;
1302         vec3_t forward;
1303         vec3_t right;
1304         vec3_t up;
1305         vec3_t wishvel;
1306         vec3_t wishdir;
1307         vec3_t yawangles;
1308         trace_t trace;
1309
1310         // jump if on ground with jump button pressed but only if it has been
1311         // released at least once since the last jump
1312         if (s->cmd.jump)
1313         {
1314                 if (s->onground && (s->cmd.canjump || !cl_movement_track_canjump.integer))
1315                 {
1316                         s->velocity[2] += cl.movevars_jumpvelocity;
1317                         s->onground = false;
1318                         s->cmd.canjump = false;
1319                 }
1320         }
1321         else
1322                 s->cmd.canjump = true;
1323
1324         // calculate movement vector
1325         VectorSet(yawangles, 0, s->cmd.viewangles[1], 0);
1326         AngleVectors(yawangles, forward, right, up);
1327         VectorMAM(s->cmd.forwardmove, forward, s->cmd.sidemove, right, wishvel);
1328
1329         // split wishvel into wishspeed and wishdir
1330         wishspeed = VectorLength(wishvel);
1331         if (wishspeed)
1332                 VectorScale(wishvel, 1 / wishspeed, wishdir);
1333         else
1334                 VectorSet( wishdir, 0.0, 0.0, 0.0 );
1335         // check if onground
1336         if (s->onground)
1337         {
1338                 wishspeed = min(wishspeed, cl.movevars_maxspeed);
1339                 if (s->crouched)
1340                         wishspeed *= 0.5;
1341
1342                 // apply edge friction
1343                 f = sqrt(s->velocity[0] * s->velocity[0] + s->velocity[1] * s->velocity[1]);
1344                 if (f > 0)
1345                 {
1346                         friction = cl.movevars_friction;
1347                         if (cl.movevars_edgefriction != 1)
1348                         {
1349                                 vec3_t neworigin2;
1350                                 vec3_t neworigin3;
1351                                 // note: QW uses the full player box for the trace, and yet still
1352                                 // uses s->origin[2] + s->mins[2], which is clearly an bug, but
1353                                 // this mimics it for compatibility
1354                                 VectorSet(neworigin2, s->origin[0] + s->velocity[0]*(16/f), s->origin[1] + s->velocity[1]*(16/f), s->origin[2] + s->mins[2]);
1355                                 VectorSet(neworigin3, neworigin2[0], neworigin2[1], neworigin2[2] - 34);
1356                                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1357                                         trace = CL_TraceBox(neworigin2, s->mins, s->maxs, neworigin3, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true);
1358                                 else
1359                                         trace = CL_TraceLine(neworigin2, neworigin3, MOVE_NORMAL, s->self, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY | SUPERCONTENTS_PLAYERCLIP, collision_extendmovelength.value, true, true, NULL, true, false);
1360                                 if (trace.fraction == 1 && !trace.startsolid)
1361                                         friction *= cl.movevars_edgefriction;
1362                         }
1363                         // apply ground friction
1364                         f = 1 - s->cmd.frametime * friction * ((f < cl.movevars_stopspeed) ? (cl.movevars_stopspeed / f) : 1);
1365                         f = max(f, 0);
1366                         VectorScale(s->velocity, f, s->velocity);
1367                 }
1368                 addspeed = wishspeed - DotProduct(s->velocity, wishdir);
1369                 if (addspeed > 0)
1370                 {
1371                         accelspeed = min(cl.movevars_accelerate * s->cmd.frametime * wishspeed, addspeed);
1372                         VectorMA(s->velocity, accelspeed, wishdir, s->velocity);
1373                 }
1374                 gravity = cl.movevars_gravity * cl.movevars_entgravity * s->cmd.frametime;
1375                 if(!(cl.moveflags & MOVEFLAG_NOGRAVITYONGROUND))
1376                 {
1377                         if(cl.moveflags & MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE)
1378                                 s->velocity[2] -= gravity * 0.5f;
1379                         else
1380                                 s->velocity[2] -= gravity;
1381                 }
1382                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
1383                         s->velocity[2] = 0;
1384                 if (VectorLength2(s->velocity))
1385                         CL_ClientMovement_Move(s);
1386                 if(!(cl.moveflags & MOVEFLAG_NOGRAVITYONGROUND) || !s->onground)
1387                 {
1388                         if(cl.moveflags & MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE)
1389                                 s->velocity[2] -= gravity * 0.5f;
1390                 }
1391         }
1392         else
1393         {
1394                 if (s->waterjumptime <= 0)
1395                 {
1396                         // apply air speed limit
1397                         vec_t accel, wishspeed0, wishspeed2, accelqw, strafity;
1398                         qboolean accelerating;
1399
1400                         accelqw = cl.movevars_airaccel_qw;
1401                         wishspeed0 = wishspeed;
1402                         wishspeed = min(wishspeed, cl.movevars_maxairspeed);
1403                         if (s->crouched)
1404                                 wishspeed *= 0.5;
1405                         accel = cl.movevars_airaccelerate;
1406
1407                         accelerating = (DotProduct(s->velocity, wishdir) > 0);
1408                         wishspeed2 = wishspeed;
1409
1410                         // CPM: air control
1411                         if(cl.movevars_airstopaccelerate != 0)
1412                         {
1413                                 vec3_t curdir;
1414                                 curdir[0] = s->velocity[0];
1415                                 curdir[1] = s->velocity[1];
1416                                 curdir[2] = 0;
1417                                 VectorNormalize(curdir);
1418                                 accel = accel + (cl.movevars_airstopaccelerate - accel) * max(0, -DotProduct(curdir, wishdir));
1419                         }
1420                         strafity = CL_IsMoveInDirection(s->cmd.forwardmove, s->cmd.sidemove, -90) + CL_IsMoveInDirection(s->cmd.forwardmove, s->cmd.sidemove, +90); // if one is nonzero, other is always zero
1421                         if(cl.movevars_maxairstrafespeed)
1422                                 wishspeed = min(wishspeed, CL_GeomLerp(cl.movevars_maxairspeed, strafity, cl.movevars_maxairstrafespeed));
1423                         if(cl.movevars_airstrafeaccelerate)
1424                                 accel = CL_GeomLerp(cl.movevars_airaccelerate, strafity, cl.movevars_airstrafeaccelerate);
1425                         if(cl.movevars_airstrafeaccel_qw)
1426                                 accelqw =
1427                                         (((strafity > 0.5 ? cl.movevars_airstrafeaccel_qw : cl.movevars_airaccel_qw) >= 0) ? +1 : -1)
1428                                         *
1429                                         (1 - CL_GeomLerp(1 - fabs(cl.movevars_airaccel_qw), strafity, 1 - fabs(cl.movevars_airstrafeaccel_qw)));
1430                         // !CPM
1431
1432                         if(cl.movevars_warsowbunny_turnaccel && accelerating && s->cmd.sidemove == 0 && s->cmd.forwardmove != 0)
1433                                 CL_ClientMovement_Physics_PM_AirAccelerate(s, wishdir, wishspeed2);
1434                         else
1435                                 CL_ClientMovement_Physics_PM_Accelerate(s, wishdir, wishspeed, wishspeed0, accel, accelqw, cl.movevars_airaccel_qw_stretchfactor, cl.movevars_airaccel_sideways_friction / cl.movevars_maxairspeed, cl.movevars_airspeedlimit_nonqw);
1436
1437                         if(cl.movevars_aircontrol)
1438                                 CL_ClientMovement_Physics_CPM_PM_Aircontrol(s, wishdir, wishspeed2);
1439                 }
1440                 gravity = cl.movevars_gravity * cl.movevars_entgravity * s->cmd.frametime;
1441                 if(cl.moveflags & MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE)
1442                         s->velocity[2] -= gravity * 0.5f;
1443                 else
1444                         s->velocity[2] -= gravity;
1445                 CL_ClientMovement_Move(s);
1446                 if(!(cl.moveflags & MOVEFLAG_NOGRAVITYONGROUND) || !s->onground)
1447                 {
1448                         if(cl.moveflags & MOVEFLAG_GRAVITYUNAFFECTEDBYTICRATE)
1449                                 s->velocity[2] -= gravity * 0.5f;
1450                 }
1451         }
1452 }
1453
1454 static void CL_ClientMovement_PlayerMove(cl_clientmovement_state_t *s)
1455 {
1456         //Con_Printf(" %f", frametime);
1457         if (!s->cmd.jump)
1458                 s->cmd.canjump = true;
1459         s->waterjumptime -= s->cmd.frametime;
1460         CL_ClientMovement_UpdateStatus(s);
1461         if (s->waterlevel >= WATERLEVEL_SWIMMING)
1462                 CL_ClientMovement_Physics_Swim(s);
1463         else
1464                 CL_ClientMovement_Physics_Walk(s);
1465 }
1466
1467 extern cvar_t slowmo;
1468 void CL_UpdateMoveVars(void)
1469 {
1470         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1471         {
1472                 cl.moveflags = 0;
1473         }
1474         else if (cl.stats[STAT_MOVEVARS_TICRATE])
1475         {
1476                 cl.moveflags = cl.stats[STAT_MOVEFLAGS];
1477                 cl.movevars_ticrate = cl.statsf[STAT_MOVEVARS_TICRATE];
1478                 cl.movevars_timescale = cl.statsf[STAT_MOVEVARS_TIMESCALE];
1479                 cl.movevars_gravity = cl.statsf[STAT_MOVEVARS_GRAVITY];
1480                 cl.movevars_stopspeed = cl.statsf[STAT_MOVEVARS_STOPSPEED] ;
1481                 cl.movevars_maxspeed = cl.statsf[STAT_MOVEVARS_MAXSPEED];
1482                 cl.movevars_spectatormaxspeed = cl.statsf[STAT_MOVEVARS_SPECTATORMAXSPEED];
1483                 cl.movevars_accelerate = cl.statsf[STAT_MOVEVARS_ACCELERATE];
1484                 cl.movevars_airaccelerate = cl.statsf[STAT_MOVEVARS_AIRACCELERATE];
1485                 cl.movevars_wateraccelerate = cl.statsf[STAT_MOVEVARS_WATERACCELERATE];
1486                 cl.movevars_entgravity = cl.statsf[STAT_MOVEVARS_ENTGRAVITY];
1487                 cl.movevars_jumpvelocity = cl.statsf[STAT_MOVEVARS_JUMPVELOCITY];
1488                 cl.movevars_edgefriction = cl.statsf[STAT_MOVEVARS_EDGEFRICTION];
1489                 cl.movevars_maxairspeed = cl.statsf[STAT_MOVEVARS_MAXAIRSPEED];
1490                 cl.movevars_stepheight = cl.statsf[STAT_MOVEVARS_STEPHEIGHT];
1491                 cl.movevars_airaccel_qw = cl.statsf[STAT_MOVEVARS_AIRACCEL_QW];
1492                 cl.movevars_airaccel_qw_stretchfactor = cl.statsf[STAT_MOVEVARS_AIRACCEL_QW_STRETCHFACTOR];
1493                 cl.movevars_airaccel_sideways_friction = cl.statsf[STAT_MOVEVARS_AIRACCEL_SIDEWAYS_FRICTION];
1494                 cl.movevars_friction = cl.statsf[STAT_MOVEVARS_FRICTION];
1495                 cl.movevars_wallfriction = cl.statsf[STAT_MOVEVARS_WALLFRICTION];
1496                 cl.movevars_waterfriction = cl.statsf[STAT_MOVEVARS_WATERFRICTION];
1497                 cl.movevars_airstopaccelerate = cl.statsf[STAT_MOVEVARS_AIRSTOPACCELERATE];
1498                 cl.movevars_airstrafeaccelerate = cl.statsf[STAT_MOVEVARS_AIRSTRAFEACCELERATE];
1499                 cl.movevars_maxairstrafespeed = cl.statsf[STAT_MOVEVARS_MAXAIRSTRAFESPEED];
1500                 cl.movevars_airstrafeaccel_qw = cl.statsf[STAT_MOVEVARS_AIRSTRAFEACCEL_QW];
1501                 cl.movevars_aircontrol = cl.statsf[STAT_MOVEVARS_AIRCONTROL];
1502                 cl.movevars_aircontrol_power = cl.statsf[STAT_MOVEVARS_AIRCONTROL_POWER];
1503                 cl.movevars_aircontrol_penalty = cl.statsf[STAT_MOVEVARS_AIRCONTROL_PENALTY];
1504                 cl.movevars_warsowbunny_airforwardaccel = cl.statsf[STAT_MOVEVARS_WARSOWBUNNY_AIRFORWARDACCEL];
1505                 cl.movevars_warsowbunny_accel = cl.statsf[STAT_MOVEVARS_WARSOWBUNNY_ACCEL];
1506                 cl.movevars_warsowbunny_topspeed = cl.statsf[STAT_MOVEVARS_WARSOWBUNNY_TOPSPEED];
1507                 cl.movevars_warsowbunny_turnaccel = cl.statsf[STAT_MOVEVARS_WARSOWBUNNY_TURNACCEL];
1508                 cl.movevars_warsowbunny_backtosideratio = cl.statsf[STAT_MOVEVARS_WARSOWBUNNY_BACKTOSIDERATIO];
1509                 cl.movevars_airspeedlimit_nonqw = cl.statsf[STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW];
1510         }
1511         else
1512         {
1513                 cl.moveflags = 0;
1514                 cl.movevars_ticrate = (cls.demoplayback ? 1.0f : slowmo.value) / bound(1.0f, cl_netfps.value, 1000.0f);
1515                 cl.movevars_timescale = (cls.demoplayback ? 1.0f : slowmo.value);
1516                 cl.movevars_gravity = sv_gravity.value;
1517                 cl.movevars_stopspeed = cl_movement_stopspeed.value;
1518                 cl.movevars_maxspeed = cl_movement_maxspeed.value;
1519                 cl.movevars_spectatormaxspeed = cl_movement_maxspeed.value;
1520                 cl.movevars_accelerate = cl_movement_accelerate.value;
1521                 cl.movevars_airaccelerate = cl_movement_airaccelerate.value < 0 ? cl_movement_accelerate.value : cl_movement_airaccelerate.value;
1522                 cl.movevars_wateraccelerate = cl_movement_wateraccelerate.value < 0 ? cl_movement_accelerate.value : cl_movement_wateraccelerate.value;
1523                 cl.movevars_friction = cl_movement_friction.value;
1524                 cl.movevars_wallfriction = cl_movement_wallfriction.value;
1525                 cl.movevars_waterfriction = cl_movement_waterfriction.value < 0 ? cl_movement_friction.value : cl_movement_waterfriction.value;
1526                 cl.movevars_entgravity = 1;
1527                 cl.movevars_jumpvelocity = cl_movement_jumpvelocity.value;
1528                 cl.movevars_edgefriction = cl_movement_edgefriction.value;
1529                 cl.movevars_maxairspeed = cl_movement_maxairspeed.value;
1530                 cl.movevars_stepheight = cl_movement_stepheight.value;
1531                 cl.movevars_airaccel_qw = cl_movement_airaccel_qw.value;
1532                 cl.movevars_airaccel_qw_stretchfactor = 0;
1533                 cl.movevars_airaccel_sideways_friction = cl_movement_airaccel_sideways_friction.value;
1534                 cl.movevars_airstopaccelerate = 0;
1535                 cl.movevars_airstrafeaccelerate = 0;
1536                 cl.movevars_maxairstrafespeed = 0;
1537                 cl.movevars_airstrafeaccel_qw = 0;
1538                 cl.movevars_aircontrol = 0;
1539                 cl.movevars_aircontrol_power = 2;
1540                 cl.movevars_aircontrol_penalty = 0;
1541                 cl.movevars_warsowbunny_airforwardaccel = 0;
1542                 cl.movevars_warsowbunny_accel = 0;
1543                 cl.movevars_warsowbunny_topspeed = 0;
1544                 cl.movevars_warsowbunny_turnaccel = 0;
1545                 cl.movevars_warsowbunny_backtosideratio = 0;
1546                 cl.movevars_airspeedlimit_nonqw = 0;
1547         }
1548
1549         if(!(cl.moveflags & MOVEFLAG_VALID))
1550         {
1551                 if(gamemode == GAME_NEXUIZ)  // Legacy hack to work with old servers of Nexuiz.
1552                         cl.moveflags = MOVEFLAG_Q2AIRACCELERATE;
1553         }
1554
1555         if(cl.movevars_aircontrol_power <= 0)
1556                 cl.movevars_aircontrol_power = 2; // CPMA default
1557 }
1558
1559 void CL_ClientMovement_PlayerMove_Frame(cl_clientmovement_state_t *s)
1560 {
1561         // if a move is more than 50ms, do it as two moves (matching qwsv)
1562         //Con_Printf("%i ", s.cmd.msec);
1563         if(s->cmd.frametime > 0.0005)
1564         {
1565                 if (s->cmd.frametime > 0.05)
1566                 {
1567                         s->cmd.frametime /= 2;
1568                         CL_ClientMovement_PlayerMove(s);
1569                 }
1570                 CL_ClientMovement_PlayerMove(s);
1571         }
1572         else
1573         {
1574                 // we REALLY need this handling to happen, even if the move is not executed
1575                 if (!s->cmd.jump)
1576                         s->cmd.canjump = true;
1577         }
1578 }
1579
1580 void CL_ClientMovement_Replay(void)
1581 {
1582         int i;
1583         double totalmovemsec;
1584         cl_clientmovement_state_t s;
1585
1586         VectorCopy(cl.mvelocity[0], cl.movement_velocity);
1587
1588         if (cl.movement_predicted && !cl.movement_replay)
1589                 return;
1590
1591         if (!cl_movement_replay.integer)
1592                 return;
1593
1594         // set up starting state for the series of moves
1595         memset(&s, 0, sizeof(s));
1596         VectorCopy(cl.entities[cl.playerentity].state_current.origin, s.origin);
1597         VectorCopy(cl.mvelocity[0], s.velocity);
1598         s.crouched = true; // will be updated on first move
1599         //Con_Printf("movement replay starting org %f %f %f vel %f %f %f\n", s.origin[0], s.origin[1], s.origin[2], s.velocity[0], s.velocity[1], s.velocity[2]);
1600
1601         totalmovemsec = 0;
1602         for (i = 0;i < CL_MAX_USERCMDS;i++)
1603                 if (cl.movecmd[i].sequence > cls.servermovesequence)
1604                         totalmovemsec += cl.movecmd[i].msec;
1605         cl.movement_predicted = totalmovemsec >= cl_movement_minping.value && cls.servermovesequence && (cl_movement.integer && !cls.demoplayback && cls.signon == SIGNONS && cl.stats[STAT_HEALTH] > 0 && !cl.intermission);
1606         //Con_Printf("%i = %.0f >= %.0f && %u && (%i && %i && %i == %i && %i > 0 && %i\n", cl.movement_predicted, totalmovemsec, cl_movement_minping.value, cls.servermovesequence, cl_movement.integer, !cls.demoplayback, cls.signon, SIGNONS, cl.stats[STAT_HEALTH], !cl.intermission);
1607         if (cl.movement_predicted)
1608         {
1609                 //Con_Printf("%ims\n", cl.movecmd[0].msec);
1610
1611                 // replay the input queue to predict current location
1612                 // note: this relies on the fact there's always one queue item at the end
1613
1614                 // find how many are still valid
1615                 for (i = 0;i < CL_MAX_USERCMDS;i++)
1616                         if (cl.movecmd[i].sequence <= cls.servermovesequence)
1617                                 break;
1618                 // now walk them in oldest to newest order
1619                 for (i--;i >= 0;i--)
1620                 {
1621                         s.cmd = cl.movecmd[i];
1622                         if (i < CL_MAX_USERCMDS - 1)
1623                                 s.cmd.canjump = cl.movecmd[i+1].canjump;
1624
1625                         CL_ClientMovement_PlayerMove_Frame(&s);
1626
1627                         cl.movecmd[i].canjump = s.cmd.canjump;
1628                 }
1629                 //Con_Printf("\n");
1630                 CL_ClientMovement_UpdateStatus(&s);
1631         }
1632         else
1633         {
1634                 // get the first movement queue entry to know whether to crouch and such
1635                 s.cmd = cl.movecmd[0];
1636         }
1637
1638         if (!cls.demoplayback) // for bob, speedometer
1639         {
1640                 cl.movement_replay = false;
1641                 // update the interpolation target position and velocity
1642                 VectorCopy(s.origin, cl.movement_origin);
1643                 VectorCopy(s.velocity, cl.movement_velocity);
1644         }
1645
1646         // update the onground flag if appropriate
1647         if (cl.movement_predicted)
1648         {
1649                 // when predicted we simply set the flag according to the UpdateStatus
1650                 cl.onground = s.onground;
1651         }
1652         else
1653         {
1654                 // when not predicted, cl.onground is cleared by cl_parse.c each time
1655                 // an update packet is received, but can be forced on here to hide
1656                 // server inconsistencies in the onground flag
1657                 // (which mostly occur when stepping up stairs at very high framerates
1658                 //  where after the step up the move continues forward and not
1659                 //  downward so the ground is not detected)
1660                 //
1661                 // such onground inconsistencies can cause jittery gun bobbing and
1662                 // stair smoothing, so we set onground if UpdateStatus says so
1663                 if (s.onground)
1664                         cl.onground = true;
1665         }
1666 }
1667
1668 static void QW_MSG_WriteDeltaUsercmd(sizebuf_t *buf, usercmd_t *from, usercmd_t *to)
1669 {
1670         int bits;
1671
1672         bits = 0;
1673         if (to->viewangles[0] != from->viewangles[0])
1674                 bits |= QW_CM_ANGLE1;
1675         if (to->viewangles[1] != from->viewangles[1])
1676                 bits |= QW_CM_ANGLE2;
1677         if (to->viewangles[2] != from->viewangles[2])
1678                 bits |= QW_CM_ANGLE3;
1679         if (to->forwardmove != from->forwardmove)
1680                 bits |= QW_CM_FORWARD;
1681         if (to->sidemove != from->sidemove)
1682                 bits |= QW_CM_SIDE;
1683         if (to->upmove != from->upmove)
1684                 bits |= QW_CM_UP;
1685         if (to->buttons != from->buttons)
1686                 bits |= QW_CM_BUTTONS;
1687         if (to->impulse != from->impulse)
1688                 bits |= QW_CM_IMPULSE;
1689
1690         MSG_WriteByte(buf, bits);
1691         if (bits & QW_CM_ANGLE1)
1692                 MSG_WriteAngle16i(buf, to->viewangles[0]);
1693         if (bits & QW_CM_ANGLE2)
1694                 MSG_WriteAngle16i(buf, to->viewangles[1]);
1695         if (bits & QW_CM_ANGLE3)
1696                 MSG_WriteAngle16i(buf, to->viewangles[2]);
1697         if (bits & QW_CM_FORWARD)
1698                 MSG_WriteShort(buf, (short) to->forwardmove);
1699         if (bits & QW_CM_SIDE)
1700                 MSG_WriteShort(buf, (short) to->sidemove);
1701         if (bits & QW_CM_UP)
1702                 MSG_WriteShort(buf, (short) to->upmove);
1703         if (bits & QW_CM_BUTTONS)
1704                 MSG_WriteByte(buf, to->buttons);
1705         if (bits & QW_CM_IMPULSE)
1706                 MSG_WriteByte(buf, to->impulse);
1707         MSG_WriteByte(buf, to->msec);
1708 }
1709
1710 void CL_NewFrameReceived(int num)
1711 {
1712         if (developer_networkentities.integer >= 10)
1713                 Con_Printf("recv: svc_entities %i\n", num);
1714         cl.latestframenums[cl.latestframenumsposition] = num;
1715         cl.latestsendnums[cl.latestframenumsposition] = cl.cmd.sequence;
1716         cl.latestframenumsposition = (cl.latestframenumsposition + 1) % LATESTFRAMENUMS;
1717 }
1718
1719 void CL_RotateMoves(const matrix4x4_t *m)
1720 {
1721         // rotate viewangles in all previous moves
1722         vec3_t v;
1723         vec3_t f, r, u;
1724         int i;
1725         for (i = 0;i < CL_MAX_USERCMDS;i++)
1726         {
1727                 if (cl.movecmd[i].sequence > cls.servermovesequence)
1728                 {
1729                         usercmd_t *c = &cl.movecmd[i];
1730                         AngleVectors(c->viewangles, f, r, u);
1731                         Matrix4x4_Transform(m, f, v); VectorCopy(v, f);
1732                         Matrix4x4_Transform(m, u, v); VectorCopy(v, u);
1733                         AnglesFromVectors(c->viewangles, f, u, false);
1734                 }
1735         }
1736 }
1737
1738 /*
1739 ==============
1740 CL_SendMove
1741 ==============
1742 */
1743 usercmd_t nullcmd; // for delta compression of qw moves
1744 void CL_SendMove(void)
1745 {
1746         int i, j, packetloss;
1747         int checksumindex;
1748         int bits;
1749         int maxusercmds;
1750         usercmd_t *cmd;
1751         sizebuf_t buf;
1752         unsigned char data[1024];
1753         double packettime;
1754         int msecdelta;
1755         qboolean quemove;
1756         qboolean important;
1757
1758         // if playing a demo, do nothing
1759         if (!cls.netcon)
1760                 return;
1761
1762         // we don't que moves during a lag spike (potential network timeout)
1763         quemove = realtime - cl.last_received_message < cl_movement_nettimeout.value;
1764
1765         // we build up cl.cmd and then decide whether to send or not
1766         // we store this into cl.movecmd[0] for prediction each frame even if we
1767         // do not send, to make sure that prediction is instant
1768         cl.cmd.time = cl.time;
1769         cl.cmd.sequence = cls.netcon->outgoing_unreliable_sequence;
1770
1771         // set button bits
1772         // LordHavoc: added 6 new buttons and use and chat buttons, and prydon cursor active button
1773         bits = 0;
1774         if (in_attack.state   & 3) bits |=   1;
1775         if (in_jump.state     & 3) bits |=   2;
1776         if (in_button3.state  & 3) bits |=   4;
1777         if (in_button4.state  & 3) bits |=   8;
1778         if (in_button5.state  & 3) bits |=  16;
1779         if (in_button6.state  & 3) bits |=  32;
1780         if (in_button7.state  & 3) bits |=  64;
1781         if (in_button8.state  & 3) bits |= 128;
1782         if (in_use.state      & 3) bits |= 256;
1783         if (key_dest != key_game || key_consoleactive) bits |= 512;
1784         if (cl_prydoncursor.integer > 0) bits |= 1024;
1785         if (in_button9.state  & 3)  bits |=   2048;
1786         if (in_button10.state  & 3) bits |=   4096;
1787         if (in_button11.state  & 3) bits |=   8192;
1788         if (in_button12.state  & 3) bits |=  16384;
1789         if (in_button13.state  & 3) bits |=  32768;
1790         if (in_button14.state  & 3) bits |=  65536;
1791         if (in_button15.state  & 3) bits |= 131072;
1792         if (in_button16.state  & 3) bits |= 262144;
1793         // button bits 19-31 unused currently
1794         // rotate/zoom view serverside if PRYDON_CLIENTCURSOR cursor is at edge of screen
1795         if(cl_prydoncursor.integer > 0)
1796         {
1797                 if (cl.cmd.cursor_screen[0] <= -1) bits |= 8;
1798                 if (cl.cmd.cursor_screen[0] >=  1) bits |= 16;
1799                 if (cl.cmd.cursor_screen[1] <= -1) bits |= 32;
1800                 if (cl.cmd.cursor_screen[1] >=  1) bits |= 64;
1801         }
1802
1803         // set buttons and impulse
1804         cl.cmd.buttons = bits;
1805         cl.cmd.impulse = in_impulse;
1806
1807         // set viewangles
1808         VectorCopy(cl.viewangles, cl.cmd.viewangles);
1809
1810         msecdelta = (int)(floor(cl.cmd.time * 1000) - floor(cl.movecmd[1].time * 1000));
1811         cl.cmd.msec = (unsigned char)bound(0, msecdelta, 255);
1812         // ridiculous value rejection (matches qw)
1813         if (cl.cmd.msec > 250)
1814                 cl.cmd.msec = 100;
1815         cl.cmd.frametime = cl.cmd.msec * (1.0 / 1000.0);
1816
1817         cl.cmd.predicted = cl_movement.integer != 0;
1818
1819         // movement is set by input code (forwardmove/sidemove/upmove)
1820         // always dump the first two moves, because they may contain leftover inputs from the last level
1821         if (cl.cmd.sequence <= 2)
1822                 cl.cmd.forwardmove = cl.cmd.sidemove = cl.cmd.upmove = cl.cmd.impulse = cl.cmd.buttons = 0;
1823
1824         cl.cmd.jump = (cl.cmd.buttons & 2) != 0;
1825         cl.cmd.crouch = 0;
1826         switch (cls.protocol)
1827         {
1828         case PROTOCOL_QUAKEWORLD:
1829         case PROTOCOL_QUAKE:
1830         case PROTOCOL_QUAKEDP:
1831         case PROTOCOL_NEHAHRAMOVIE:
1832         case PROTOCOL_NEHAHRABJP:
1833         case PROTOCOL_NEHAHRABJP2:
1834         case PROTOCOL_NEHAHRABJP3:
1835         case PROTOCOL_DARKPLACES1:
1836         case PROTOCOL_DARKPLACES2:
1837         case PROTOCOL_DARKPLACES3:
1838         case PROTOCOL_DARKPLACES4:
1839         case PROTOCOL_DARKPLACES5:
1840                 break;
1841         case PROTOCOL_DARKPLACES6:
1842         case PROTOCOL_DARKPLACES7:
1843                 // FIXME: cl.cmd.buttons & 16 is +button5, Nexuiz/Xonotic specific
1844                 cl.cmd.crouch = (cl.cmd.buttons & 16) != 0;
1845                 break;
1846         case PROTOCOL_UNKNOWN:
1847                 break;
1848         }
1849
1850         if (quemove)
1851                 cl.movecmd[0] = cl.cmd;
1852
1853         // don't predict more than 200fps
1854         if (realtime >= cl.lastpackettime + 0.005)
1855                 cl.movement_replay = true; // redo the prediction
1856
1857         // now decide whether to actually send this move
1858         // (otherwise it is only for prediction)
1859
1860         // don't send too often or else network connections can get clogged by a
1861         // high renderer framerate
1862         packettime = 1.0 / bound(1, cl_netfps.value, 1000);
1863         if (cl.movevars_timescale && cl.movevars_ticrate)
1864         {
1865                 float maxtic = cl.movevars_ticrate / cl.movevars_timescale;
1866                 packettime = min(packettime, maxtic);
1867         }
1868
1869         // do not send 0ms packets because they mess up physics
1870         if(cl.cmd.msec == 0 && cl.time > cl.oldtime && (cls.protocol == PROTOCOL_QUAKEWORLD || cls.signon == SIGNONS))
1871                 return;
1872         // always send if buttons changed or an impulse is pending
1873         // even if it violates the rate limit!
1874         important = (cl.cmd.impulse || (cl_netimmediatebuttons.integer && cl.cmd.buttons != cl.movecmd[1].buttons));
1875         // don't send too often (cl_netfps)
1876         if (!important && realtime < cl.lastpackettime + packettime)
1877                 return;
1878         // don't choke the connection with packets (obey rate limit)
1879         // it is important that this check be last, because it adds a new
1880         // frame to the shownetgraph output and any cancelation after this
1881         // will produce a nasty spike-like look to the netgraph
1882         // we also still send if it is important
1883         if (!NetConn_CanSend(cls.netcon) && !important)
1884                 return;
1885         // try to round off the lastpackettime to a multiple of the packet interval
1886         // (this causes it to emit packets at a steady beat)
1887         if (packettime > 0)
1888                 cl.lastpackettime = floor(realtime / packettime) * packettime;
1889         else
1890                 cl.lastpackettime = realtime;
1891
1892         buf.maxsize = sizeof(data);
1893         buf.cursize = 0;
1894         buf.data = data;
1895
1896         // send the movement message
1897         // PROTOCOL_QUAKE        clc_move = 16 bytes total
1898         // PROTOCOL_QUAKEDP      clc_move = 16 bytes total
1899         // PROTOCOL_NEHAHRAMOVIE clc_move = 16 bytes total
1900         // PROTOCOL_DARKPLACES1  clc_move = 19 bytes total
1901         // PROTOCOL_DARKPLACES2  clc_move = 25 bytes total
1902         // PROTOCOL_DARKPLACES3  clc_move = 25 bytes total
1903         // PROTOCOL_DARKPLACES4  clc_move = 19 bytes total
1904         // PROTOCOL_DARKPLACES5  clc_move = 19 bytes total
1905         // PROTOCOL_DARKPLACES6  clc_move = 52 bytes total
1906         // PROTOCOL_DARKPLACES7  clc_move = 56 bytes total per move (can be up to 16 moves)
1907         // PROTOCOL_QUAKEWORLD   clc_move = 34 bytes total (typically, but can reach 43 bytes, or even 49 bytes with roll)
1908
1909         // set prydon cursor info
1910         CL_UpdatePrydonCursor();
1911
1912         if (cls.protocol == PROTOCOL_QUAKEWORLD || cls.signon == SIGNONS)
1913         {
1914                 switch (cls.protocol)
1915                 {
1916                 case PROTOCOL_QUAKEWORLD:
1917                         MSG_WriteByte(&buf, qw_clc_move);
1918                         // save the position for a checksum byte
1919                         checksumindex = buf.cursize;
1920                         MSG_WriteByte(&buf, 0);
1921                         // packet loss percentage
1922                         for (j = 0, packetloss = 0;j < NETGRAPH_PACKETS;j++)
1923                                 if (cls.netcon->incoming_netgraph[j].unreliablebytes == NETGRAPH_LOSTPACKET)
1924                                         packetloss++;
1925                         packetloss = packetloss * 100 / NETGRAPH_PACKETS;
1926                         MSG_WriteByte(&buf, packetloss);
1927                         // write most recent 3 moves
1928                         QW_MSG_WriteDeltaUsercmd(&buf, &nullcmd, &cl.movecmd[2]);
1929                         QW_MSG_WriteDeltaUsercmd(&buf, &cl.movecmd[2], &cl.movecmd[1]);
1930                         QW_MSG_WriteDeltaUsercmd(&buf, &cl.movecmd[1], &cl.cmd);
1931                         // calculate the checksum
1932                         buf.data[checksumindex] = COM_BlockSequenceCRCByteQW(buf.data + checksumindex + 1, buf.cursize - checksumindex - 1, cls.netcon->outgoing_unreliable_sequence);
1933                         // if delta compression history overflows, request no delta
1934                         if (cls.netcon->outgoing_unreliable_sequence - cl.qw_validsequence >= QW_UPDATE_BACKUP-1)
1935                                 cl.qw_validsequence = 0;
1936                         // request delta compression if appropriate
1937                         if (cl.qw_validsequence && !cl_nodelta.integer && cls.state == ca_connected && !cls.demorecording)
1938                         {
1939                                 cl.qw_deltasequence[cls.netcon->outgoing_unreliable_sequence & QW_UPDATE_MASK] = cl.qw_validsequence;
1940                                 MSG_WriteByte(&buf, qw_clc_delta);
1941                                 MSG_WriteByte(&buf, cl.qw_validsequence & 255);
1942                         }
1943                         else
1944                                 cl.qw_deltasequence[cls.netcon->outgoing_unreliable_sequence & QW_UPDATE_MASK] = -1;
1945                         break;
1946                 case PROTOCOL_QUAKE:
1947                 case PROTOCOL_QUAKEDP:
1948                 case PROTOCOL_NEHAHRAMOVIE:
1949                 case PROTOCOL_NEHAHRABJP:
1950                 case PROTOCOL_NEHAHRABJP2:
1951                 case PROTOCOL_NEHAHRABJP3:
1952                         // 5 bytes
1953                         MSG_WriteByte (&buf, clc_move);
1954                         MSG_WriteFloat (&buf, cl.cmd.time); // last server packet time
1955                         // 3 bytes (6 bytes in proquake)
1956                         if (cls.proquake_servermod == 1) // MOD_PROQUAKE
1957                         {
1958                                 for (i = 0;i < 3;i++)
1959                                         MSG_WriteAngle16i (&buf, cl.cmd.viewangles[i]);
1960                         }
1961                         else
1962                         {
1963                                 for (i = 0;i < 3;i++)
1964                                         MSG_WriteAngle8i (&buf, cl.cmd.viewangles[i]);
1965                         }
1966                         // 6 bytes
1967                         MSG_WriteCoord16i (&buf, cl.cmd.forwardmove);
1968                         MSG_WriteCoord16i (&buf, cl.cmd.sidemove);
1969                         MSG_WriteCoord16i (&buf, cl.cmd.upmove);
1970                         // 2 bytes
1971                         MSG_WriteByte (&buf, cl.cmd.buttons);
1972                         MSG_WriteByte (&buf, cl.cmd.impulse);
1973                         break;
1974                 case PROTOCOL_DARKPLACES2:
1975                 case PROTOCOL_DARKPLACES3:
1976                         // 5 bytes
1977                         MSG_WriteByte (&buf, clc_move);
1978                         MSG_WriteFloat (&buf, cl.cmd.time); // last server packet time
1979                         // 12 bytes
1980                         for (i = 0;i < 3;i++)
1981                                 MSG_WriteAngle32f (&buf, cl.cmd.viewangles[i]);
1982                         // 6 bytes
1983                         MSG_WriteCoord16i (&buf, cl.cmd.forwardmove);
1984                         MSG_WriteCoord16i (&buf, cl.cmd.sidemove);
1985                         MSG_WriteCoord16i (&buf, cl.cmd.upmove);
1986                         // 2 bytes
1987                         MSG_WriteByte (&buf, cl.cmd.buttons);
1988                         MSG_WriteByte (&buf, cl.cmd.impulse);
1989                         break;
1990                 case PROTOCOL_DARKPLACES1:
1991                 case PROTOCOL_DARKPLACES4:
1992                 case PROTOCOL_DARKPLACES5:
1993                         // 5 bytes
1994                         MSG_WriteByte (&buf, clc_move);
1995                         MSG_WriteFloat (&buf, cl.cmd.time); // last server packet time
1996                         // 6 bytes
1997                         for (i = 0;i < 3;i++)
1998                                 MSG_WriteAngle16i (&buf, cl.cmd.viewangles[i]);
1999                         // 6 bytes
2000                         MSG_WriteCoord16i (&buf, cl.cmd.forwardmove);
2001                         MSG_WriteCoord16i (&buf, cl.cmd.sidemove);
2002                         MSG_WriteCoord16i (&buf, cl.cmd.upmove);
2003                         // 2 bytes
2004                         MSG_WriteByte (&buf, cl.cmd.buttons);
2005                         MSG_WriteByte (&buf, cl.cmd.impulse);
2006                 case PROTOCOL_DARKPLACES6:
2007                 case PROTOCOL_DARKPLACES7:
2008                         // set the maxusercmds variable to limit how many should be sent
2009                         maxusercmds = bound(1, cl_netrepeatinput.integer + 1, min(3, CL_MAX_USERCMDS));
2010                         // when movement prediction is off, there's not much point in repeating old input as it will just be ignored
2011                         if (!cl.cmd.predicted)
2012                                 maxusercmds = 1;
2013
2014                         // send the latest moves in order, the old ones will be
2015                         // ignored by the server harmlessly, however if the previous
2016                         // packets were lost these moves will be used
2017                         //
2018                         // this reduces packet loss impact on gameplay.
2019                         for (j = 0, cmd = &cl.movecmd[maxusercmds-1];j < maxusercmds;j++, cmd--)
2020                         {
2021                                 // don't repeat any stale moves
2022                                 if (cmd->sequence && cmd->sequence < cls.servermovesequence)
2023                                         continue;
2024                                 // 5/9 bytes
2025                                 MSG_WriteByte (&buf, clc_move);
2026                                 if (cls.protocol != PROTOCOL_DARKPLACES6)
2027                                         MSG_WriteLong (&buf, cmd->predicted ? cmd->sequence : 0);
2028                                 MSG_WriteFloat (&buf, cmd->time); // last server packet time
2029                                 // 6 bytes
2030                                 for (i = 0;i < 3;i++)
2031                                         MSG_WriteAngle16i (&buf, cmd->viewangles[i]);
2032                                 // 6 bytes
2033                                 MSG_WriteCoord16i (&buf, cmd->forwardmove);
2034                                 MSG_WriteCoord16i (&buf, cmd->sidemove);
2035                                 MSG_WriteCoord16i (&buf, cmd->upmove);
2036                                 // 5 bytes
2037                                 MSG_WriteLong (&buf, cmd->buttons);
2038                                 MSG_WriteByte (&buf, cmd->impulse);
2039                                 // PRYDON_CLIENTCURSOR
2040                                 // 30 bytes
2041                                 MSG_WriteShort (&buf, (short)(cmd->cursor_screen[0] * 32767.0f));
2042                                 MSG_WriteShort (&buf, (short)(cmd->cursor_screen[1] * 32767.0f));
2043                                 MSG_WriteFloat (&buf, cmd->cursor_start[0]);
2044                                 MSG_WriteFloat (&buf, cmd->cursor_start[1]);
2045                                 MSG_WriteFloat (&buf, cmd->cursor_start[2]);
2046                                 MSG_WriteFloat (&buf, cmd->cursor_impact[0]);
2047                                 MSG_WriteFloat (&buf, cmd->cursor_impact[1]);
2048                                 MSG_WriteFloat (&buf, cmd->cursor_impact[2]);
2049                                 MSG_WriteShort (&buf, cmd->cursor_entitynumber);
2050                         }
2051                         break;
2052                 case PROTOCOL_UNKNOWN:
2053                         break;
2054                 }
2055         }
2056
2057         if (cls.protocol != PROTOCOL_QUAKEWORLD && buf.cursize)
2058         {
2059                 // ack entity frame numbers received since the last input was sent
2060                 // (redundent to improve handling of client->server packet loss)
2061                 // if cl_netrepeatinput is 1 and client framerate matches server
2062                 // framerate, this is 10 bytes, if client framerate is lower this
2063                 // will be more...
2064                 unsigned int oldsequence = cl.cmd.sequence;
2065                 unsigned int delta = bound(1, cl_netrepeatinput.integer + 1, 3);
2066                 if (oldsequence > delta)
2067                         oldsequence = oldsequence - delta;
2068                 else
2069                         oldsequence = 1;
2070                 for (i = 0;i < LATESTFRAMENUMS;i++)
2071                 {
2072                         j = (cl.latestframenumsposition + i) % LATESTFRAMENUMS;
2073                         if (cl.latestsendnums[j] >= oldsequence)
2074                         {
2075                                 if (developer_networkentities.integer >= 10)
2076                                         Con_Printf("send clc_ackframe %i\n", cl.latestframenums[j]);
2077                                 MSG_WriteByte(&buf, clc_ackframe);
2078                                 MSG_WriteLong(&buf, cl.latestframenums[j]);
2079                         }
2080                 }
2081         }
2082
2083         // PROTOCOL_DARKPLACES6 = 67 bytes per packet
2084         // PROTOCOL_DARKPLACES7 = 71 bytes per packet
2085
2086         // acknowledge any recently received data blocks
2087         for (i = 0;i < CL_MAX_DOWNLOADACKS && (cls.dp_downloadack[i].start || cls.dp_downloadack[i].size);i++)
2088         {
2089                 MSG_WriteByte(&buf, clc_ackdownloaddata);
2090                 MSG_WriteLong(&buf, cls.dp_downloadack[i].start);
2091                 MSG_WriteShort(&buf, cls.dp_downloadack[i].size);
2092                 cls.dp_downloadack[i].start = 0;
2093                 cls.dp_downloadack[i].size = 0;
2094         }
2095
2096         // send the reliable message (forwarded commands) if there is one
2097         if (buf.cursize || cls.netcon->message.cursize)
2098                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, max(20*(buf.cursize+40), cl_rate.integer), cl_rate_burstsize.integer, false);
2099
2100         if (quemove)
2101         {
2102                 // update the cl.movecmd array which holds the most recent moves,
2103                 // because we now need a new slot for the next input
2104                 for (i = CL_MAX_USERCMDS - 1;i >= 1;i--)
2105                         cl.movecmd[i] = cl.movecmd[i-1];
2106                 cl.movecmd[0].msec = 0;
2107                 cl.movecmd[0].frametime = 0;
2108         }
2109
2110         // clear button 'click' states
2111         in_attack.state  &= ~2;
2112         in_jump.state    &= ~2;
2113         in_button3.state &= ~2;
2114         in_button4.state &= ~2;
2115         in_button5.state &= ~2;
2116         in_button6.state &= ~2;
2117         in_button7.state &= ~2;
2118         in_button8.state &= ~2;
2119         in_use.state     &= ~2;
2120         in_button9.state  &= ~2;
2121         in_button10.state &= ~2;
2122         in_button11.state &= ~2;
2123         in_button12.state &= ~2;
2124         in_button13.state &= ~2;
2125         in_button14.state &= ~2;
2126         in_button15.state &= ~2;
2127         in_button16.state &= ~2;
2128         // clear impulse
2129         in_impulse = 0;
2130
2131         if (cls.netcon->message.overflowed)
2132         {
2133                 Con_Print("CL_SendMove: lost server connection\n");
2134                 CL_Disconnect();
2135                 SV_LockThreadMutex();
2136                 Host_ShutdownServer();
2137                 SV_UnlockThreadMutex();
2138         }
2139 }
2140
2141 /*
2142 ============
2143 CL_InitInput
2144 ============
2145 */
2146 void CL_InitInput (void)
2147 {
2148         Cmd_AddCommand ("+moveup",IN_UpDown, "swim upward");
2149         Cmd_AddCommand ("-moveup",IN_UpUp, "stop swimming upward");
2150         Cmd_AddCommand ("+movedown",IN_DownDown, "swim downward");
2151         Cmd_AddCommand ("-movedown",IN_DownUp, "stop swimming downward");
2152         Cmd_AddCommand ("+left",IN_LeftDown, "turn left");
2153         Cmd_AddCommand ("-left",IN_LeftUp, "stop turning left");
2154         Cmd_AddCommand ("+right",IN_RightDown, "turn right");
2155         Cmd_AddCommand ("-right",IN_RightUp, "stop turning right");
2156         Cmd_AddCommand ("+forward",IN_ForwardDown, "move forward");
2157         Cmd_AddCommand ("-forward",IN_ForwardUp, "stop moving forward");
2158         Cmd_AddCommand ("+back",IN_BackDown, "move backward");
2159         Cmd_AddCommand ("-back",IN_BackUp, "stop moving backward");
2160         Cmd_AddCommand ("+lookup", IN_LookupDown, "look upward");
2161         Cmd_AddCommand ("-lookup", IN_LookupUp, "stop looking upward");
2162         Cmd_AddCommand ("+lookdown", IN_LookdownDown, "look downward");
2163         Cmd_AddCommand ("-lookdown", IN_LookdownUp, "stop looking downward");
2164         Cmd_AddCommand ("+strafe", IN_StrafeDown, "activate strafing mode (move instead of turn)");
2165         Cmd_AddCommand ("-strafe", IN_StrafeUp, "deactivate strafing mode");
2166         Cmd_AddCommand ("+moveleft", IN_MoveleftDown, "strafe left");
2167         Cmd_AddCommand ("-moveleft", IN_MoveleftUp, "stop strafing left");
2168         Cmd_AddCommand ("+moveright", IN_MoverightDown, "strafe right");
2169         Cmd_AddCommand ("-moveright", IN_MoverightUp, "stop strafing right");
2170         Cmd_AddCommand ("+speed", IN_SpeedDown, "activate run mode (faster movement and turning)");
2171         Cmd_AddCommand ("-speed", IN_SpeedUp, "deactivate run mode");
2172         Cmd_AddCommand ("+attack", IN_AttackDown, "begin firing");
2173         Cmd_AddCommand ("-attack", IN_AttackUp, "stop firing");
2174         Cmd_AddCommand ("+jump", IN_JumpDown, "jump");
2175         Cmd_AddCommand ("-jump", IN_JumpUp, "end jump (so you can jump again)");
2176         Cmd_AddCommand ("impulse", IN_Impulse, "send an impulse number to server (select weapon, use item, etc)");
2177         Cmd_AddCommand ("+klook", IN_KLookDown, "activate keyboard looking mode, do not recenter view");
2178         Cmd_AddCommand ("-klook", IN_KLookUp, "deactivate keyboard looking mode");
2179         Cmd_AddCommand ("+mlook", IN_MLookDown, "activate mouse looking mode, do not recenter view");
2180         Cmd_AddCommand ("-mlook", IN_MLookUp, "deactivate mouse looking mode");
2181
2182         // LordHavoc: added use button
2183         Cmd_AddCommand ("+use", IN_UseDown, "use something (may be used by some mods)");
2184         Cmd_AddCommand ("-use", IN_UseUp, "stop using something");
2185
2186         // LordHavoc: added 6 new buttons
2187         Cmd_AddCommand ("+button3", IN_Button3Down, "activate button3 (behavior depends on mod)");
2188         Cmd_AddCommand ("-button3", IN_Button3Up, "deactivate button3");
2189         Cmd_AddCommand ("+button4", IN_Button4Down, "activate button4 (behavior depends on mod)");
2190         Cmd_AddCommand ("-button4", IN_Button4Up, "deactivate button4");
2191         Cmd_AddCommand ("+button5", IN_Button5Down, "activate button5 (behavior depends on mod)");
2192         Cmd_AddCommand ("-button5", IN_Button5Up, "deactivate button5");
2193         Cmd_AddCommand ("+button6", IN_Button6Down, "activate button6 (behavior depends on mod)");
2194         Cmd_AddCommand ("-button6", IN_Button6Up, "deactivate button6");
2195         Cmd_AddCommand ("+button7", IN_Button7Down, "activate button7 (behavior depends on mod)");
2196         Cmd_AddCommand ("-button7", IN_Button7Up, "deactivate button7");
2197         Cmd_AddCommand ("+button8", IN_Button8Down, "activate button8 (behavior depends on mod)");
2198         Cmd_AddCommand ("-button8", IN_Button8Up, "deactivate button8");
2199         Cmd_AddCommand ("+button9", IN_Button9Down, "activate button9 (behavior depends on mod)");
2200         Cmd_AddCommand ("-button9", IN_Button9Up, "deactivate button9");
2201         Cmd_AddCommand ("+button10", IN_Button10Down, "activate button10 (behavior depends on mod)");
2202         Cmd_AddCommand ("-button10", IN_Button10Up, "deactivate button10");
2203         Cmd_AddCommand ("+button11", IN_Button11Down, "activate button11 (behavior depends on mod)");
2204         Cmd_AddCommand ("-button11", IN_Button11Up, "deactivate button11");
2205         Cmd_AddCommand ("+button12", IN_Button12Down, "activate button12 (behavior depends on mod)");
2206         Cmd_AddCommand ("-button12", IN_Button12Up, "deactivate button12");
2207         Cmd_AddCommand ("+button13", IN_Button13Down, "activate button13 (behavior depends on mod)");
2208         Cmd_AddCommand ("-button13", IN_Button13Up, "deactivate button13");
2209         Cmd_AddCommand ("+button14", IN_Button14Down, "activate button14 (behavior depends on mod)");
2210         Cmd_AddCommand ("-button14", IN_Button14Up, "deactivate button14");
2211         Cmd_AddCommand ("+button15", IN_Button15Down, "activate button15 (behavior depends on mod)");
2212         Cmd_AddCommand ("-button15", IN_Button15Up, "deactivate button15");
2213         Cmd_AddCommand ("+button16", IN_Button16Down, "activate button16 (behavior depends on mod)");
2214         Cmd_AddCommand ("-button16", IN_Button16Up, "deactivate button16");
2215
2216         // LordHavoc: added bestweapon command
2217         Cmd_AddCommand ("bestweapon", IN_BestWeapon, "send an impulse number to server to select the first usable weapon out of several (example: 8 7 6 5 4 3 2 1)");
2218 #if 0
2219         Cmd_AddCommand ("cycleweapon", IN_CycleWeapon, "send an impulse number to server to select the next usable weapon out of several (example: 9 4 8) if you are holding one of these, and choose the first one if you are holding none of these");
2220 #endif
2221         Cmd_AddCommand ("register_bestweapon", IN_BestWeapon_Register_f, "(for QC usage only) change weapon parameters to be used by bestweapon; stuffcmd this in ClientConnect");
2222
2223         Cvar_RegisterVariable(&cl_movecliptokeyboard);
2224         Cvar_RegisterVariable(&cl_movement);
2225         Cvar_RegisterVariable(&cl_movement_replay);
2226         Cvar_RegisterVariable(&cl_movement_nettimeout);
2227         Cvar_RegisterVariable(&cl_movement_minping);
2228         Cvar_RegisterVariable(&cl_movement_track_canjump);
2229         Cvar_RegisterVariable(&cl_movement_maxspeed);
2230         Cvar_RegisterVariable(&cl_movement_maxairspeed);
2231         Cvar_RegisterVariable(&cl_movement_stopspeed);
2232         Cvar_RegisterVariable(&cl_movement_friction);
2233         Cvar_RegisterVariable(&cl_movement_wallfriction);
2234         Cvar_RegisterVariable(&cl_movement_waterfriction);
2235         Cvar_RegisterVariable(&cl_movement_edgefriction);
2236         Cvar_RegisterVariable(&cl_movement_stepheight);
2237         Cvar_RegisterVariable(&cl_movement_accelerate);
2238         Cvar_RegisterVariable(&cl_movement_airaccelerate);
2239         Cvar_RegisterVariable(&cl_movement_wateraccelerate);
2240         Cvar_RegisterVariable(&cl_movement_jumpvelocity);
2241         Cvar_RegisterVariable(&cl_movement_airaccel_qw);
2242         Cvar_RegisterVariable(&cl_movement_airaccel_sideways_friction);
2243
2244         Cvar_RegisterVariable(&in_pitch_min);
2245         Cvar_RegisterVariable(&in_pitch_max);
2246         Cvar_RegisterVariable(&m_filter);
2247         Cvar_RegisterVariable(&m_accelerate);
2248         Cvar_RegisterVariable(&m_accelerate_minspeed);
2249         Cvar_RegisterVariable(&m_accelerate_maxspeed);
2250         Cvar_RegisterVariable(&m_accelerate_filter);
2251
2252         Cvar_RegisterVariable(&cl_netfps);
2253         Cvar_RegisterVariable(&cl_netrepeatinput);
2254         Cvar_RegisterVariable(&cl_netimmediatebuttons);
2255
2256         Cvar_RegisterVariable(&cl_nodelta);
2257
2258         Cvar_RegisterVariable(&cl_csqc_generatemousemoveevents);
2259 }
2260