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