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