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