now sends player physics variables as stats, including slowmo, gravity,
[xonotic/darkplaces.git] / sv_user.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 // sv_user.c -- server code for moving users
21
22 #include "quakedef.h"
23 #define DEBUGMOVES 0
24
25 cvar_t sv_edgefriction = {0, "edgefriction", "2", "how much you slow down when nearing a ledge you might fall off"};
26 cvar_t sv_idealpitchscale = {0, "sv_idealpitchscale","0.8", "how much to look up/down slopes and stairs when not using freelook"};
27 cvar_t sv_maxspeed = {CVAR_NOTIFY, "sv_maxspeed", "320", "maximum speed a player can accelerate to when on ground (can be exceeded by tricks)"};
28 cvar_t sv_maxairspeed = {0, "sv_maxairspeed", "30", "maximum speed a player can accelerate to when airborn (note that it is possible to completely stop by moving the opposite direction)"};
29 cvar_t sv_accelerate = {0, "sv_accelerate", "10", "rate at which a player accelerates to sv_maxspeed"};
30 cvar_t sv_airaccelerate = {0, "sv_airaccelerate", "-1", "rate at which a player accelerates to sv_maxairspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
31 cvar_t sv_wateraccelerate = {0, "sv_wateraccelerate", "-1", "rate at which a player accelerates to sv_maxspeed while in the air, if less than 0 the sv_accelerate variable is used instead"};
32 cvar_t sv_jumpvelocity = {0, "sv_jumpvelocity", "270", "cvar that can be used by QuakeC code for jump velocity"};
33 cvar_t sv_airaccel_qw = {0, "sv_airaccelerate", "1", "ratio of QW-style air control as opposed to simple acceleration"};
34 cvar_t sv_airaccel_sideways_friction = {0, "sv_airaccelerate", "", "anti-sideways movement stabilization (reduces speed gain when zigzagging)"};
35 cvar_t sv_clmovement_enable = {0, "sv_clmovement_enable", "1", "whether to allow clients to use cl_movement prediction, which can cause choppy movement on the server which may annoy other players"};
36 cvar_t sv_clmovement_minping = {0, "sv_clmovement_minping", "0", "if client ping is below this time in milliseconds, then their ability to use cl_movement prediction is disabled for a while (as they don't need it)"};
37 cvar_t sv_clmovement_minping_disabletime = {0, "sv_clmovement_minping_disabletime", "1000", "when client falls below minping, disable their prediction for this many milliseconds (should be at least 1000 or else their prediction may turn on/off frequently)"};
38 cvar_t sv_clmovement_waitforinput = {0, "sv_clmovement_waitforinput", "16", "when a client does not send input for this many frames, force them to move anyway (unlike QuakeWorld)"};
39
40 static usercmd_t cmd;
41
42
43 /*
44 ===============
45 SV_SetIdealPitch
46 ===============
47 */
48 #define MAX_FORWARD     6
49 void SV_SetIdealPitch (void)
50 {
51         float   angleval, sinval, cosval, step, dir;
52         trace_t tr;
53         vec3_t  top, bottom;
54         float   z[MAX_FORWARD];
55         int             i, j;
56         int             steps;
57
58         if (!((int)host_client->edict->fields.server->flags & FL_ONGROUND))
59                 return;
60
61         angleval = host_client->edict->fields.server->angles[YAW] * M_PI*2 / 360;
62         sinval = sin(angleval);
63         cosval = cos(angleval);
64
65         for (i=0 ; i<MAX_FORWARD ; i++)
66         {
67                 top[0] = host_client->edict->fields.server->origin[0] + cosval*(i+3)*12;
68                 top[1] = host_client->edict->fields.server->origin[1] + sinval*(i+3)*12;
69                 top[2] = host_client->edict->fields.server->origin[2] + host_client->edict->fields.server->view_ofs[2];
70
71                 bottom[0] = top[0];
72                 bottom[1] = top[1];
73                 bottom[2] = top[2] - 160;
74
75                 tr = SV_Move (top, vec3_origin, vec3_origin, bottom, MOVE_NOMONSTERS, host_client->edict, SUPERCONTENTS_SOLID);
76                 // if looking at a wall, leave ideal the way is was
77                 if (tr.startsolid)
78                         return;
79
80                 // near a dropoff
81                 if (tr.fraction == 1)
82                         return;
83
84                 z[i] = top[2] + tr.fraction*(bottom[2]-top[2]);
85         }
86
87         dir = 0;
88         steps = 0;
89         for (j=1 ; j<i ; j++)
90         {
91                 step = z[j] - z[j-1];
92                 if (step > -ON_EPSILON && step < ON_EPSILON)
93                         continue;
94
95                 // mixed changes
96                 if (dir && ( step-dir > ON_EPSILON || step-dir < -ON_EPSILON ) )
97                         return;
98
99                 steps++;
100                 dir = step;
101         }
102
103         if (!dir)
104         {
105                 host_client->edict->fields.server->idealpitch = 0;
106                 return;
107         }
108
109         if (steps < 2)
110                 return;
111         host_client->edict->fields.server->idealpitch = -dir * sv_idealpitchscale.value;
112 }
113
114 static vec3_t wishdir, forward, right, up;
115 static float wishspeed;
116
117 static qboolean onground;
118
119 /*
120 ==================
121 SV_UserFriction
122
123 ==================
124 */
125 void SV_UserFriction (void)
126 {
127         float speed, newspeed, control, friction;
128         vec3_t start, stop;
129         trace_t trace;
130
131         speed = sqrt(host_client->edict->fields.server->velocity[0]*host_client->edict->fields.server->velocity[0]+host_client->edict->fields.server->velocity[1]*host_client->edict->fields.server->velocity[1]);
132         if (!speed)
133                 return;
134
135         // if the leading edge is over a dropoff, increase friction
136         start[0] = stop[0] = host_client->edict->fields.server->origin[0] + host_client->edict->fields.server->velocity[0]/speed*16;
137         start[1] = stop[1] = host_client->edict->fields.server->origin[1] + host_client->edict->fields.server->velocity[1]/speed*16;
138         start[2] = host_client->edict->fields.server->origin[2] + host_client->edict->fields.server->mins[2];
139         stop[2] = start[2] - 34;
140
141         trace = SV_Move (start, vec3_origin, vec3_origin, stop, MOVE_NOMONSTERS, host_client->edict, SV_GenericHitSuperContentsMask(host_client->edict));
142
143         if (trace.fraction == 1.0)
144                 friction = sv_friction.value*sv_edgefriction.value;
145         else
146                 friction = sv_friction.value;
147
148         // apply friction
149         control = speed < sv_stopspeed.value ? sv_stopspeed.value : speed;
150         newspeed = speed - sv.frametime*control*friction;
151
152         if (newspeed < 0)
153                 newspeed = 0;
154         else
155                 newspeed /= speed;
156
157         VectorScale(host_client->edict->fields.server->velocity, newspeed, host_client->edict->fields.server->velocity);
158 }
159
160 /*
161 ==============
162 SV_Accelerate
163 ==============
164 */
165 void SV_Accelerate (void)
166 {
167         int i;
168         float addspeed, accelspeed, currentspeed;
169
170         currentspeed = DotProduct (host_client->edict->fields.server->velocity, wishdir);
171         addspeed = wishspeed - currentspeed;
172         if (addspeed <= 0)
173                 return;
174         accelspeed = sv_accelerate.value*sv.frametime*wishspeed;
175         if (accelspeed > addspeed)
176                 accelspeed = addspeed;
177
178         for (i=0 ; i<3 ; i++)
179                 host_client->edict->fields.server->velocity[i] += accelspeed*wishdir[i];
180 }
181
182 void SV_AirAccelerate (vec3_t wishveloc)
183 {
184         int i;
185         float addspeed, wishspd, accelspeed, currentspeed;
186
187         wishspd = VectorNormalizeLength (wishveloc);
188         if (wishspd > sv_maxairspeed.value)
189                 wishspd = sv_maxairspeed.value;
190         currentspeed = DotProduct (host_client->edict->fields.server->velocity, wishveloc);
191         addspeed = wishspd - currentspeed;
192         if (addspeed <= 0)
193                 return;
194         accelspeed = (sv_airaccelerate.value < 0 ? sv_accelerate.value : sv_airaccelerate.value)*wishspeed * sv.frametime;
195         if (accelspeed > addspeed)
196                 accelspeed = addspeed;
197
198         for (i=0 ; i<3 ; i++)
199                 host_client->edict->fields.server->velocity[i] += accelspeed*wishveloc[i];
200 }
201
202
203 void DropPunchAngle (void)
204 {
205         float len;
206         prvm_eval_t *val;
207
208         len = VectorNormalizeLength (host_client->edict->fields.server->punchangle);
209
210         len -= 10*sv.frametime;
211         if (len < 0)
212                 len = 0;
213         VectorScale (host_client->edict->fields.server->punchangle, len, host_client->edict->fields.server->punchangle);
214
215         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.punchvector)))
216         {
217                 len = VectorNormalizeLength (val->vector);
218
219                 len -= 20*sv.frametime;
220                 if (len < 0)
221                         len = 0;
222                 VectorScale (val->vector, len, val->vector);
223         }
224 }
225
226 /*
227 ===================
228 SV_FreeMove
229 ===================
230 */
231 void SV_FreeMove (void)
232 {
233         int i;
234         float wishspeed;
235
236         AngleVectors (host_client->edict->fields.server->v_angle, forward, right, up);
237
238         for (i = 0; i < 3; i++)
239                 host_client->edict->fields.server->velocity[i] = forward[i] * cmd.forwardmove + right[i] * cmd.sidemove;
240
241         host_client->edict->fields.server->velocity[2] += cmd.upmove;
242
243         wishspeed = VectorLength(host_client->edict->fields.server->velocity);
244         if (wishspeed > sv_maxspeed.value)
245                 VectorScale(host_client->edict->fields.server->velocity, sv_maxspeed.value / wishspeed, host_client->edict->fields.server->velocity);
246 }
247
248 /*
249 ===================
250 SV_WaterMove
251
252 ===================
253 */
254 void SV_WaterMove (void)
255 {
256         int i;
257         vec3_t wishvel;
258         float speed, newspeed, wishspeed, addspeed, accelspeed, temp;
259
260         // user intentions
261         AngleVectors (host_client->edict->fields.server->v_angle, forward, right, up);
262
263         for (i=0 ; i<3 ; i++)
264                 wishvel[i] = forward[i]*cmd.forwardmove + right[i]*cmd.sidemove;
265
266         if (!cmd.forwardmove && !cmd.sidemove && !cmd.upmove)
267                 wishvel[2] -= 60;               // drift towards bottom
268         else
269                 wishvel[2] += cmd.upmove;
270
271         wishspeed = VectorLength(wishvel);
272         if (wishspeed > sv_maxspeed.value)
273         {
274                 temp = sv_maxspeed.value/wishspeed;
275                 VectorScale (wishvel, temp, wishvel);
276                 wishspeed = sv_maxspeed.value;
277         }
278         wishspeed *= 0.7;
279
280         // water friction
281         speed = VectorLength(host_client->edict->fields.server->velocity);
282         if (speed)
283         {
284                 newspeed = speed - sv.frametime * speed * (sv_waterfriction.value < 0 ? sv_friction.value : sv_waterfriction.value);
285                 if (newspeed < 0)
286                         newspeed = 0;
287                 temp = newspeed/speed;
288                 VectorScale(host_client->edict->fields.server->velocity, temp, host_client->edict->fields.server->velocity);
289         }
290         else
291                 newspeed = 0;
292
293         // water acceleration
294         if (!wishspeed)
295                 return;
296
297         addspeed = wishspeed - newspeed;
298         if (addspeed <= 0)
299                 return;
300
301         VectorNormalize (wishvel);
302         accelspeed = (sv_wateraccelerate.value < 0 ? sv_accelerate.value : sv_wateraccelerate.value) * wishspeed * sv.frametime;
303         if (accelspeed > addspeed)
304                 accelspeed = addspeed;
305
306         for (i=0 ; i<3 ; i++)
307                 host_client->edict->fields.server->velocity[i] += accelspeed * wishvel[i];
308 }
309
310 void SV_WaterJump (void)
311 {
312         if (sv.time > host_client->edict->fields.server->teleport_time || !host_client->edict->fields.server->waterlevel)
313         {
314                 host_client->edict->fields.server->flags = (int)host_client->edict->fields.server->flags & ~FL_WATERJUMP;
315                 host_client->edict->fields.server->teleport_time = 0;
316         }
317         host_client->edict->fields.server->velocity[0] = host_client->edict->fields.server->movedir[0];
318         host_client->edict->fields.server->velocity[1] = host_client->edict->fields.server->movedir[1];
319 }
320
321
322 /*
323 ===================
324 SV_AirMove
325
326 ===================
327 */
328 void SV_AirMove (void)
329 {
330         int i;
331         vec3_t wishvel;
332         float fmove, smove, temp;
333
334         // LordHavoc: correct quake movement speed bug when looking up/down
335         wishvel[0] = wishvel[2] = 0;
336         wishvel[1] = host_client->edict->fields.server->angles[1];
337         AngleVectors (wishvel, forward, right, up);
338
339         fmove = cmd.forwardmove;
340         smove = cmd.sidemove;
341
342 // hack to not let you back into teleporter
343         if (sv.time < host_client->edict->fields.server->teleport_time && fmove < 0)
344                 fmove = 0;
345
346         for (i=0 ; i<3 ; i++)
347                 wishvel[i] = forward[i]*fmove + right[i]*smove;
348
349         if ((int)host_client->edict->fields.server->movetype != MOVETYPE_WALK)
350                 wishvel[2] += cmd.upmove;
351
352         VectorCopy (wishvel, wishdir);
353         wishspeed = VectorNormalizeLength(wishdir);
354         if (wishspeed > sv_maxspeed.value)
355         {
356                 temp = sv_maxspeed.value/wishspeed;
357                 VectorScale (wishvel, temp, wishvel);
358                 wishspeed = sv_maxspeed.value;
359         }
360
361         if (host_client->edict->fields.server->movetype == MOVETYPE_NOCLIP)
362         {
363                 // noclip
364                 VectorCopy (wishvel, host_client->edict->fields.server->velocity);
365         }
366         else if (onground && (!sv_gameplayfix_qwplayerphysics.integer || !(host_client->edict->fields.server->button2 || !((int)host_client->edict->fields.server->flags & FL_JUMPRELEASED))))
367         {
368                 SV_UserFriction ();
369                 SV_Accelerate ();
370         }
371         else
372         {
373                 // not on ground, so little effect on velocity
374                 SV_AirAccelerate (wishvel);
375         }
376 }
377
378 /*
379 ===================
380 SV_ClientThink
381
382 the move fields specify an intended velocity in pix/sec
383 the angle fields specify an exact angular motion in degrees
384 ===================
385 */
386 extern cvar_t sv_playerphysicsqc;
387 void SV_ClientThink (void)
388 {
389         vec3_t v_angle;
390
391         SV_ApplyClientMove();
392         // make sure the velocity is sane (not a NaN)
393         SV_CheckVelocity(host_client->edict);
394
395         // LordHavoc: QuakeC replacement for SV_ClientThink (player movement)
396         if (prog->funcoffsets.SV_PlayerPhysics && sv_playerphysicsqc.integer)
397         {
398                 prog->globals.server->time = sv.time;
399                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
400                 PRVM_ExecuteProgram (prog->funcoffsets.SV_PlayerPhysics, "QC function SV_PlayerPhysics is missing");
401                 SV_CheckVelocity(host_client->edict);
402                 return;
403         }
404
405         if (host_client->edict->fields.server->movetype == MOVETYPE_NONE)
406                 return;
407
408         onground = (int)host_client->edict->fields.server->flags & FL_ONGROUND;
409
410         DropPunchAngle ();
411
412         // if dead, behave differently
413         if (host_client->edict->fields.server->health <= 0)
414                 return;
415
416         cmd = host_client->cmd;
417
418         // angles
419         // show 1/3 the pitch angle and all the roll angle
420         VectorAdd (host_client->edict->fields.server->v_angle, host_client->edict->fields.server->punchangle, v_angle);
421         host_client->edict->fields.server->angles[ROLL] = V_CalcRoll (host_client->edict->fields.server->angles, host_client->edict->fields.server->velocity)*4;
422         if (!host_client->edict->fields.server->fixangle)
423         {
424                 host_client->edict->fields.server->angles[PITCH] = -v_angle[PITCH]/3;
425                 host_client->edict->fields.server->angles[YAW] = v_angle[YAW];
426         }
427
428         if ( (int)host_client->edict->fields.server->flags & FL_WATERJUMP )
429         {
430                 SV_WaterJump ();
431                 SV_CheckVelocity(host_client->edict);
432                 return;
433         }
434
435         /*
436         // Player is (somehow) outside of the map, or flying, or noclipping
437         if (host_client->edict->fields.server->movetype != MOVETYPE_NOCLIP && (host_client->edict->fields.server->movetype == MOVETYPE_FLY || SV_TestEntityPosition (host_client->edict)))
438         //if (host_client->edict->fields.server->movetype == MOVETYPE_NOCLIP || host_client->edict->fields.server->movetype == MOVETYPE_FLY || SV_TestEntityPosition (host_client->edict))
439         {
440                 SV_FreeMove ();
441                 return;
442         }
443         */
444
445         // walk
446         if ((host_client->edict->fields.server->waterlevel >= 2) && (host_client->edict->fields.server->movetype != MOVETYPE_NOCLIP))
447         {
448                 SV_WaterMove ();
449                 SV_CheckVelocity(host_client->edict);
450                 return;
451         }
452
453         SV_AirMove ();
454         SV_CheckVelocity(host_client->edict);
455 }
456
457 /*
458 ===================
459 SV_ReadClientMove
460 ===================
461 */
462 int sv_numreadmoves = 0;
463 usercmd_t sv_readmoves[CL_MAX_USERCMDS];
464 void SV_ReadClientMove (void)
465 {
466         int i;
467         usercmd_t newmove;
468         usercmd_t *move = &newmove;
469
470         memset(move, 0, sizeof(*move));
471
472         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
473
474         // read ping time
475         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5 && sv.protocol != PROTOCOL_DARKPLACES6)
476                 move->sequence = MSG_ReadLong ();
477         move->time = MSG_ReadFloat ();
478         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
479         move->receivetime = (float)sv.time;
480
481 #if DEBUGMOVES
482         Con_Printf("%s move%i #%i %ims (%ims) %i %i '%i %i %i' '%i %i %i'\n", move->time > move->receivetime ? "^3read future" : "^4read normal", sv_numreadmoves + 1, move->sequence, (int)floor((move->time - host_client->cmd.time) * 1000.0 + 0.5), (int)floor(move->time * 1000.0 + 0.5), move->impulse, move->buttons, (int)move->viewangles[0], (int)move->viewangles[1], (int)move->viewangles[2], (int)move->forwardmove, (int)move->sidemove, (int)move->upmove);
483 #endif
484         // limit reported time to current time
485         // (incase the client is trying to cheat)
486         move->time = min(move->time, move->receivetime + sv.frametime);
487
488         // read current angles
489         for (i = 0;i < 3;i++)
490         {
491                 if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
492                         move->viewangles[i] = MSG_ReadAngle8i();
493                 else if (sv.protocol == PROTOCOL_DARKPLACES1)
494                         move->viewangles[i] = MSG_ReadAngle16i();
495                 else if (sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3)
496                         move->viewangles[i] = MSG_ReadAngle32f();
497                 else
498                         move->viewangles[i] = MSG_ReadAngle16i();
499         }
500         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
501
502         // read movement
503         move->forwardmove = MSG_ReadCoord16i ();
504         move->sidemove = MSG_ReadCoord16i ();
505         move->upmove = MSG_ReadCoord16i ();
506         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
507
508         // read buttons
509         // be sure to bitwise OR them into the move->buttons because we want to
510         // accumulate button presses from multiple packets per actual move
511         if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_QUAKEDP || sv.protocol == PROTOCOL_NEHAHRAMOVIE || sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
512                 move->buttons = MSG_ReadByte ();
513         else
514                 move->buttons = MSG_ReadLong ();
515         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
516
517         // read impulse
518         move->impulse = MSG_ReadByte ();
519         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
520
521         // PRYDON_CLIENTCURSOR
522         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5)
523         {
524                 // 30 bytes
525                 move->cursor_screen[0] = MSG_ReadShort() * (1.0f / 32767.0f);
526                 move->cursor_screen[1] = MSG_ReadShort() * (1.0f / 32767.0f);
527                 move->cursor_start[0] = MSG_ReadFloat();
528                 move->cursor_start[1] = MSG_ReadFloat();
529                 move->cursor_start[2] = MSG_ReadFloat();
530                 move->cursor_impact[0] = MSG_ReadFloat();
531                 move->cursor_impact[1] = MSG_ReadFloat();
532                 move->cursor_impact[2] = MSG_ReadFloat();
533                 move->cursor_entitynumber = (unsigned short)MSG_ReadShort();
534                 if (move->cursor_entitynumber >= prog->max_edicts)
535                 {
536                         Con_DPrintf("SV_ReadClientMessage: client send bad cursor_entitynumber\n");
537                         move->cursor_entitynumber = 0;
538                 }
539                 // as requested by FrikaC, cursor_trace_ent is reset to world if the
540                 // entity is free at time of receipt
541                 if (PRVM_EDICT_NUM(move->cursor_entitynumber)->priv.server->free)
542                         move->cursor_entitynumber = 0;
543                 if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
544         }
545
546         // if the previous move has not been applied yet, we need to accumulate
547         // the impulse/buttons from it
548         if (!host_client->cmd.applied)
549         {
550                 if (!move->impulse)
551                         move->impulse = host_client->cmd.impulse;
552                 move->buttons |= host_client->cmd.buttons;
553         }
554
555         // now store this move for later execution
556         // (we have to buffer the moves because of old ones being repeated)
557         if (sv_numreadmoves < CL_MAX_USERCMDS)
558                 sv_readmoves[sv_numreadmoves++] = *move;
559 }
560
561 void SV_ExecuteClientMoves(void)
562 {
563         int moveindex;
564         float moveframetime;
565         double oldframetime;
566         double oldframetime2;
567 #ifdef NUM_PING_TIMES
568         double total;
569 #endif
570         prvm_eval_t *val;
571         if (sv_numreadmoves < 1)
572                 return;
573         // only start accepting input once the player is spawned
574         if (!host_client->spawned)
575                 return;
576 #if DEBUGMOVES
577         Con_Printf("SV_ExecuteClientMoves: read %i moves at sv.time %f\n", sv_numreadmoves, (float)sv.time);
578 #endif
579         // disable clientside movement prediction in some cases
580         if (ceil(max(sv_readmoves[sv_numreadmoves-1].receivetime - sv_readmoves[sv_numreadmoves-1].time, 0) * 1000.0) < sv_clmovement_minping.integer)
581                 host_client->clmovement_disabletimeout = realtime + sv_clmovement_minping_disabletime.value / 1000.0;
582         // several conditions govern whether clientside movement prediction is allowed
583         if (sv_readmoves[sv_numreadmoves-1].sequence && sv_clmovement_enable.integer && sv_clmovement_waitforinput.integer > 0 && host_client->clmovement_disabletimeout <= realtime && host_client->edict->fields.server->movetype == MOVETYPE_WALK && (!(val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.disableclientprediction)) || !val->_float))
584         {
585                 // process the moves in order and ignore old ones
586                 // but always trust the latest move
587                 // (this deals with bogus initial move sequences after level change,
588                 //  where the client will eventually catch up with the level change
589                 //  and reset its move sequence)
590                 for (moveindex = 0;moveindex < sv_numreadmoves;moveindex++)
591                 {
592                         usercmd_t *move = sv_readmoves + moveindex;
593                         if (host_client->movesequence < move->sequence || moveindex == sv_numreadmoves - 1)
594                         {
595 #if DEBUGMOVES
596                                 Con_Printf("%smove #%i %ims (%ims) %i %i '%i %i %i' '%i %i %i'\n", (move->time - host_client->cmd.time) > sv.frametime * 1.01 ? "^1" : "^2", move->sequence, (int)floor((move->time - host_client->cmd.time) * 1000.0 + 0.5), (int)floor(move->time * 1000.0 + 0.5), move->impulse, move->buttons, (int)move->viewangles[0], (int)move->viewangles[1], (int)move->viewangles[2], (int)move->forwardmove, (int)move->sidemove, (int)move->upmove);
597 #endif
598                                 // this is a new move
599                                 moveframetime = bound(0, move->time - host_client->cmd.time, 0.1);
600                                 //Con_Printf("movesequence = %i (%i lost), moveframetime = %f\n", move->sequence, move->sequence ? move->sequence - host_client->movesequence - 1 : 0, moveframetime);
601                                 host_client->cmd = *move;
602                                 host_client->movesequence = move->sequence;
603
604                                 // if using prediction, we need to perform moves when packets are
605                                 // received, even if multiple occur in one frame
606                                 // (they can't go beyond the current time so there is no cheat issue
607                                 //  with this approach, and if they don't send input for a while they
608                                 //  start moving anyway, so the longest 'lagaport' possible is
609                                 //  determined by the sv_clmovement_waitforinput cvar)
610                                 if (moveframetime <= 0)
611                                         continue;
612                                 oldframetime = prog->globals.server->frametime;
613                                 oldframetime2 = sv.frametime;
614                                 // update ping time for qc to see while executing this move
615                                 host_client->ping = host_client->cmd.receivetime - host_client->cmd.time;
616                                 // the server and qc frametime values must be changed temporarily
617                                 prog->globals.server->frametime = sv.frametime = moveframetime;
618                                 // if move is more than 50ms, split it into two moves (this matches QWSV behavior and the client prediction)
619                                 if (sv.frametime > 0.05)
620                                 {
621                                         prog->globals.server->frametime = sv.frametime = moveframetime * 0.5f;
622                                         SV_Physics_ClientMove();
623                                 }
624                                 SV_Physics_ClientMove();
625                                 sv.frametime = oldframetime2;
626                                 prog->globals.server->frametime = oldframetime;
627                                 host_client->clmovement_skipphysicsframes = sv_clmovement_waitforinput.integer;
628                         }
629                 }
630         }
631         else
632         {
633                 // try to gather button bits from old moves, but only if their time is
634                 // advancing (ones with the same timestamp can't be trusted)
635                 for (moveindex = 0;moveindex < sv_numreadmoves-1;moveindex++)
636                 {
637                         usercmd_t *move = sv_readmoves + moveindex;
638                         if (host_client->cmd.time < move->time)
639                         {
640                                 sv_readmoves[sv_numreadmoves-1].buttons |= move->buttons;
641                                 if (move->impulse)
642                                         sv_readmoves[sv_numreadmoves-1].impulse = move->impulse;
643                         }
644                 }
645                 // now copy the new move
646                 host_client->cmd = sv_readmoves[sv_numreadmoves-1];
647                 host_client->movesequence = 0;
648                 // make sure that normal physics takes over immediately
649                 host_client->clmovement_skipphysicsframes = 0;
650         }
651
652         // calculate average ping time
653         host_client->ping = host_client->cmd.receivetime - host_client->cmd.time;
654 #ifdef NUM_PING_TIMES
655         host_client->ping_times[host_client->num_pings % NUM_PING_TIMES] = host_client->cmd.receivetime - host_client->cmd.time;
656         host_client->num_pings++;
657         for (i=0, total = 0;i < NUM_PING_TIMES;i++)
658                 total += host_client->ping_times[i];
659         host_client->ping = total / NUM_PING_TIMES;
660 #endif
661 }
662
663 void SV_ApplyClientMove (void)
664 {
665         prvm_eval_t *val;
666         usercmd_t *move = &host_client->cmd;
667
668         if (!move->receivetime)
669                 return;
670
671         // note: a move can be applied multiple times if the client packets are
672         // not coming as often as the physics is executed, and the move must be
673         // applied before running qc each time because the id1 qc had a bug where
674         // it clears self.button2 in PlayerJump, causing pogostick behavior if
675         // moves are not applied every time before calling qc
676         move->applied = true;
677
678         // set the edict fields
679         host_client->edict->fields.server->button0 = move->buttons & 1;
680         host_client->edict->fields.server->button2 = (move->buttons & 2)>>1;
681         if (move->impulse)
682                 host_client->edict->fields.server->impulse = move->impulse;
683         // only send the impulse to qc once
684         move->impulse = 0;
685         VectorCopy(move->viewangles, host_client->edict->fields.server->v_angle);
686         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button3))) val->_float = ((move->buttons >> 2) & 1);
687         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button4))) val->_float = ((move->buttons >> 3) & 1);
688         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button5))) val->_float = ((move->buttons >> 4) & 1);
689         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button6))) val->_float = ((move->buttons >> 5) & 1);
690         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button7))) val->_float = ((move->buttons >> 6) & 1);
691         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button8))) val->_float = ((move->buttons >> 7) & 1);
692         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button9))) val->_float = ((move->buttons >> 11) & 1);
693         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button10))) val->_float = ((move->buttons >> 12) & 1);
694         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button11))) val->_float = ((move->buttons >> 13) & 1);
695         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button12))) val->_float = ((move->buttons >> 14) & 1);
696         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button13))) val->_float = ((move->buttons >> 15) & 1);
697         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button14))) val->_float = ((move->buttons >> 16) & 1);
698         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button15))) val->_float = ((move->buttons >> 17) & 1);
699         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.button16))) val->_float = ((move->buttons >> 18) & 1);
700         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.buttonuse))) val->_float = ((move->buttons >> 8) & 1);
701         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.buttonchat))) val->_float = ((move->buttons >> 9) & 1);
702         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_active))) val->_float = ((move->buttons >> 10) & 1);
703         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.movement))) VectorSet(val->vector, move->forwardmove, move->sidemove, move->upmove);
704         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_screen))) VectorCopy(move->cursor_screen, val->vector);
705         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_trace_start))) VectorCopy(move->cursor_start, val->vector);
706         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_trace_endpos))) VectorCopy(move->cursor_impact, val->vector);
707         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.cursor_trace_ent))) val->edict = PRVM_EDICT_TO_PROG(PRVM_EDICT_NUM(move->cursor_entitynumber));
708         if ((val = PRVM_EDICTFIELDVALUE(host_client->edict, prog->fieldoffsets.ping))) val->_float = host_client->ping * 1000.0;
709 }
710
711 void SV_FrameLost(int framenum)
712 {
713         if (host_client->entitydatabase5)
714                 EntityFrame5_LostFrame(host_client->entitydatabase5, framenum);
715 }
716
717 void SV_FrameAck(int framenum)
718 {
719         if (host_client->entitydatabase)
720                 EntityFrame_AckFrame(host_client->entitydatabase, framenum);
721         else if (host_client->entitydatabase4)
722                 EntityFrame4_AckFrame(host_client->entitydatabase4, framenum, true);
723         else if (host_client->entitydatabase5)
724                 EntityFrame5_AckFrame(host_client->entitydatabase5, framenum);
725 }
726
727 /*
728 ===================
729 SV_ReadClientMessage
730 ===================
731 */
732 extern void SV_SendServerinfo(client_t *client);
733 extern sizebuf_t vm_tempstringsbuf;
734 void SV_ReadClientMessage(void)
735 {
736         int cmd, num, start;
737         char *s;
738
739         //MSG_BeginReading ();
740         sv_numreadmoves = 0;
741
742         for(;;)
743         {
744                 if (!host_client->active)
745                 {
746                         // a command caused an error
747                         SV_DropClient (false);
748                         return;
749                 }
750
751                 if (msg_badread)
752                 {
753                         Con_Print("SV_ReadClientMessage: badread\n");
754                         SV_DropClient (false);
755                         return;
756                 }
757
758                 cmd = MSG_ReadByte ();
759                 if (cmd == -1)
760                 {
761                         // end of message
762                         // apply the moves that were read this frame
763                         SV_ExecuteClientMoves();
764                         break;
765                 }
766
767                 switch (cmd)
768                 {
769                 default:
770                         Con_Printf("SV_ReadClientMessage: unknown command char %i\n", cmd);
771                         SV_DropClient (false);
772                         return;
773
774                 case clc_nop:
775                         break;
776
777                 case clc_stringcmd:
778                         s = MSG_ReadString ();
779                         if (strncasecmp(s, "spawn", 5) == 0
780                          || strncasecmp(s, "begin", 5) == 0
781                          || strncasecmp(s, "prespawn", 8) == 0)
782                                 Cmd_ExecuteString (s, src_client);
783                         else if (prog->funcoffsets.SV_ParseClientCommand)
784                         {
785                                 int restorevm_tempstringsbuf_cursize;
786                                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
787                                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(s);
788                                 prog->globals.server->self = PRVM_EDICT_TO_PROG(host_client->edict);
789                                 PRVM_ExecuteProgram (prog->funcoffsets.SV_ParseClientCommand, "QC function SV_ParseClientCommand is missing");
790                                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
791                         }
792                         else
793                                 Cmd_ExecuteString (s, src_client);
794                         break;
795
796                 case clc_disconnect:
797                         SV_DropClient (false); // client wants to disconnect
798                         return;
799
800                 case clc_move:
801                         SV_ReadClientMove();
802                         break;
803
804                 case clc_ackdownloaddata:
805                         start = MSG_ReadLong();
806                         num = MSG_ReadShort();
807                         if (host_client->download_file && host_client->download_started)
808                         {
809                                 if (host_client->download_expectedposition == start)
810                                 {
811                                         int size = (int)FS_FileSize(host_client->download_file);
812                                         // a data block was successfully received by the client,
813                                         // update the expected position on the next data block
814                                         host_client->download_expectedposition = start + num;
815                                         // if this was the last data block of the file, it's done
816                                         if (host_client->download_expectedposition >= FS_FileSize(host_client->download_file))
817                                         {
818                                                 // tell the client that the download finished
819                                                 // we need to calculate the crc now
820                                                 //
821                                                 // note: at this point the OS probably has the file
822                                                 // entirely in memory, so this is a faster operation
823                                                 // now than it was when the download started.
824                                                 //
825                                                 // it is also preferable to do this at the end of the
826                                                 // download rather than the start because it reduces
827                                                 // potential for Denial Of Service attacks against the
828                                                 // server.
829                                                 int crc;
830                                                 unsigned char *temp;
831                                                 FS_Seek(host_client->download_file, 0, SEEK_SET);
832                                                 temp = Mem_Alloc(tempmempool, size);
833                                                 FS_Read(host_client->download_file, temp, size);
834                                                 crc = CRC_Block(temp, size);
835                                                 Mem_Free(temp);
836                                                 // calculated crc, send the file info to the client
837                                                 // (so that it can verify the data)
838                                                 Host_ClientCommands(va("\ncl_downloadfinished %i %i %s\n", size, crc, host_client->download_name));
839                                                 Con_DPrintf("Download of %s by %s has finished\n", host_client->download_name, host_client->name);
840                                                 FS_Close(host_client->download_file);
841                                                 host_client->download_file = NULL;
842                                                 host_client->download_name[0] = 0;
843                                                 host_client->download_expectedposition = 0;
844                                                 host_client->download_started = false;
845                                         }
846                                 }
847                                 else
848                                 {
849                                         // a data block was lost, reset to the expected position
850                                         // and resume sending from there
851                                         FS_Seek(host_client->download_file, host_client->download_expectedposition, SEEK_SET);
852                                 }
853                         }
854                         break;
855
856                 case clc_ackframe:
857                         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
858                         num = MSG_ReadLong();
859                         if (msg_badread) Con_Printf("SV_ReadClientMessage: badread at %s:%i\n", __FILE__, __LINE__);
860                         if (developer_networkentities.integer >= 10)
861                                 Con_Printf("recv clc_ackframe %i\n", num);
862                         // if the client hasn't progressed through signons yet,
863                         // ignore any clc_ackframes we get (they're probably from the
864                         // previous level)
865                         if (host_client->spawned && host_client->latestframenum < num)
866                         {
867                                 int i;
868                                 for (i = host_client->latestframenum + 1;i < num;i++)
869                                         SV_FrameLost(i);
870                                 SV_FrameAck(num);
871                                 host_client->latestframenum = num;
872                         }
873                         break;
874                 }
875         }
876 }
877