more miscellaneous fixes from graphitemaster
[xonotic/darkplaces.git] / cl_parse.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cl_parse.c  -- parse a message received from the server
21
22 #include "quakedef.h"
23 #ifdef CONFIG_CD
24 #include "cdaudio.h"
25 #endif
26 #include "cl_collision.h"
27 #include "csprogs.h"
28 #include "libcurl.h"
29 #include "utf8lib.h"
30 #ifdef CONFIG_MENU
31 #include "menu.h"
32 #endif
33 #include "cl_video.h"
34
35 const char *svc_strings[128] =
36 {
37         "svc_bad",
38         "svc_nop",
39         "svc_disconnect",
40         "svc_updatestat",
41         "svc_version",          // [int] server version
42         "svc_setview",          // [short] entity number
43         "svc_sound",                    // <see code>
44         "svc_time",                     // [float] server time
45         "svc_print",                    // [string] null terminated string
46         "svc_stufftext",                // [string] stuffed into client's console buffer
47                                                 // the string should be \n terminated
48         "svc_setangle",         // [vec3] set the view angle to this absolute value
49
50         "svc_serverinfo",               // [int] version
51                                                 // [string] signon string
52                                                 // [string]..[0]model cache [string]...[0]sounds cache
53                                                 // [string]..[0]item cache
54         "svc_lightstyle",               // [byte] [string]
55         "svc_updatename",               // [byte] [string]
56         "svc_updatefrags",      // [byte] [short]
57         "svc_clientdata",               // <shortbits + data>
58         "svc_stopsound",                // <see code>
59         "svc_updatecolors",     // [byte] [byte]
60         "svc_particle",         // [vec3] <variable>
61         "svc_damage",                   // [byte] impact [byte] blood [vec3] from
62
63         "svc_spawnstatic",
64         "OBSOLETE svc_spawnbinary",
65         "svc_spawnbaseline",
66
67         "svc_temp_entity",              // <variable>
68         "svc_setpause",
69         "svc_signonnum",
70         "svc_centerprint",
71         "svc_killedmonster",
72         "svc_foundsecret",
73         "svc_spawnstaticsound",
74         "svc_intermission",
75         "svc_finale",                   // [string] music [string] text
76         "svc_cdtrack",                  // [byte] track [byte] looptrack
77         "svc_sellscreen",
78         "svc_cutscene",
79         "svc_showlmp",  // [string] iconlabel [string] lmpfile [short] x [short] y
80         "svc_hidelmp",  // [string] iconlabel
81         "svc_skybox", // [string] skyname
82         "", // 38
83         "", // 39
84         "", // 40
85         "", // 41
86         "", // 42
87         "", // 43
88         "", // 44
89         "", // 45
90         "", // 46
91         "", // 47
92         "", // 48
93         "", // 49
94         "svc_downloaddata", //                          50              // [int] start [short] size [variable length] data
95         "svc_updatestatubyte", //                       51              // [byte] stat [byte] value
96         "svc_effect", //                        52              // [vector] org [byte] modelindex [byte] startframe [byte] framecount [byte] framerate
97         "svc_effect2", //                       53              // [vector] org [short] modelindex [short] startframe [byte] framecount [byte] framerate
98         "svc_sound2", //                        54              // short soundindex instead of byte
99         "svc_spawnbaseline2", //        55              // short modelindex instead of byte
100         "svc_spawnstatic2", //          56              // short modelindex instead of byte
101         "svc_entities", //                      57              // [int] deltaframe [int] thisframe [float vector] eye [variable length] entitydata
102         "svc_csqcentities", //          58              // [short] entnum [variable length] entitydata ... [short] 0x0000
103         "svc_spawnstaticsound2", //     59              // [coord3] [short] samp [byte] vol [byte] aten
104         "svc_trailparticles", //        60              // [short] entnum [short] effectnum [vector] start [vector] end
105         "svc_pointparticles", //        61              // [short] effectnum [vector] start [vector] velocity [short] count
106         "svc_pointparticles1", //       62              // [short] effectnum [vector] start, same as svc_pointparticles except velocity is zero and count is 1
107 };
108
109 const char *qw_svc_strings[128] =
110 {
111         "qw_svc_bad",                                   // 0
112         "qw_svc_nop",                                   // 1
113         "qw_svc_disconnect",                    // 2
114         "qw_svc_updatestat",                    // 3    // [byte] [byte]
115         "",                                                             // 4
116         "qw_svc_setview",                               // 5    // [short] entity number
117         "qw_svc_sound",                                 // 6    // <see code>
118         "",                                                             // 7
119         "qw_svc_print",                                 // 8    // [byte] id [string] null terminated string
120         "qw_svc_stufftext",                             // 9    // [string] stuffed into client's console buffer
121         "qw_svc_setangle",                              // 10   // [angle3] set the view angle to this absolute value
122         "qw_svc_serverdata",                    // 11   // [long] protocol ...
123         "qw_svc_lightstyle",                    // 12   // [byte] [string]
124         "",                                                             // 13
125         "qw_svc_updatefrags",                   // 14   // [byte] [short]
126         "",                                                             // 15
127         "qw_svc_stopsound",                             // 16   // <see code>
128         "",                                                             // 17
129         "",                                                             // 18
130         "qw_svc_damage",                                // 19
131         "qw_svc_spawnstatic",                   // 20
132         "",                                                             // 21
133         "qw_svc_spawnbaseline",                 // 22
134         "qw_svc_temp_entity",                   // 23   // variable
135         "qw_svc_setpause",                              // 24   // [byte] on / off
136         "",                                                             // 25
137         "qw_svc_centerprint",                   // 26   // [string] to put in center of the screen
138         "qw_svc_killedmonster",                 // 27
139         "qw_svc_foundsecret",                   // 28
140         "qw_svc_spawnstaticsound",              // 29   // [coord3] [byte] samp [byte] vol [byte] aten
141         "qw_svc_intermission",                  // 30           // [vec3_t] origin [vec3_t] angle
142         "qw_svc_finale",                                // 31           // [string] text
143         "qw_svc_cdtrack",                               // 32           // [byte] track
144         "qw_svc_sellscreen",                    // 33
145         "qw_svc_smallkick",                             // 34           // set client punchangle to 2
146         "qw_svc_bigkick",                               // 35           // set client punchangle to 4
147         "qw_svc_updateping",                    // 36           // [byte] [short]
148         "qw_svc_updateentertime",               // 37           // [byte] [float]
149         "qw_svc_updatestatlong",                // 38           // [byte] [long]
150         "qw_svc_muzzleflash",                   // 39           // [short] entity
151         "qw_svc_updateuserinfo",                // 40           // [byte] slot [long] uid
152         "qw_svc_download",                              // 41           // [short] size [size bytes]
153         "qw_svc_playerinfo",                    // 42           // variable
154         "qw_svc_nails",                                 // 43           // [byte] num [48 bits] xyzpy 12 12 12 4 8
155         "qw_svc_chokecount",                    // 44           // [byte] packets choked
156         "qw_svc_modellist",                             // 45           // [strings]
157         "qw_svc_soundlist",                             // 46           // [strings]
158         "qw_svc_packetentities",                // 47           // [...]
159         "qw_svc_deltapacketentities",   // 48           // [...]
160         "qw_svc_maxspeed",                              // 49           // maxspeed change, for prediction
161         "qw_svc_entgravity",                    // 50           // gravity change, for prediction
162         "qw_svc_setinfo",                               // 51           // setinfo on a client
163         "qw_svc_serverinfo",                    // 52           // serverinfo
164         "qw_svc_updatepl",                              // 53           // [byte] [byte]
165 };
166
167 //=============================================================================
168
169 cvar_t cl_worldmessage = {CVAR_READONLY, "cl_worldmessage", "", "title of current level"};
170 cvar_t cl_worldname = {CVAR_READONLY, "cl_worldname", "", "name of current worldmodel"};
171 cvar_t cl_worldnamenoextension = {CVAR_READONLY, "cl_worldnamenoextension", "", "name of current worldmodel without extension"};
172 cvar_t cl_worldbasename = {CVAR_READONLY, "cl_worldbasename", "", "name of current worldmodel without maps/ prefix or extension"};
173
174 cvar_t developer_networkentities = {0, "developer_networkentities", "0", "prints received entities, value is 0-10 (higher for more info, 10 being the most verbose)"};
175 cvar_t cl_gameplayfix_soundsmovewithentities = {0, "cl_gameplayfix_soundsmovewithentities", "1", "causes sounds made by lifts, players, projectiles, and any other entities, to move with the entity, so for example a rocket noise follows the rocket rather than staying at the starting position"};
176 cvar_t cl_sound_wizardhit = {0, "cl_sound_wizardhit", "wizard/hit.wav", "sound to play during TE_WIZSPIKE (empty cvar disables sound)"};
177 cvar_t cl_sound_hknighthit = {0, "cl_sound_hknighthit", "hknight/hit.wav", "sound to play during TE_KNIGHTSPIKE (empty cvar disables sound)"};
178 cvar_t cl_sound_tink1 = {0, "cl_sound_tink1", "weapons/tink1.wav", "sound to play with 80% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
179 cvar_t cl_sound_ric1 = {0, "cl_sound_ric1", "weapons/ric1.wav", "sound to play with 5% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
180 cvar_t cl_sound_ric2 = {0, "cl_sound_ric2", "weapons/ric2.wav", "sound to play with 5% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
181 cvar_t cl_sound_ric3 = {0, "cl_sound_ric3", "weapons/ric3.wav", "sound to play with 10% chance during TE_SPIKE/TE_SUPERSPIKE (empty cvar disables sound)"};
182 cvar_t cl_readpicture_force = {0, "cl_readpicture_force", "0", "when enabled, the low quality pictures read by ReadPicture() are preferred over the high quality pictures on the file system"};
183
184 #define RIC_GUNSHOT             1
185 #define RIC_GUNSHOTQUAD 2
186 cvar_t cl_sound_ric_gunshot = {0, "cl_sound_ric_gunshot", "0", "specifies if and when the related cl_sound_ric and cl_sound_tink sounds apply to TE_GUNSHOT/TE_GUNSHOTQUAD, 0 = no sound, 1 = TE_GUNSHOT, 2 = TE_GUNSHOTQUAD, 3 = TE_GUNSHOT and TE_GUNSHOTQUAD"};
187 cvar_t cl_sound_r_exp3 = {0, "cl_sound_r_exp3", "weapons/r_exp3.wav", "sound to play during TE_EXPLOSION and related effects (empty cvar disables sound)"};
188 cvar_t cl_serverextension_download = {0, "cl_serverextension_download", "0", "indicates whether the server supports the download command"};
189 cvar_t cl_joinbeforedownloadsfinish = {CVAR_SAVE, "cl_joinbeforedownloadsfinish", "1", "if non-zero the game will begin after the map is loaded before other downloads finish"};
190 cvar_t cl_nettimesyncfactor = {CVAR_SAVE, "cl_nettimesyncfactor", "0", "rate at which client time adapts to match server time, 1 = instantly, 0.125 = slowly, 0 = not at all (bounding still applies)"};
191 cvar_t cl_nettimesyncboundmode = {CVAR_SAVE, "cl_nettimesyncboundmode", "6", "method of restricting client time to valid values, 0 = no correction, 1 = tight bounding (jerky with packet loss), 2 = loose bounding (corrects it if out of bounds), 3 = leniant bounding (ignores temporary errors due to varying framerate), 4 = slow adjustment method from Quake3, 5 = slighttly nicer version of Quake3 method, 6 = bounding + Quake3"};
192 cvar_t cl_nettimesyncboundtolerance = {CVAR_SAVE, "cl_nettimesyncboundtolerance", "0.25", "how much error is tolerated by bounding check, as a fraction of frametime, 0.25 = up to 25% margin of error tolerated, 1 = use only new time, 0 = use only old time (same effect as setting cl_nettimesyncfactor to 1)"};
193 cvar_t cl_iplog_name = {CVAR_SAVE, "cl_iplog_name", "darkplaces_iplog.txt", "name of iplog file containing player addresses for iplog_list command and automatic ip logging when parsing status command"};
194
195 static qboolean QW_CL_CheckOrDownloadFile(const char *filename);
196 static void QW_CL_RequestNextDownload(void);
197 static void QW_CL_NextUpload(void);
198 //static qboolean QW_CL_IsUploading(void);
199 static void QW_CL_StopUpload(void);
200
201 /*
202 ==================
203 CL_ParseStartSoundPacket
204 ==================
205 */
206 static void CL_ParseStartSoundPacket(int largesoundindex)
207 {
208         vec3_t  pos;
209         int     channel, ent;
210         int     sound_num;
211         int     volume;
212         int     field_mask;
213         float   attenuation;
214         float   speed;
215         int             fflags = CHANNELFLAG_NONE;
216
217         if (cls.protocol == PROTOCOL_QUAKEWORLD)
218         {
219                 channel = MSG_ReadShort(&cl_message);
220
221                 if (channel & (1<<15))
222                         volume = MSG_ReadByte(&cl_message);
223                 else
224                         volume = DEFAULT_SOUND_PACKET_VOLUME;
225
226                 if (channel & (1<<14))
227                         attenuation = MSG_ReadByte(&cl_message) / 64.0;
228                 else
229                         attenuation = DEFAULT_SOUND_PACKET_ATTENUATION;
230
231                 speed = 1.0f;
232
233                 ent = (channel>>3)&1023;
234                 channel &= 7;
235
236                 sound_num = MSG_ReadByte(&cl_message);
237         }
238         else
239         {
240                 field_mask = MSG_ReadByte(&cl_message);
241
242                 if (field_mask & SND_VOLUME)
243                         volume = MSG_ReadByte(&cl_message);
244                 else
245                         volume = DEFAULT_SOUND_PACKET_VOLUME;
246
247                 if (field_mask & SND_ATTENUATION)
248                         attenuation = MSG_ReadByte(&cl_message) / 64.0;
249                 else
250                         attenuation = DEFAULT_SOUND_PACKET_ATTENUATION;
251
252                 if (field_mask & SND_SPEEDUSHORT4000)
253                         speed = ((unsigned short)MSG_ReadShort(&cl_message)) / 4000.0f;
254                 else
255                         speed = 1.0f;
256
257                 if (field_mask & SND_LARGEENTITY)
258                 {
259                         ent = (unsigned short) MSG_ReadShort(&cl_message);
260                         channel = MSG_ReadChar(&cl_message);
261                 }
262                 else
263                 {
264                         channel = (unsigned short) MSG_ReadShort(&cl_message);
265                         ent = channel >> 3;
266                         channel &= 7;
267                 }
268
269                 if (largesoundindex || (field_mask & SND_LARGESOUND) || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
270                         sound_num = (unsigned short) MSG_ReadShort(&cl_message);
271                 else
272                         sound_num = MSG_ReadByte(&cl_message);
273         }
274
275         channel = CHAN_NET2ENGINE(channel);
276
277         MSG_ReadVector(&cl_message, pos, cls.protocol);
278
279         if (sound_num < 0 || sound_num >= MAX_SOUNDS)
280         {
281                 Con_Printf("CL_ParseStartSoundPacket: sound_num (%i) >= MAX_SOUNDS (%i)\n", sound_num, MAX_SOUNDS);
282                 return;
283         }
284
285         if (ent >= MAX_EDICTS)
286         {
287                 Con_Printf("CL_ParseStartSoundPacket: ent = %i", ent);
288                 return;
289         }
290
291         if (ent >= cl.max_entities)
292                 CL_ExpandEntities(ent);
293
294         if( !CL_VM_Event_Sound(sound_num, volume / 255.0f, channel, attenuation, ent, pos, fflags, speed) )
295                 S_StartSound_StartPosition_Flags (ent, channel, cl.sound_precache[sound_num], pos, volume/255.0f, attenuation, 0, fflags, speed);
296 }
297
298 /*
299 ==================
300 CL_KeepaliveMessage
301
302 When the client is taking a long time to load stuff, send keepalive messages
303 so the server doesn't disconnect.
304 ==================
305 */
306
307 static unsigned char olddata[NET_MAXMESSAGE];
308 void CL_KeepaliveMessage (qboolean readmessages)
309 {
310         static double lastdirtytime = 0;
311         static qboolean recursive = false;
312         double dirtytime;
313         double deltatime;
314         static double countdownmsg = 0;
315         static double countdownupdate = 0;
316         sizebuf_t old;
317
318         qboolean thisrecursive;
319
320         thisrecursive = recursive;
321         recursive = true;
322
323         dirtytime = Sys_DirtyTime();
324         deltatime = dirtytime - lastdirtytime;
325         lastdirtytime = dirtytime;
326         if (deltatime <= 0 || deltatime >= 1800.0)
327                 return;
328
329         countdownmsg -= deltatime;
330         countdownupdate -= deltatime;
331
332         if(!thisrecursive)
333         {
334                 if(cls.state != ca_dedicated)
335                 {
336                         if(countdownupdate <= 0) // check if time stepped backwards
337                         {
338                                 SCR_UpdateLoadingScreenIfShown();
339                                 countdownupdate = 2;
340                         }
341                 }
342         }
343
344         // no need if server is local and definitely not if this is a demo
345         if (sv.active || !cls.netcon || cls.protocol == PROTOCOL_QUAKEWORLD || cls.signon >= SIGNONS)
346         {
347                 recursive = thisrecursive;
348                 return;
349         }
350
351         if (readmessages)
352         {
353                 // read messages from server, should just be nops
354                 old = cl_message;
355                 memcpy(olddata, cl_message.data, cl_message.cursize);
356
357                 NetConn_ClientFrame();
358
359                 cl_message = old;
360                 memcpy(cl_message.data, olddata, cl_message.cursize);
361         }
362
363         if (cls.netcon && countdownmsg <= 0) // check if time stepped backwards
364         {
365                 sizebuf_t       msg;
366                 unsigned char           buf[4];
367                 countdownmsg = 5;
368                 // write out a nop
369                 // LordHavoc: must use unreliable because reliable could kill the sigon message!
370                 Con_Print("--> client to server keepalive\n");
371                 memset(&msg, 0, sizeof(msg));
372                 msg.data = buf;
373                 msg.maxsize = sizeof(buf);
374                 MSG_WriteChar(&msg, clc_nop);
375                 NetConn_SendUnreliableMessage(cls.netcon, &msg, cls.protocol, 10000, 0, false);
376         }
377
378         recursive = thisrecursive;
379 }
380
381 void CL_ParseEntityLump(char *entdata)
382 {
383         qboolean loadedsky = false;
384         const char *data;
385         char key[128], value[MAX_INPUTLINE];
386         FOG_clear(); // LordHavoc: no fog until set
387         // LordHavoc: default to the map's sky (q3 shader parsing sets this)
388         R_SetSkyBox(cl.worldmodel->brush.skybox);
389         data = entdata;
390         if (!data)
391                 return;
392         if (!COM_ParseToken_Simple(&data, false, false, true))
393                 return; // error
394         if (com_token[0] != '{')
395                 return; // error
396         while (1)
397         {
398                 if (!COM_ParseToken_Simple(&data, false, false, true))
399                         return; // error
400                 if (com_token[0] == '}')
401                         break; // end of worldspawn
402                 if (com_token[0] == '_')
403                         strlcpy (key, com_token + 1, sizeof (key));
404                 else
405                         strlcpy (key, com_token, sizeof (key));
406                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
407                         key[strlen(key)-1] = 0;
408                 if (!COM_ParseToken_Simple(&data, false, false, true))
409                         return; // error
410                 strlcpy (value, com_token, sizeof (value));
411                 if (!strcmp("sky", key))
412                 {
413                         loadedsky = true;
414                         R_SetSkyBox(value);
415                 }
416                 else if (!strcmp("skyname", key)) // non-standard, introduced by QuakeForge... sigh.
417                 {
418                         loadedsky = true;
419                         R_SetSkyBox(value);
420                 }
421                 else if (!strcmp("qlsky", key)) // non-standard, introduced by QuakeLives (EEK)
422                 {
423                         loadedsky = true;
424                         R_SetSkyBox(value);
425                 }
426                 else if (!strcmp("fog", key))
427                 {
428                         FOG_clear(); // so missing values get good defaults
429                         r_refdef.fog_start = 0;
430                         r_refdef.fog_alpha = 1;
431                         r_refdef.fog_end = 16384;
432                         r_refdef.fog_height = 1<<30;
433                         r_refdef.fog_fadedepth = 128;
434 #if _MSC_VER >= 1400
435 #define sscanf sscanf_s
436 #endif
437                         sscanf(value, "%f %f %f %f %f %f %f %f %f", &r_refdef.fog_density, &r_refdef.fog_red, &r_refdef.fog_green, &r_refdef.fog_blue, &r_refdef.fog_alpha, &r_refdef.fog_start, &r_refdef.fog_end, &r_refdef.fog_height, &r_refdef.fog_fadedepth);
438                 }
439                 else if (!strcmp("fog_density", key))
440                         r_refdef.fog_density = atof(value);
441                 else if (!strcmp("fog_red", key))
442                         r_refdef.fog_red = atof(value);
443                 else if (!strcmp("fog_green", key))
444                         r_refdef.fog_green = atof(value);
445                 else if (!strcmp("fog_blue", key))
446                         r_refdef.fog_blue = atof(value);
447                 else if (!strcmp("fog_alpha", key))
448                         r_refdef.fog_alpha = atof(value);
449                 else if (!strcmp("fog_start", key))
450                         r_refdef.fog_start = atof(value);
451                 else if (!strcmp("fog_end", key))
452                         r_refdef.fog_end = atof(value);
453                 else if (!strcmp("fog_height", key))
454                         r_refdef.fog_height = atof(value);
455                 else if (!strcmp("fog_fadedepth", key))
456                         r_refdef.fog_fadedepth = atof(value);
457                 else if (!strcmp("fog_heighttexture", key))
458                 {
459                         FOG_clear(); // so missing values get good defaults
460 #if _MSC_VER >= 1400
461                         sscanf_s(value, "%f %f %f %f %f %f %f %f %f %s", &r_refdef.fog_density, &r_refdef.fog_red, &r_refdef.fog_green, &r_refdef.fog_blue, &r_refdef.fog_alpha, &r_refdef.fog_start, &r_refdef.fog_end, &r_refdef.fog_height, &r_refdef.fog_fadedepth, r_refdef.fog_height_texturename, (unsigned int)sizeof(r_refdef.fog_height_texturename));
462 #else
463                         sscanf(value, "%f %f %f %f %f %f %f %f %f %63s", &r_refdef.fog_density, &r_refdef.fog_red, &r_refdef.fog_green, &r_refdef.fog_blue, &r_refdef.fog_alpha, &r_refdef.fog_start, &r_refdef.fog_end, &r_refdef.fog_height, &r_refdef.fog_fadedepth, r_refdef.fog_height_texturename);
464 #endif
465                         r_refdef.fog_height_texturename[63] = 0;
466                 }
467         }
468
469         if (!loadedsky && cl.worldmodel->brush.isq2bsp)
470                 R_SetSkyBox("unit1_");
471 }
472
473 static const vec3_t defaultmins = {-4096, -4096, -4096};
474 static const vec3_t defaultmaxs = {4096, 4096, 4096};
475 static void CL_SetupWorldModel(void)
476 {
477         prvm_prog_t *prog = CLVM_prog;
478         // update the world model
479         cl.entities[0].render.model = cl.worldmodel = CL_GetModelByIndex(1);
480         CL_UpdateRenderEntity(&cl.entities[0].render);
481
482         // make sure the cl.worldname and related cvars are set up now that we know the world model name
483         // set up csqc world for collision culling
484         if (cl.worldmodel)
485         {
486                 strlcpy(cl.worldname, cl.worldmodel->name, sizeof(cl.worldname));
487                 FS_StripExtension(cl.worldname, cl.worldnamenoextension, sizeof(cl.worldnamenoextension));
488                 strlcpy(cl.worldbasename, !strncmp(cl.worldnamenoextension, "maps/", 5) ? cl.worldnamenoextension + 5 : cl.worldnamenoextension, sizeof(cl.worldbasename));
489                 Cvar_SetQuick(&cl_worldmessage, cl.worldmessage);
490                 Cvar_SetQuick(&cl_worldname, cl.worldname);
491                 Cvar_SetQuick(&cl_worldnamenoextension, cl.worldnamenoextension);
492                 Cvar_SetQuick(&cl_worldbasename, cl.worldbasename);
493                 World_SetSize(&cl.world, cl.worldname, cl.worldmodel->normalmins, cl.worldmodel->normalmaxs, prog);
494         }
495         else
496         {
497                 Cvar_SetQuick(&cl_worldmessage, cl.worldmessage);
498                 Cvar_SetQuick(&cl_worldnamenoextension, "");
499                 Cvar_SetQuick(&cl_worldbasename, "");
500                 World_SetSize(&cl.world, "", defaultmins, defaultmaxs, prog);
501         }
502         World_Start(&cl.world);
503
504         // load or reload .loc file for team chat messages
505         CL_Locs_Reload_f();
506
507         // make sure we send enough keepalives
508         CL_KeepaliveMessage(false);
509
510         // reset particles and other per-level things
511         R_Modules_NewMap();
512
513         // make sure we send enough keepalives
514         CL_KeepaliveMessage(false);
515
516         // load the team chat beep if possible
517         cl.foundtalk2wav = FS_FileExists("sound/misc/talk2.wav");
518
519         // check memory integrity
520         Mem_CheckSentinelsGlobal();
521
522 #ifdef CONFIG_MENU
523         // make menu know
524         MR_NewMap();
525 #endif
526
527         // load the csqc now
528         if (cl.loadcsqc)
529         {
530                 cl.loadcsqc = false;
531
532                 CL_VM_Init();
533         }
534 }
535
536 static qboolean QW_CL_CheckOrDownloadFile(const char *filename)
537 {
538         qfile_t *file;
539         char vabuf[1024];
540
541         // see if the file already exists
542         file = FS_OpenVirtualFile(filename, true);
543         if (file)
544         {
545                 FS_Close(file);
546                 return true;
547         }
548
549         // download messages in a demo would be bad
550         if (cls.demorecording)
551         {
552                 Con_Printf("Unable to download \"%s\" when recording.\n", filename);
553                 return true;
554         }
555
556         // don't try to download when playing a demo
557         if (!cls.netcon)
558                 return true;
559
560         strlcpy(cls.qw_downloadname, filename, sizeof(cls.qw_downloadname));
561         Con_Printf("Downloading %s\n", filename);
562
563         if (!cls.qw_downloadmemory)
564         {
565                 cls.qw_downloadmemory = NULL;
566                 cls.qw_downloadmemorycursize = 0;
567                 cls.qw_downloadmemorymaxsize = 1024*1024; // start out with a 1MB buffer
568         }
569
570         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
571         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "download %s", filename));
572
573         cls.qw_downloadnumber++;
574         cls.qw_downloadpercent = 0;
575         cls.qw_downloadmemorycursize = 0;
576
577         return false;
578 }
579
580 static void QW_CL_ProcessUserInfo(int slot);
581 static void QW_CL_RequestNextDownload(void)
582 {
583         int i;
584         char vabuf[1024];
585
586         // clear name of file that just finished
587         cls.qw_downloadname[0] = 0;
588
589         switch (cls.qw_downloadtype)
590         {
591         case dl_single:
592                 break;
593         case dl_skin:
594                 if (cls.qw_downloadnumber == 0)
595                         Con_Printf("Checking skins...\n");
596                 for (;cls.qw_downloadnumber < cl.maxclients;cls.qw_downloadnumber++)
597                 {
598                         if (!cl.scores[cls.qw_downloadnumber].name[0])
599                                 continue;
600                         // check if we need to download the file, and return if so
601                         if (!QW_CL_CheckOrDownloadFile(va(vabuf, sizeof(vabuf), "skins/%s.pcx", cl.scores[cls.qw_downloadnumber].qw_skin)))
602                                 return;
603                 }
604
605                 cls.qw_downloadtype = dl_none;
606
607                 // load any newly downloaded skins
608                 for (i = 0;i < cl.maxclients;i++)
609                         QW_CL_ProcessUserInfo(i);
610
611                 // if we're still in signon stages, request the next one
612                 if (cls.signon != SIGNONS)
613                 {
614                         cls.signon = SIGNONS-1;
615                         // we'll go to SIGNONS when the first entity update is received
616                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
617                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "begin %i", cl.qw_servercount));
618                 }
619                 break;
620         case dl_model:
621                 if (cls.qw_downloadnumber == 0)
622                 {
623                         Con_Printf("Checking models...\n");
624                         cls.qw_downloadnumber = 1;
625                 }
626
627                 for (;cls.qw_downloadnumber < MAX_MODELS && cl.model_name[cls.qw_downloadnumber][0];cls.qw_downloadnumber++)
628                 {
629                         // skip submodels
630                         if (cl.model_name[cls.qw_downloadnumber][0] == '*')
631                                 continue;
632                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/spike.mdl"))
633                                 cl.qw_modelindex_spike = cls.qw_downloadnumber;
634                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/player.mdl"))
635                                 cl.qw_modelindex_player = cls.qw_downloadnumber;
636                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/flag.mdl"))
637                                 cl.qw_modelindex_flag = cls.qw_downloadnumber;
638                         if (!strcmp(cl.model_name[cls.qw_downloadnumber], "progs/s_explod.spr"))
639                                 cl.qw_modelindex_s_explod = cls.qw_downloadnumber;
640                         // check if we need to download the file, and return if so
641                         if (!QW_CL_CheckOrDownloadFile(cl.model_name[cls.qw_downloadnumber]))
642                                 return;
643                 }
644
645                 cls.qw_downloadtype = dl_none;
646
647                 // touch all of the precached models that are still loaded so we can free
648                 // anything that isn't needed
649                 if (!sv.active)
650                         Mod_ClearUsed();
651                 for (i = 1;i < MAX_MODELS && cl.model_name[i][0];i++)
652                         Mod_FindName(cl.model_name[i], cl.model_name[i][0] == '*' ? cl.model_name[1] : NULL);
653                 // precache any models used by the client (this also marks them used)
654                 cl.model_bolt = Mod_ForName("progs/bolt.mdl", false, false, NULL);
655                 cl.model_bolt2 = Mod_ForName("progs/bolt2.mdl", false, false, NULL);
656                 cl.model_bolt3 = Mod_ForName("progs/bolt3.mdl", false, false, NULL);
657                 cl.model_beam = Mod_ForName("progs/beam.mdl", false, false, NULL);
658
659                 // we purge the models and sounds later in CL_SignonReply
660                 //Mod_PurgeUnused();
661
662                 // now we try to load everything that is new
663
664                 // world model
665                 cl.model_precache[1] = Mod_ForName(cl.model_name[1], false, false, NULL);
666                 if (cl.model_precache[1]->Draw == NULL)
667                         Con_Printf("Map %s could not be found or downloaded\n", cl.model_name[1]);
668
669                 // normal models
670                 for (i = 2;i < MAX_MODELS && cl.model_name[i][0];i++)
671                         if ((cl.model_precache[i] = Mod_ForName(cl.model_name[i], false, false, cl.model_name[i][0] == '*' ? cl.model_name[1] : NULL))->Draw == NULL)
672                                 Con_Printf("Model %s could not be found or downloaded\n", cl.model_name[i]);
673
674                 // check memory integrity
675                 Mem_CheckSentinelsGlobal();
676
677                 // now that we have a world model, set up the world entity, renderer
678                 // modules and csqc
679                 CL_SetupWorldModel();
680
681                 // add pmodel/emodel CRCs to userinfo
682                 CL_SetInfo("pmodel", va(vabuf, sizeof(vabuf), "%i", FS_CRCFile("progs/player.mdl", NULL)), true, true, true, true);
683                 CL_SetInfo("emodel", va(vabuf, sizeof(vabuf), "%i", FS_CRCFile("progs/eyes.mdl", NULL)), true, true, true, true);
684
685                 // done checking sounds and models, send a prespawn command now
686                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
687                 MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "prespawn %i 0 %i", cl.qw_servercount, cl.model_precache[1]->brush.qw_md4sum2));
688
689                 if (cls.qw_downloadmemory)
690                 {
691                         Mem_Free(cls.qw_downloadmemory);
692                         cls.qw_downloadmemory = NULL;
693                 }
694
695                 // done loading
696                 cl.loadfinished = true;
697                 break;
698         case dl_sound:
699                 if (cls.qw_downloadnumber == 0)
700                 {
701                         Con_Printf("Checking sounds...\n");
702                         cls.qw_downloadnumber = 1;
703                 }
704
705                 for (;cl.sound_name[cls.qw_downloadnumber][0];cls.qw_downloadnumber++)
706                 {
707                         // check if we need to download the file, and return if so
708                         if (!QW_CL_CheckOrDownloadFile(va(vabuf, sizeof(vabuf), "sound/%s", cl.sound_name[cls.qw_downloadnumber])))
709                                 return;
710                 }
711
712                 cls.qw_downloadtype = dl_none;
713
714                 // clear sound usage flags for purging of unused sounds
715                 S_ClearUsed();
716
717                 // precache any sounds used by the client
718                 cl.sfx_wizhit = S_PrecacheSound(cl_sound_wizardhit.string, false, true);
719                 cl.sfx_knighthit = S_PrecacheSound(cl_sound_hknighthit.string, false, true);
720                 cl.sfx_tink1 = S_PrecacheSound(cl_sound_tink1.string, false, true);
721                 cl.sfx_ric1 = S_PrecacheSound(cl_sound_ric1.string, false, true);
722                 cl.sfx_ric2 = S_PrecacheSound(cl_sound_ric2.string, false, true);
723                 cl.sfx_ric3 = S_PrecacheSound(cl_sound_ric3.string, false, true);
724                 cl.sfx_r_exp3 = S_PrecacheSound(cl_sound_r_exp3.string, false, true);
725
726                 // sounds used by the game
727                 for (i = 1;i < MAX_SOUNDS && cl.sound_name[i][0];i++)
728                         cl.sound_precache[i] = S_PrecacheSound(cl.sound_name[i], true, true);
729
730                 // we purge the models and sounds later in CL_SignonReply
731                 //S_PurgeUnused();
732
733                 // check memory integrity
734                 Mem_CheckSentinelsGlobal();
735
736                 // done with sound downloads, next we check models
737                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
738                 MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "modellist %i %i", cl.qw_servercount, 0));
739                 break;
740         case dl_none:
741         default:
742                 Con_Printf("Unknown download type.\n");
743         }
744 }
745
746 static void QW_CL_ParseDownload(void)
747 {
748         int size = (signed short)MSG_ReadShort(&cl_message);
749         int percent = MSG_ReadByte(&cl_message);
750
751         //Con_Printf("download %i %i%% (%i/%i)\n", size, percent, cls.qw_downloadmemorycursize, cls.qw_downloadmemorymaxsize);
752
753         // skip the download fragment if playing a demo
754         if (!cls.netcon)
755         {
756                 if (size > 0)
757                         cl_message.readcount += size;
758                 return;
759         }
760
761         if (size == -1)
762         {
763                 Con_Printf("File not found.\n");
764                 QW_CL_RequestNextDownload();
765                 return;
766         }
767
768         if (cl_message.readcount + (unsigned short)size > cl_message.cursize)
769                 Host_Error("corrupt download message\n");
770
771         // make sure the buffer is big enough to include this new fragment
772         if (!cls.qw_downloadmemory || cls.qw_downloadmemorymaxsize < cls.qw_downloadmemorycursize + size)
773         {
774                 unsigned char *old;
775                 while (cls.qw_downloadmemorymaxsize < cls.qw_downloadmemorycursize + size)
776                         cls.qw_downloadmemorymaxsize *= 2;
777                 old = cls.qw_downloadmemory;
778                 cls.qw_downloadmemory = (unsigned char *)Mem_Alloc(cls.permanentmempool, cls.qw_downloadmemorymaxsize);
779                 if (old)
780                 {
781                         memcpy(cls.qw_downloadmemory, old, cls.qw_downloadmemorycursize);
782                         Mem_Free(old);
783                 }
784         }
785
786         // read the fragment out of the packet
787         MSG_ReadBytes(&cl_message, size, cls.qw_downloadmemory + cls.qw_downloadmemorycursize);
788         cls.qw_downloadmemorycursize += size;
789         cls.qw_downloadspeedcount += size;
790
791         cls.qw_downloadpercent = percent;
792
793         if (percent != 100)
794         {
795                 // request next fragment
796                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
797                 MSG_WriteString(&cls.netcon->message, "nextdl");
798         }
799         else
800         {
801                 // finished file
802                 Con_Printf("Downloaded \"%s\"\n", cls.qw_downloadname);
803
804                 FS_WriteFile(cls.qw_downloadname, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
805
806                 cls.qw_downloadpercent = 0;
807
808                 // start downloading the next file (or join the game)
809                 QW_CL_RequestNextDownload();
810         }
811 }
812
813 static void QW_CL_ParseModelList(void)
814 {
815         int n;
816         int nummodels = MSG_ReadByte(&cl_message);
817         char *str;
818         char vabuf[1024];
819
820         // parse model precache list
821         for (;;)
822         {
823                 str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
824                 if (!str[0])
825                         break;
826                 nummodels++;
827                 if (nummodels==MAX_MODELS)
828                         Host_Error("Server sent too many model precaches");
829                 if (strlen(str) >= MAX_QPATH)
830                         Host_Error("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
831                 strlcpy(cl.model_name[nummodels], str, sizeof (cl.model_name[nummodels]));
832         }
833
834         n = MSG_ReadByte(&cl_message);
835         if (n)
836         {
837                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
838                 MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "modellist %i %i", cl.qw_servercount, n));
839                 return;
840         }
841
842         cls.signon = 2;
843         cls.qw_downloadnumber = 0;
844         cls.qw_downloadtype = dl_model;
845         QW_CL_RequestNextDownload();
846 }
847
848 static void QW_CL_ParseSoundList(void)
849 {
850         int n;
851         int numsounds = MSG_ReadByte(&cl_message);
852         char *str;
853         char vabuf[1024];
854
855         // parse sound precache list
856         for (;;)
857         {
858                 str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
859                 if (!str[0])
860                         break;
861                 numsounds++;
862                 if (numsounds==MAX_SOUNDS)
863                         Host_Error("Server sent too many sound precaches");
864                 if (strlen(str) >= MAX_QPATH)
865                         Host_Error("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
866                 strlcpy(cl.sound_name[numsounds], str, sizeof (cl.sound_name[numsounds]));
867         }
868
869         n = MSG_ReadByte(&cl_message);
870
871         if (n)
872         {
873                 MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
874                 MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "soundlist %i %i", cl.qw_servercount, n));
875                 return;
876         }
877
878         cls.signon = 2;
879         cls.qw_downloadnumber = 0;
880         cls.qw_downloadtype = dl_sound;
881         QW_CL_RequestNextDownload();
882 }
883
884 static void QW_CL_Skins_f(void)
885 {
886         cls.qw_downloadnumber = 0;
887         cls.qw_downloadtype = dl_skin;
888         QW_CL_RequestNextDownload();
889 }
890
891 static void QW_CL_Changing_f(void)
892 {
893         if (cls.qw_downloadmemory)  // don't change when downloading
894                 return;
895
896         S_StopAllSounds();
897         cl.intermission = 0;
898         cls.signon = 1; // not active anymore, but not disconnected
899         Con_Printf("\nChanging map...\n");
900 }
901
902 void QW_CL_NextUpload(void)
903 {
904         int r, percent, size;
905
906         if (!cls.qw_uploaddata)
907                 return;
908
909         r = cls.qw_uploadsize - cls.qw_uploadpos;
910         if (r > 768)
911                 r = 768;
912         size = min(1, cls.qw_uploadsize);
913         percent = (cls.qw_uploadpos+r)*100/size;
914
915         MSG_WriteByte(&cls.netcon->message, qw_clc_upload);
916         MSG_WriteShort(&cls.netcon->message, r);
917         MSG_WriteByte(&cls.netcon->message, percent);
918         SZ_Write(&cls.netcon->message, cls.qw_uploaddata + cls.qw_uploadpos, r);
919
920         Con_DPrintf("UPLOAD: %6d: %d written\n", cls.qw_uploadpos, r);
921
922         cls.qw_uploadpos += r;
923
924         if (cls.qw_uploadpos < cls.qw_uploadsize)
925                 return;
926
927         Con_Printf("Upload completed\n");
928
929         QW_CL_StopUpload();
930 }
931
932 void QW_CL_StartUpload(unsigned char *data, int size)
933 {
934         // do nothing in demos or if not connected
935         if (!cls.netcon)
936                 return;
937
938         // abort existing upload if in progress
939         QW_CL_StopUpload();
940
941         Con_DPrintf("Starting upload of %d bytes...\n", size);
942
943         cls.qw_uploaddata = (unsigned char *)Mem_Alloc(cls.permanentmempool, size);
944         memcpy(cls.qw_uploaddata, data, size);
945         cls.qw_uploadsize = size;
946         cls.qw_uploadpos = 0;
947
948         QW_CL_NextUpload();
949 }
950
951 #if 0
952 qboolean QW_CL_IsUploading(void)
953 {
954         return cls.qw_uploaddata != NULL;
955 }
956 #endif
957
958 void QW_CL_StopUpload(void)
959 {
960         if (cls.qw_uploaddata)
961                 Mem_Free(cls.qw_uploaddata);
962         cls.qw_uploaddata = NULL;
963         cls.qw_uploadsize = 0;
964         cls.qw_uploadpos = 0;
965 }
966
967 static void QW_CL_ProcessUserInfo(int slot)
968 {
969         int topcolor, bottomcolor;
970         char temp[2048];
971         InfoString_GetValue(cl.scores[slot].qw_userinfo, "name", cl.scores[slot].name, sizeof(cl.scores[slot].name));
972         InfoString_GetValue(cl.scores[slot].qw_userinfo, "topcolor", temp, sizeof(temp));topcolor = atoi(temp);
973         InfoString_GetValue(cl.scores[slot].qw_userinfo, "bottomcolor", temp, sizeof(temp));bottomcolor = atoi(temp);
974         cl.scores[slot].colors = topcolor * 16 + bottomcolor;
975         InfoString_GetValue(cl.scores[slot].qw_userinfo, "*spectator", temp, sizeof(temp));
976         cl.scores[slot].qw_spectator = temp[0] != 0;
977         InfoString_GetValue(cl.scores[slot].qw_userinfo, "team", cl.scores[slot].qw_team, sizeof(cl.scores[slot].qw_team));
978         InfoString_GetValue(cl.scores[slot].qw_userinfo, "skin", cl.scores[slot].qw_skin, sizeof(cl.scores[slot].qw_skin));
979         if (!cl.scores[slot].qw_skin[0])
980                 strlcpy(cl.scores[slot].qw_skin, "base", sizeof(cl.scores[slot].qw_skin));
981         // TODO: skin cache
982 }
983
984 static void QW_CL_UpdateUserInfo(void)
985 {
986         int slot;
987         slot = MSG_ReadByte(&cl_message);
988         if (slot >= cl.maxclients)
989         {
990                 Con_Printf("svc_updateuserinfo >= cl.maxclients\n");
991                 MSG_ReadLong(&cl_message);
992                 MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
993                 return;
994         }
995         cl.scores[slot].qw_userid = MSG_ReadLong(&cl_message);
996         strlcpy(cl.scores[slot].qw_userinfo, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(cl.scores[slot].qw_userinfo));
997
998         QW_CL_ProcessUserInfo(slot);
999 }
1000
1001 static void QW_CL_SetInfo(void)
1002 {
1003         int slot;
1004         char key[2048];
1005         char value[2048];
1006         slot = MSG_ReadByte(&cl_message);
1007         strlcpy(key, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(key));
1008         strlcpy(value, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(value));
1009         if (slot >= cl.maxclients)
1010         {
1011                 Con_Printf("svc_setinfo >= cl.maxclients\n");
1012                 return;
1013         }
1014         InfoString_SetValue(cl.scores[slot].qw_userinfo, sizeof(cl.scores[slot].qw_userinfo), key, value);
1015
1016         QW_CL_ProcessUserInfo(slot);
1017 }
1018
1019 static void QW_CL_ServerInfo(void)
1020 {
1021         char key[2048];
1022         char value[2048];
1023         char temp[32];
1024         strlcpy(key, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(key));
1025         strlcpy(value, MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), sizeof(value));
1026         Con_DPrintf("SERVERINFO: %s=%s\n", key, value);
1027         InfoString_SetValue(cl.qw_serverinfo, sizeof(cl.qw_serverinfo), key, value);
1028         InfoString_GetValue(cl.qw_serverinfo, "teamplay", temp, sizeof(temp));
1029         cl.qw_teamplay = atoi(temp);
1030 }
1031
1032 static void QW_CL_ParseNails(void)
1033 {
1034         int i, j;
1035         int numnails = MSG_ReadByte(&cl_message);
1036         vec_t *v;
1037         unsigned char bits[6];
1038         for (i = 0;i < numnails;i++)
1039         {
1040                 for (j = 0;j < 6;j++)
1041                         bits[j] = MSG_ReadByte(&cl_message);
1042                 if (cl.qw_num_nails >= 255)
1043                         continue;
1044                 v = cl.qw_nails[cl.qw_num_nails++];
1045                 v[0] = ( ( bits[0] + ((bits[1]&15)<<8) ) <<1) - 4096;
1046                 v[1] = ( ( (bits[1]>>4) + (bits[2]<<4) ) <<1) - 4096;
1047                 v[2] = ( ( bits[3] + ((bits[4]&15)<<8) ) <<1) - 4096;
1048                 v[3] = -360*(bits[4]>>4)/16;
1049                 v[4] = 360*bits[5]/256;
1050                 v[5] = 0;
1051         }
1052 }
1053
1054 static void CL_UpdateItemsAndWeapon(void)
1055 {
1056         int j;
1057         // check for important changes
1058
1059         // set flash times
1060         if (cl.olditems != cl.stats[STAT_ITEMS])
1061                 for (j = 0;j < 32;j++)
1062                         if ((cl.stats[STAT_ITEMS] & (1<<j)) && !(cl.olditems & (1<<j)))
1063                                 cl.item_gettime[j] = cl.time;
1064         cl.olditems = cl.stats[STAT_ITEMS];
1065
1066         // GAME_NEXUIZ hud needs weapon change time
1067         if (cl.activeweapon != cl.stats[STAT_ACTIVEWEAPON])
1068                 cl.weapontime = cl.time;
1069         cl.activeweapon = cl.stats[STAT_ACTIVEWEAPON];
1070 }
1071
1072 #define LOADPROGRESSWEIGHT_SOUND            1.0
1073 #define LOADPROGRESSWEIGHT_MODEL            4.0
1074 #define LOADPROGRESSWEIGHT_WORLDMODEL      30.0
1075 #define LOADPROGRESSWEIGHT_WORLDMODEL_INIT  2.0
1076
1077 static void CL_BeginDownloads(qboolean aborteddownload)
1078 {
1079         char vabuf[1024];
1080         // quakeworld works differently
1081         if (cls.protocol == PROTOCOL_QUAKEWORLD)
1082                 return;
1083
1084         // this would be a good place to do curl downloads
1085         if(Curl_Have_forthismap())
1086         {
1087                 Curl_Register_predownload(); // come back later
1088                 return;
1089         }
1090
1091         // if we got here...
1092         // curl is done, so let's start with the business
1093         if(!cl.loadbegun)
1094                 SCR_PushLoadingScreen(false, "Loading precaches", 1);
1095         cl.loadbegun = true;
1096
1097         // if already downloading something from the previous level, don't stop it
1098         if (cls.qw_downloadname[0])
1099                 return;
1100
1101         if (cl.downloadcsqc)
1102         {
1103                 size_t progsize;
1104                 cl.downloadcsqc = false;
1105                 if (cls.netcon
1106                  && !sv.active
1107                  && csqc_progname.string
1108                  && csqc_progname.string[0]
1109                  && csqc_progcrc.integer >= 0
1110                  && cl_serverextension_download.integer
1111                  && (FS_CRCFile(csqc_progname.string, &progsize) != csqc_progcrc.integer || ((int)progsize != csqc_progsize.integer && csqc_progsize.integer != -1))
1112                  && !FS_FileExists(va(vabuf, sizeof(vabuf), "dlcache/%s.%i.%i", csqc_progname.string, csqc_progsize.integer, csqc_progcrc.integer)))
1113                 {
1114                         Con_Printf("Downloading new CSQC code to dlcache/%s.%i.%i\n", csqc_progname.string, csqc_progsize.integer, csqc_progcrc.integer);
1115                         if(cl_serverextension_download.integer == 2 && FS_HasZlib())
1116                                 Cmd_ForwardStringToServer(va(vabuf, sizeof(vabuf), "download %s deflate", csqc_progname.string));
1117                         else
1118                                 Cmd_ForwardStringToServer(va(vabuf, sizeof(vabuf), "download %s", csqc_progname.string));
1119                         return;
1120                 }
1121         }
1122
1123         if (cl.loadmodel_current < cl.loadmodel_total)
1124         {
1125                 // loading models
1126                 if(cl.loadmodel_current == 1)
1127                 {
1128                         // worldmodel counts as 16 models (15 + world model setup), for better progress bar
1129                         SCR_PushLoadingScreen(false, "Loading precached models",
1130                                 (
1131                                         (cl.loadmodel_total - 1) * LOADPROGRESSWEIGHT_MODEL
1132                                 +       LOADPROGRESSWEIGHT_WORLDMODEL
1133                                 +       LOADPROGRESSWEIGHT_WORLDMODEL_INIT
1134                                 ) / (
1135                                         (cl.loadmodel_total - 1) * LOADPROGRESSWEIGHT_MODEL
1136                                 +       LOADPROGRESSWEIGHT_WORLDMODEL
1137                                 +       LOADPROGRESSWEIGHT_WORLDMODEL_INIT
1138                                 +       cl.loadsound_total * LOADPROGRESSWEIGHT_SOUND
1139                                 )
1140                         );
1141                         SCR_BeginLoadingPlaque(false);
1142                 }
1143                 for (;cl.loadmodel_current < cl.loadmodel_total;cl.loadmodel_current++)
1144                 {
1145                         SCR_PushLoadingScreen(false, cl.model_name[cl.loadmodel_current],
1146                                 (
1147                                         (cl.loadmodel_current == 1) ? LOADPROGRESSWEIGHT_WORLDMODEL : LOADPROGRESSWEIGHT_MODEL
1148                                 ) / (
1149                                         (cl.loadmodel_total - 1) * LOADPROGRESSWEIGHT_MODEL
1150                                 +       LOADPROGRESSWEIGHT_WORLDMODEL
1151                                 +       LOADPROGRESSWEIGHT_WORLDMODEL_INIT
1152                                 )
1153                         );
1154                         if (cl.model_precache[cl.loadmodel_current] && cl.model_precache[cl.loadmodel_current]->Draw)
1155                         {
1156                                 SCR_PopLoadingScreen(false);
1157                                 if(cl.loadmodel_current == 1)
1158                                 {
1159                                         SCR_PushLoadingScreen(false, cl.model_name[cl.loadmodel_current], 1.0 / cl.loadmodel_total);
1160                                         SCR_PopLoadingScreen(false);
1161                                 }
1162                                 continue;
1163                         }
1164                         CL_KeepaliveMessage(true);
1165
1166                         // if running a local game, calling Mod_ForName is a completely wasted effort...
1167                         if (sv.active)
1168                                 cl.model_precache[cl.loadmodel_current] = sv.models[cl.loadmodel_current];
1169                         else
1170                         {
1171                                 if(cl.loadmodel_current == 1)
1172                                 {
1173                                         // they'll be soon loaded, but make sure we apply freshly downloaded shaders from a curled pk3
1174                                         Mod_FreeQ3Shaders();
1175                                 }
1176                                 cl.model_precache[cl.loadmodel_current] = Mod_ForName(cl.model_name[cl.loadmodel_current], false, false, cl.model_name[cl.loadmodel_current][0] == '*' ? cl.model_name[1] : NULL);
1177                         }
1178                         SCR_PopLoadingScreen(false);
1179                         if (cl.model_precache[cl.loadmodel_current] && cl.model_precache[cl.loadmodel_current]->Draw && cl.loadmodel_current == 1)
1180                         {
1181                                 // we now have the worldmodel so we can set up the game world
1182                                 SCR_PushLoadingScreen(true, "world model setup",
1183                                         (
1184                                                 LOADPROGRESSWEIGHT_WORLDMODEL_INIT
1185                                         ) / (
1186                                                 (cl.loadmodel_total - 1) * LOADPROGRESSWEIGHT_MODEL
1187                                         +       LOADPROGRESSWEIGHT_WORLDMODEL
1188                                         +       LOADPROGRESSWEIGHT_WORLDMODEL_INIT
1189                                         )
1190                                 );
1191                                 CL_SetupWorldModel();
1192                                 SCR_PopLoadingScreen(true);
1193                                 if (!cl.loadfinished && cl_joinbeforedownloadsfinish.integer)
1194                                 {
1195                                         cl.loadfinished = true;
1196                                         // now issue the spawn to move on to signon 2 like normal
1197                                         if (cls.netcon)
1198                                                 Cmd_ForwardStringToServer("prespawn");
1199                                 }
1200                         }
1201                 }
1202                 SCR_PopLoadingScreen(false);
1203                 // finished loading models
1204         }
1205
1206         if (cl.loadsound_current < cl.loadsound_total)
1207         {
1208                 // loading sounds
1209                 if(cl.loadsound_current == 1)
1210                         SCR_PushLoadingScreen(false, "Loading precached sounds",
1211                                 (
1212                                         cl.loadsound_total * LOADPROGRESSWEIGHT_SOUND
1213                                 ) / (
1214                                         (cl.loadmodel_total - 1) * LOADPROGRESSWEIGHT_MODEL
1215                                 +       LOADPROGRESSWEIGHT_WORLDMODEL
1216                                 +       LOADPROGRESSWEIGHT_WORLDMODEL_INIT
1217                                 +       cl.loadsound_total * LOADPROGRESSWEIGHT_SOUND
1218                                 )
1219                         );
1220                 for (;cl.loadsound_current < cl.loadsound_total;cl.loadsound_current++)
1221                 {
1222                         SCR_PushLoadingScreen(false, cl.sound_name[cl.loadsound_current], 1.0 / cl.loadsound_total);
1223                         if (cl.sound_precache[cl.loadsound_current] && S_IsSoundPrecached(cl.sound_precache[cl.loadsound_current]))
1224                         {
1225                                 SCR_PopLoadingScreen(false);
1226                                 continue;
1227                         }
1228                         CL_KeepaliveMessage(true);
1229                         cl.sound_precache[cl.loadsound_current] = S_PrecacheSound(cl.sound_name[cl.loadsound_current], false, true);
1230                         SCR_PopLoadingScreen(false);
1231                 }
1232                 SCR_PopLoadingScreen(false);
1233                 // finished loading sounds
1234         }
1235
1236         if(IS_NEXUIZ_DERIVED(gamemode))
1237                 Cvar_SetValueQuick(&cl_serverextension_download, false);
1238                 // in Nexuiz/Xonotic, the built in download protocol is kinda broken (misses lots
1239                 // of dependencies) anyway, and can mess around with the game directory;
1240                 // until this is fixed, only support pk3 downloads via curl, and turn off
1241                 // individual file downloads other than for CSQC
1242                 // on the other end of the download protocol, GAME_NEXUIZ/GAME_XONOTIC enforces writing
1243                 // to dlcache only
1244                 // idea: support download of pk3 files using this protocol later
1245
1246         // note: the reason these loops skip already-loaded things is that it
1247         // enables this command to be issued during the game if desired
1248
1249         if (cl.downloadmodel_current < cl.loadmodel_total)
1250         {
1251                 // loading models
1252
1253                 for (;cl.downloadmodel_current < cl.loadmodel_total;cl.downloadmodel_current++)
1254                 {
1255                         if (aborteddownload)
1256                         {
1257
1258                                 if (cl.downloadmodel_current == 1)
1259                                 {
1260                                         // the worldmodel failed, but we need to set up anyway
1261                                         Mod_FreeQ3Shaders();
1262                                         CL_SetupWorldModel();
1263                                         if (!cl.loadfinished && cl_joinbeforedownloadsfinish.integer)
1264                                         {
1265                                                 cl.loadfinished = true;
1266                                                 // now issue the spawn to move on to signon 2 like normal
1267                                                 if (cls.netcon)
1268                                                         Cmd_ForwardStringToServer("prespawn");
1269                                         }
1270                                 }
1271                                 aborteddownload = false;
1272                                 continue;
1273                         }
1274                         if (cl.model_precache[cl.downloadmodel_current] && cl.model_precache[cl.downloadmodel_current]->Draw)
1275                                 continue;
1276                         CL_KeepaliveMessage(true);
1277                         if (cl.model_name[cl.downloadmodel_current][0] != '*' && strcmp(cl.model_name[cl.downloadmodel_current], "null") && !FS_FileExists(cl.model_name[cl.downloadmodel_current]))
1278                         {
1279                                 if (cl.downloadmodel_current == 1)
1280                                         Con_Printf("Map %s not found\n", cl.model_name[cl.downloadmodel_current]);
1281                                 else
1282                                         Con_Printf("Model %s not found\n", cl.model_name[cl.downloadmodel_current]);
1283                                 // regarding the * check: don't try to download submodels
1284                                 if (cl_serverextension_download.integer && cls.netcon && cl.model_name[cl.downloadmodel_current][0] != '*' && !sv.active)
1285                                 {
1286                                         Cmd_ForwardStringToServer(va(vabuf, sizeof(vabuf), "download %s", cl.model_name[cl.downloadmodel_current]));
1287                                         // we'll try loading again when the download finishes
1288                                         return;
1289                                 }
1290                         }
1291
1292                         if(cl.downloadmodel_current == 1)
1293                         {
1294                                 // they'll be soon loaded, but make sure we apply freshly downloaded shaders from a curled pk3
1295                                 Mod_FreeQ3Shaders();
1296                         }
1297
1298                         cl.model_precache[cl.downloadmodel_current] = Mod_ForName(cl.model_name[cl.downloadmodel_current], false, true, cl.model_name[cl.downloadmodel_current][0] == '*' ? cl.model_name[1] : NULL);
1299                         if (cl.downloadmodel_current == 1)
1300                         {
1301                                 // we now have the worldmodel so we can set up the game world
1302                                 // or maybe we do not have it (cl_serverextension_download 0)
1303                                 // then we need to continue loading ANYWAY!
1304                                 CL_SetupWorldModel();
1305                                 if (!cl.loadfinished && cl_joinbeforedownloadsfinish.integer)
1306                                 {
1307                                         cl.loadfinished = true;
1308                                         // now issue the spawn to move on to signon 2 like normal
1309                                         if (cls.netcon)
1310                                                 Cmd_ForwardStringToServer("prespawn");
1311                                 }
1312                         }
1313                 }
1314
1315                 // finished loading models
1316         }
1317
1318         if (cl.downloadsound_current < cl.loadsound_total)
1319         {
1320                 // loading sounds
1321
1322                 for (;cl.downloadsound_current < cl.loadsound_total;cl.downloadsound_current++)
1323                 {
1324                         char soundname[MAX_QPATH];
1325                         if (aborteddownload)
1326                         {
1327                                 aborteddownload = false;
1328                                 continue;
1329                         }
1330                         if (cl.sound_precache[cl.downloadsound_current] && S_IsSoundPrecached(cl.sound_precache[cl.downloadsound_current]))
1331                                 continue;
1332                         CL_KeepaliveMessage(true);
1333                         dpsnprintf(soundname, sizeof(soundname), "sound/%s", cl.sound_name[cl.downloadsound_current]);
1334                         if (!FS_FileExists(soundname) && !FS_FileExists(cl.sound_name[cl.downloadsound_current]))
1335                         {
1336                                 Con_Printf("Sound %s not found\n", soundname);
1337                                 if (cl_serverextension_download.integer && cls.netcon && !sv.active)
1338                                 {
1339                                         Cmd_ForwardStringToServer(va(vabuf, sizeof(vabuf), "download %s", soundname));
1340                                         // we'll try loading again when the download finishes
1341                                         return;
1342                                 }
1343                         }
1344                         cl.sound_precache[cl.downloadsound_current] = S_PrecacheSound(cl.sound_name[cl.downloadsound_current], false, true);
1345                 }
1346
1347                 // finished loading sounds
1348         }
1349
1350         SCR_PopLoadingScreen(false);
1351
1352         if (!cl.loadfinished)
1353         {
1354                 cl.loadfinished = true;
1355
1356                 // check memory integrity
1357                 Mem_CheckSentinelsGlobal();
1358
1359                 // now issue the spawn to move on to signon 2 like normal
1360                 if (cls.netcon)
1361                         Cmd_ForwardStringToServer("prespawn");
1362         }
1363 }
1364
1365 static void CL_BeginDownloads_f(void)
1366 {
1367         // prevent cl_begindownloads from being issued multiple times in one match
1368         // to prevent accidentally cancelled downloads
1369         if(cl.loadbegun)
1370                 Con_Printf("cl_begindownloads is only valid once per match\n");
1371         else
1372                 CL_BeginDownloads(false);
1373 }
1374
1375 static void CL_StopDownload(int size, int crc)
1376 {
1377         if (cls.qw_downloadmemory && cls.qw_downloadmemorycursize == size && CRC_Block(cls.qw_downloadmemory, cls.qw_downloadmemorycursize) == crc)
1378         {
1379                 int existingcrc;
1380                 size_t existingsize;
1381                 const char *extension;
1382
1383                 if(cls.qw_download_deflate)
1384                 {
1385                         unsigned char *out;
1386                         size_t inflated_size;
1387                         out = FS_Inflate(cls.qw_downloadmemory, cls.qw_downloadmemorycursize, &inflated_size, tempmempool);
1388                         Mem_Free(cls.qw_downloadmemory);
1389                         if(out)
1390                         {
1391                                 Con_Printf("Inflated download: new size: %u (%g%%)\n", (unsigned)inflated_size, 100.0 - 100.0*(cls.qw_downloadmemorycursize / (float)inflated_size));
1392                                 cls.qw_downloadmemory = out;
1393                                 cls.qw_downloadmemorycursize = (int)inflated_size;
1394                         }
1395                         else
1396                         {
1397                                 cls.qw_downloadmemory = NULL;
1398                                 cls.qw_downloadmemorycursize = 0;
1399                                 Con_Printf("Cannot inflate download, possibly corrupt or zlib not present\n");
1400                         }
1401                 }
1402
1403                 if(!cls.qw_downloadmemory)
1404                 {
1405                         Con_Printf("Download \"%s\" is corrupt (see above!)\n", cls.qw_downloadname);
1406                 }
1407                 else
1408                 {
1409                         crc = CRC_Block(cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
1410                         size = cls.qw_downloadmemorycursize;
1411                         // finished file
1412                         // save to disk only if we don't already have it
1413                         // (this is mainly for playing back demos)
1414                         existingcrc = FS_CRCFile(cls.qw_downloadname, &existingsize);
1415                         if (existingsize || IS_NEXUIZ_DERIVED(gamemode) || !strcmp(cls.qw_downloadname, csqc_progname.string))
1416                                 // let csprogs ALWAYS go to dlcache, to prevent "viral csprogs"; also, never put files outside dlcache for Nexuiz/Xonotic
1417                         {
1418                                 if ((int)existingsize != size || existingcrc != crc)
1419                                 {
1420                                         // we have a mismatching file, pick another name for it
1421                                         char name[MAX_QPATH*2];
1422                                         dpsnprintf(name, sizeof(name), "dlcache/%s.%i.%i", cls.qw_downloadname, size, crc);
1423                                         if (!FS_FileExists(name))
1424                                         {
1425                                                 Con_Printf("Downloaded \"%s\" (%i bytes, %i CRC)\n", name, size, crc);
1426                                                 FS_WriteFile(name, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
1427                                                 if(!strcmp(cls.qw_downloadname, csqc_progname.string))
1428                                                 {
1429                                                         if(cls.caughtcsprogsdata)
1430                                                                 Mem_Free(cls.caughtcsprogsdata);
1431                                                         cls.caughtcsprogsdata = (unsigned char *) Mem_Alloc(cls.permanentmempool, cls.qw_downloadmemorycursize);
1432                                                         memcpy(cls.caughtcsprogsdata, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
1433                                                         cls.caughtcsprogsdatasize = cls.qw_downloadmemorycursize;
1434                                                         Con_DPrintf("Buffered \"%s\"\n", name);
1435                                                 }
1436                                         }
1437                                 }
1438                         }
1439                         else
1440                         {
1441                                 // we either don't have it or have a mismatching file...
1442                                 // so it's time to accept the file
1443                                 // but if we already have a mismatching file we need to rename
1444                                 // this new one, and if we already have this file in renamed form,
1445                                 // we do nothing
1446                                 Con_Printf("Downloaded \"%s\" (%i bytes, %i CRC)\n", cls.qw_downloadname, size, crc);
1447                                 FS_WriteFile(cls.qw_downloadname, cls.qw_downloadmemory, cls.qw_downloadmemorycursize);
1448                                 extension = FS_FileExtension(cls.qw_downloadname);
1449                                 if (!strcasecmp(extension, "pak") || !strcasecmp(extension, "pk3"))
1450                                         FS_Rescan();
1451                         }
1452                 }
1453         }
1454         else if (cls.qw_downloadmemory && size)
1455         {
1456                 Con_Printf("Download \"%s\" is corrupt (%i bytes, %i CRC, should be %i bytes, %i CRC), discarding\n", cls.qw_downloadname, size, crc, (int)cls.qw_downloadmemorycursize, (int)CRC_Block(cls.qw_downloadmemory, cls.qw_downloadmemorycursize));
1457                 CL_BeginDownloads(true);
1458         }
1459
1460         if (cls.qw_downloadmemory)
1461                 Mem_Free(cls.qw_downloadmemory);
1462         cls.qw_downloadmemory = NULL;
1463         cls.qw_downloadname[0] = 0;
1464         cls.qw_downloadmemorymaxsize = 0;
1465         cls.qw_downloadmemorycursize = 0;
1466         cls.qw_downloadpercent = 0;
1467 }
1468
1469 static void CL_ParseDownload(void)
1470 {
1471         int i, start, size;
1472         static unsigned char data[NET_MAXMESSAGE];
1473         start = MSG_ReadLong(&cl_message);
1474         size = (unsigned short)MSG_ReadShort(&cl_message);
1475
1476         // record the start/size information to ack in the next input packet
1477         for (i = 0;i < CL_MAX_DOWNLOADACKS;i++)
1478         {
1479                 if (!cls.dp_downloadack[i].start && !cls.dp_downloadack[i].size)
1480                 {
1481                         cls.dp_downloadack[i].start = start;
1482                         cls.dp_downloadack[i].size = size;
1483                         break;
1484                 }
1485         }
1486
1487         MSG_ReadBytes(&cl_message, size, data);
1488
1489         if (!cls.qw_downloadname[0])
1490         {
1491                 if (size > 0)
1492                         Con_Printf("CL_ParseDownload: received %i bytes with no download active\n", size);
1493                 return;
1494         }
1495
1496         if (start + size > cls.qw_downloadmemorymaxsize)
1497                 Host_Error("corrupt download message\n");
1498
1499         // only advance cursize if the data is at the expected position
1500         // (gaps are unacceptable)
1501         memcpy(cls.qw_downloadmemory + start, data, size);
1502         cls.qw_downloadmemorycursize = start + size;
1503         cls.qw_downloadpercent = (int)floor((start+size) * 100.0 / cls.qw_downloadmemorymaxsize);
1504         cls.qw_downloadpercent = bound(0, cls.qw_downloadpercent, 100);
1505         cls.qw_downloadspeedcount += size;
1506 }
1507
1508 static void CL_DownloadBegin_f(void)
1509 {
1510         int size = atoi(Cmd_Argv(1));
1511
1512         if (size < 0 || size > 1<<30 || FS_CheckNastyPath(Cmd_Argv(2), false))
1513         {
1514                 Con_Printf("cl_downloadbegin: received bogus information\n");
1515                 CL_StopDownload(0, 0);
1516                 return;
1517         }
1518
1519         if (cls.qw_downloadname[0])
1520                 Con_Printf("Download of %s aborted\n", cls.qw_downloadname);
1521
1522         CL_StopDownload(0, 0);
1523
1524         // we're really beginning a download now, so initialize stuff
1525         strlcpy(cls.qw_downloadname, Cmd_Argv(2), sizeof(cls.qw_downloadname));
1526         cls.qw_downloadmemorymaxsize = size;
1527         cls.qw_downloadmemory = (unsigned char *) Mem_Alloc(cls.permanentmempool, cls.qw_downloadmemorymaxsize);
1528         cls.qw_downloadnumber++;
1529
1530         cls.qw_download_deflate = false;
1531         if(Cmd_Argc() >= 4)
1532         {
1533                 if(!strcmp(Cmd_Argv(3), "deflate"))
1534                         cls.qw_download_deflate = true;
1535                 // check further encodings here
1536         }
1537
1538         Cmd_ForwardStringToServer("sv_startdownload");
1539 }
1540
1541 static void CL_StopDownload_f(void)
1542 {
1543         Curl_CancelAll();
1544         if (cls.qw_downloadname[0])
1545         {
1546                 Con_Printf("Download of %s aborted\n", cls.qw_downloadname);
1547                 CL_StopDownload(0, 0);
1548         }
1549         CL_BeginDownloads(true);
1550 }
1551
1552 static void CL_DownloadFinished_f(void)
1553 {
1554         if (Cmd_Argc() < 3)
1555         {
1556                 Con_Printf("Malformed cl_downloadfinished command\n");
1557                 return;
1558         }
1559         CL_StopDownload(atoi(Cmd_Argv(1)), atoi(Cmd_Argv(2)));
1560         CL_BeginDownloads(false);
1561 }
1562
1563 static void CL_SendPlayerInfo(void)
1564 {
1565         char vabuf[1024];
1566         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1567         MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "name \"%s\"", cl_name.string));
1568
1569         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1570         MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "color %i %i", cl_color.integer >> 4, cl_color.integer & 15));
1571
1572         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1573         MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "rate %i", cl_rate.integer));
1574
1575         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1576         MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "rate_burstsize %i", cl_rate_burstsize.integer));
1577
1578         if (cl_pmodel.integer)
1579         {
1580                 MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1581                 MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "pmodel %i", cl_pmodel.integer));
1582         }
1583         if (*cl_playermodel.string)
1584         {
1585                 MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1586                 MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "playermodel %s", cl_playermodel.string));
1587         }
1588         if (*cl_playerskin.string)
1589         {
1590                 MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1591                 MSG_WriteString (&cls.netcon->message, va(vabuf, sizeof(vabuf), "playerskin %s", cl_playerskin.string));
1592         }
1593 }
1594
1595 /*
1596 =====================
1597 CL_SignonReply
1598
1599 An svc_signonnum has been received, perform a client side setup
1600 =====================
1601 */
1602 static void CL_SignonReply (void)
1603 {
1604         Con_DPrintf("CL_SignonReply: %i\n", cls.signon);
1605
1606         switch (cls.signon)
1607         {
1608         case 1:
1609                 if (cls.netcon)
1610                 {
1611                         // send player info before we begin downloads
1612                         // (so that the server can see the player name while downloading)
1613                         CL_SendPlayerInfo();
1614
1615                         // execute cl_begindownloads next frame
1616                         // (after any commands added by svc_stufftext have been executed)
1617                         // when done with downloads the "prespawn" will be sent
1618                         Cbuf_AddText("\ncl_begindownloads\n");
1619
1620                         //MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1621                         //MSG_WriteString (&cls.netcon->message, "prespawn");
1622                 }
1623                 else // playing a demo...  make sure loading occurs as soon as possible
1624                         CL_BeginDownloads(false);
1625                 break;
1626
1627         case 2:
1628                 if (cls.netcon)
1629                 {
1630                         // LordHavoc: quake sent the player info here but due to downloads
1631                         // it is sent earlier instead
1632                         // CL_SendPlayerInfo();
1633
1634                         // LordHavoc: changed to begin a loading stage and issue this when done
1635                         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1636                         MSG_WriteString (&cls.netcon->message, "spawn");
1637                 }
1638                 break;
1639
1640         case 3:
1641                 if (cls.netcon)
1642                 {
1643                         MSG_WriteByte (&cls.netcon->message, clc_stringcmd);
1644                         MSG_WriteString (&cls.netcon->message, "begin");
1645                 }
1646                 break;
1647
1648         case 4:
1649                 // after the level has been loaded, we shouldn't need the shaders, and
1650                 // if they are needed again they will be automatically loaded...
1651                 // we also don't need the unused models or sounds from the last level
1652                 Mod_FreeQ3Shaders();
1653                 Mod_PurgeUnused();
1654                 S_PurgeUnused();
1655
1656                 Con_ClearNotify();
1657                 if (COM_CheckParm("-profilegameonly"))
1658                         Sys_AllowProfiling(true);
1659                 break;
1660         }
1661 }
1662
1663 /*
1664 ==================
1665 CL_ParseServerInfo
1666 ==================
1667 */
1668 static void CL_ParseServerInfo (void)
1669 {
1670         char *str;
1671         int i;
1672         protocolversion_t protocol;
1673         int nummodels, numsounds;
1674         char vabuf[1024];
1675
1676         // if we start loading a level and a video is still playing, stop it
1677         CL_VideoStop();
1678
1679         Con_DPrint("Serverinfo packet received.\n");
1680         Collision_Cache_Reset(true);
1681
1682         // if server is active, we already began a loading plaque
1683         if (!sv.active)
1684         {
1685                 SCR_BeginLoadingPlaque(false);
1686                 S_StopAllSounds();
1687                 // free q3 shaders so that any newly downloaded shaders will be active
1688                 Mod_FreeQ3Shaders();
1689         }
1690
1691         // check memory integrity
1692         Mem_CheckSentinelsGlobal();
1693
1694         // clear cl_serverextension cvars
1695         Cvar_SetValueQuick(&cl_serverextension_download, 0);
1696
1697 //
1698 // wipe the client_state_t struct
1699 //
1700         CL_ClearState ();
1701
1702 // parse protocol version number
1703         i = MSG_ReadLong(&cl_message);
1704         protocol = Protocol_EnumForNumber(i);
1705         if (protocol == PROTOCOL_UNKNOWN)
1706         {
1707                 Host_Error("CL_ParseServerInfo: Server is unrecognized protocol number (%i)", i);
1708                 return;
1709         }
1710         // hack for unmarked Nehahra movie demos which had a custom protocol
1711         if (protocol == PROTOCOL_QUAKEDP && cls.demoplayback && gamemode == GAME_NEHAHRA)
1712                 protocol = PROTOCOL_NEHAHRAMOVIE;
1713         cls.protocol = protocol;
1714         Con_DPrintf("Server protocol is %s\n", Protocol_NameForEnum(cls.protocol));
1715
1716         cl.num_entities = 1;
1717
1718         if (protocol == PROTOCOL_QUAKEWORLD)
1719         {
1720                 char gamedir[1][MAX_QPATH];
1721
1722                 cl.qw_servercount = MSG_ReadLong(&cl_message);
1723
1724                 str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1725                 Con_Printf("server gamedir is %s\n", str);
1726                 strlcpy(gamedir[0], str, sizeof(gamedir[0]));
1727
1728                 // change gamedir if needed
1729                 if (!FS_ChangeGameDirs(1, gamedir, true, false))
1730                         Host_Error("CL_ParseServerInfo: unable to switch to server specified gamedir");
1731
1732                 cl.gametype = GAME_DEATHMATCH;
1733                 cl.maxclients = 32;
1734
1735                 // parse player number
1736                 i = MSG_ReadByte(&cl_message);
1737                 // cl.qw_spectator is an unneeded flag, cl.scores[cl.playerentity].qw_spectator works better (it can be updated by the server during the game)
1738                 //cl.qw_spectator = (i & 128) != 0;
1739                 cl.realplayerentity = cl.playerentity = cl.viewentity = (i & 127) + 1;
1740                 cl.scores = (scoreboard_t *)Mem_Alloc(cls.levelmempool, cl.maxclients*sizeof(*cl.scores));
1741
1742                 // get the full level name
1743                 str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1744                 strlcpy (cl.worldmessage, str, sizeof(cl.worldmessage));
1745
1746                 // get the movevars that are defined in the qw protocol
1747                 cl.movevars_gravity            = MSG_ReadFloat(&cl_message);
1748                 cl.movevars_stopspeed          = MSG_ReadFloat(&cl_message);
1749                 cl.movevars_maxspeed           = MSG_ReadFloat(&cl_message);
1750                 cl.movevars_spectatormaxspeed  = MSG_ReadFloat(&cl_message);
1751                 cl.movevars_accelerate         = MSG_ReadFloat(&cl_message);
1752                 cl.movevars_airaccelerate      = MSG_ReadFloat(&cl_message);
1753                 cl.movevars_wateraccelerate    = MSG_ReadFloat(&cl_message);
1754                 cl.movevars_friction           = MSG_ReadFloat(&cl_message);
1755                 cl.movevars_waterfriction      = MSG_ReadFloat(&cl_message);
1756                 cl.movevars_entgravity         = MSG_ReadFloat(&cl_message);
1757
1758                 // other movevars not in the protocol...
1759                 cl.movevars_wallfriction = 0;
1760                 cl.movevars_timescale = 1;
1761                 cl.movevars_jumpvelocity = 270;
1762                 cl.movevars_edgefriction = 1;
1763                 cl.movevars_maxairspeed = 30;
1764                 cl.movevars_stepheight = 18;
1765                 cl.movevars_airaccel_qw = 1;
1766                 cl.movevars_airaccel_sideways_friction = 0;
1767
1768                 // seperate the printfs so the server message can have a color
1769                 Con_Printf("\n\n<===================================>\n\n\2%s\n", str);
1770
1771                 // check memory integrity
1772                 Mem_CheckSentinelsGlobal();
1773
1774                 if (cls.netcon)
1775                 {
1776                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
1777                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "soundlist %i %i", cl.qw_servercount, 0));
1778                 }
1779
1780                 cl.loadbegun = false;
1781                 cl.loadfinished = false;
1782
1783                 cls.state = ca_connected;
1784                 cls.signon = 1;
1785
1786                 // note: on QW protocol we can't set up the gameworld until after
1787                 // downloads finish...
1788                 // (we don't even know the name of the map yet)
1789                 // this also means cl_autodemo does not work on QW protocol...
1790
1791                 strlcpy(cl.worldname, "", sizeof(cl.worldname));
1792                 strlcpy(cl.worldnamenoextension, "", sizeof(cl.worldnamenoextension));
1793                 strlcpy(cl.worldbasename, "qw", sizeof(cl.worldbasename));
1794                 Cvar_SetQuick(&cl_worldname, cl.worldname);
1795                 Cvar_SetQuick(&cl_worldnamenoextension, cl.worldnamenoextension);
1796                 Cvar_SetQuick(&cl_worldbasename, cl.worldbasename);
1797
1798                 // check memory integrity
1799                 Mem_CheckSentinelsGlobal();
1800         }
1801         else
1802         {
1803         // parse maxclients
1804                 cl.maxclients = MSG_ReadByte(&cl_message);
1805                 if (cl.maxclients < 1 || cl.maxclients > MAX_SCOREBOARD)
1806                 {
1807                         Host_Error("Bad maxclients (%u) from server", cl.maxclients);
1808                         return;
1809                 }
1810                 cl.scores = (scoreboard_t *)Mem_Alloc(cls.levelmempool, cl.maxclients*sizeof(*cl.scores));
1811
1812         // parse gametype
1813                 cl.gametype = MSG_ReadByte(&cl_message);
1814                 // the original id singleplayer demos are bugged and contain
1815                 // GAME_DEATHMATCH even for singleplayer
1816                 if (cl.maxclients == 1 && cls.protocol == PROTOCOL_QUAKE)
1817                         cl.gametype = GAME_COOP;
1818
1819         // parse signon message
1820                 str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1821                 strlcpy (cl.worldmessage, str, sizeof(cl.worldmessage));
1822
1823         // seperate the printfs so the server message can have a color
1824                 if (cls.protocol != PROTOCOL_NEHAHRAMOVIE) // no messages when playing the Nehahra movie
1825                         Con_Printf("\n<===================================>\n\n\2%s\n", str);
1826
1827                 // check memory integrity
1828                 Mem_CheckSentinelsGlobal();
1829
1830                 // parse model precache list
1831                 for (nummodels=1 ; ; nummodels++)
1832                 {
1833                         str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1834                         if (!str[0])
1835                                 break;
1836                         if (nummodels==MAX_MODELS)
1837                                 Host_Error ("Server sent too many model precaches");
1838                         if (strlen(str) >= MAX_QPATH)
1839                                 Host_Error ("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
1840                         strlcpy (cl.model_name[nummodels], str, sizeof (cl.model_name[nummodels]));
1841                 }
1842                 // parse sound precache list
1843                 for (numsounds=1 ; ; numsounds++)
1844                 {
1845                         str = MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring));
1846                         if (!str[0])
1847                                 break;
1848                         if (numsounds==MAX_SOUNDS)
1849                                 Host_Error("Server sent too many sound precaches");
1850                         if (strlen(str) >= MAX_QPATH)
1851                                 Host_Error("Server sent a precache name of %i characters (max %i)", (int)strlen(str), MAX_QPATH - 1);
1852                         strlcpy (cl.sound_name[numsounds], str, sizeof (cl.sound_name[numsounds]));
1853                 }
1854
1855                 // set the base name for level-specific things...  this gets updated again by CL_SetupWorldModel later
1856                 strlcpy(cl.worldname, cl.model_name[1], sizeof(cl.worldname));
1857                 FS_StripExtension(cl.worldname, cl.worldnamenoextension, sizeof(cl.worldnamenoextension));
1858                 strlcpy(cl.worldbasename, !strncmp(cl.worldnamenoextension, "maps/", 5) ? cl.worldnamenoextension + 5 : cl.worldnamenoextension, sizeof(cl.worldbasename));
1859                 Cvar_SetQuick(&cl_worldmessage, cl.worldmessage);
1860                 Cvar_SetQuick(&cl_worldname, cl.worldname);
1861                 Cvar_SetQuick(&cl_worldnamenoextension, cl.worldnamenoextension);
1862                 Cvar_SetQuick(&cl_worldbasename, cl.worldbasename);
1863
1864                 // touch all of the precached models that are still loaded so we can free
1865                 // anything that isn't needed
1866                 if (!sv.active)
1867                         Mod_ClearUsed();
1868                 for (i = 1;i < nummodels;i++)
1869                         Mod_FindName(cl.model_name[i], cl.model_name[i][0] == '*' ? cl.model_name[1] : NULL);
1870                 // precache any models used by the client (this also marks them used)
1871                 cl.model_bolt = Mod_ForName("progs/bolt.mdl", false, false, NULL);
1872                 cl.model_bolt2 = Mod_ForName("progs/bolt2.mdl", false, false, NULL);
1873                 cl.model_bolt3 = Mod_ForName("progs/bolt3.mdl", false, false, NULL);
1874                 cl.model_beam = Mod_ForName("progs/beam.mdl", false, false, NULL);
1875
1876                 // we purge the models and sounds later in CL_SignonReply
1877                 //Mod_PurgeUnused();
1878                 //S_PurgeUnused();
1879
1880                 // clear sound usage flags for purging of unused sounds
1881                 S_ClearUsed();
1882
1883                 // precache any sounds used by the client
1884                 cl.sfx_wizhit = S_PrecacheSound(cl_sound_wizardhit.string, false, true);
1885                 cl.sfx_knighthit = S_PrecacheSound(cl_sound_hknighthit.string, false, true);
1886                 cl.sfx_tink1 = S_PrecacheSound(cl_sound_tink1.string, false, true);
1887                 cl.sfx_ric1 = S_PrecacheSound(cl_sound_ric1.string, false, true);
1888                 cl.sfx_ric2 = S_PrecacheSound(cl_sound_ric2.string, false, true);
1889                 cl.sfx_ric3 = S_PrecacheSound(cl_sound_ric3.string, false, true);
1890                 cl.sfx_r_exp3 = S_PrecacheSound(cl_sound_r_exp3.string, false, true);
1891
1892                 // sounds used by the game
1893                 for (i = 1;i < MAX_SOUNDS && cl.sound_name[i][0];i++)
1894                         cl.sound_precache[i] = S_PrecacheSound(cl.sound_name[i], true, true);
1895
1896                 // now we try to load everything that is new
1897                 cl.loadmodel_current = 1;
1898                 cl.downloadmodel_current = 1;
1899                 cl.loadmodel_total = nummodels;
1900                 cl.loadsound_current = 1;
1901                 cl.downloadsound_current = 1;
1902                 cl.loadsound_total = numsounds;
1903                 cl.downloadcsqc = true;
1904                 cl.loadbegun = false;
1905                 cl.loadfinished = false;
1906                 cl.loadcsqc = true;
1907
1908                 // check memory integrity
1909                 Mem_CheckSentinelsGlobal();
1910
1911         // if cl_autodemo is set, automatically start recording a demo if one isn't being recorded already
1912                 if (cl_autodemo.integer && cls.netcon && cls.protocol != PROTOCOL_QUAKEWORLD)
1913                 {
1914                         char demofile[MAX_OSPATH];
1915
1916                         if (cls.demorecording)
1917                         {
1918                                 // finish the previous level's demo file
1919                                 CL_Stop_f();
1920                         }
1921
1922                         // start a new demo file
1923                         dpsnprintf (demofile, sizeof(demofile), "%s_%s.dem", Sys_TimeString (cl_autodemo_nameformat.string), cl.worldbasename);
1924
1925                         Con_Printf ("Auto-recording to %s.\n", demofile);
1926
1927                         // Reset bit 0 for every new demo
1928                         Cvar_SetValueQuick(&cl_autodemo_delete,
1929                                 (cl_autodemo_delete.integer & ~0x1)
1930                                 |
1931                                 ((cl_autodemo_delete.integer & 0x2) ? 0x1 : 0)
1932                         );
1933
1934                         cls.demofile = FS_OpenRealFile(demofile, "wb", false);
1935                         if (cls.demofile)
1936                         {
1937                                 cls.forcetrack = -1;
1938                                 FS_Printf (cls.demofile, "%i\n", cls.forcetrack);
1939                                 cls.demorecording = true;
1940                                 strlcpy(cls.demoname, demofile, sizeof(cls.demoname));
1941                                 cls.demo_lastcsprogssize = -1;
1942                                 cls.demo_lastcsprogscrc = -1;
1943                         }
1944                         else
1945                                 Con_Print ("ERROR: couldn't open.\n");
1946                 }
1947         }
1948         cl.islocalgame = NetConn_IsLocalGame();
1949 }
1950
1951 void CL_ValidateState(entity_state_t *s)
1952 {
1953         dp_model_t *model;
1954
1955         if (!s->active)
1956                 return;
1957
1958         if (s->modelindex >= MAX_MODELS)
1959                 Host_Error("CL_ValidateState: modelindex (%i) >= MAX_MODELS (%i)\n", s->modelindex, MAX_MODELS);
1960
1961         // these warnings are only warnings, no corrections are made to the state
1962         // because states are often copied for decoding, which otherwise would
1963         // propogate some of the corrections accidentally
1964         // (this used to happen, sometimes affecting skin and frame)
1965
1966         // colormap is client index + 1
1967         if (!(s->flags & RENDER_COLORMAPPED) && s->colormap > cl.maxclients)
1968                 Con_DPrintf("CL_ValidateState: colormap (%i) > cl.maxclients (%i)\n", s->colormap, cl.maxclients);
1969
1970         if (developer_extra.integer)
1971         {
1972                 model = CL_GetModelByIndex(s->modelindex);
1973                 if (model && model->type && s->frame >= model->numframes)
1974                         Con_DPrintf("CL_ValidateState: no such frame %i in \"%s\" (which has %i frames)\n", s->frame, model->name, model->numframes);
1975                 if (model && model->type && s->skin > 0 && s->skin >= model->numskins && !(s->lightpflags & PFLAGS_FULLDYNAMIC))
1976                         Con_DPrintf("CL_ValidateState: no such skin %i in \"%s\" (which has %i skins)\n", s->skin, model->name, model->numskins);
1977         }
1978 }
1979
1980 void CL_MoveLerpEntityStates(entity_t *ent)
1981 {
1982         float odelta[3], adelta[3];
1983         VectorSubtract(ent->state_current.origin, ent->persistent.neworigin, odelta);
1984         VectorSubtract(ent->state_current.angles, ent->persistent.newangles, adelta);
1985         if (!ent->state_previous.active || ent->state_previous.modelindex != ent->state_current.modelindex)
1986         {
1987                 // reset all persistent stuff if this is a new entity
1988                 ent->persistent.lerpdeltatime = 0;
1989                 ent->persistent.lerpstarttime = cl.mtime[1];
1990                 VectorCopy(ent->state_current.origin, ent->persistent.oldorigin);
1991                 VectorCopy(ent->state_current.angles, ent->persistent.oldangles);
1992                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
1993                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
1994                 // reset animation interpolation as well
1995                 ent->render.framegroupblend[0].frame = ent->render.framegroupblend[1].frame = ent->state_current.frame;
1996                 ent->render.framegroupblend[0].start = ent->render.framegroupblend[1].start = cl.time;
1997                 ent->render.framegroupblend[0].lerp = 1;ent->render.framegroupblend[1].lerp = 0;
1998                 ent->render.shadertime = cl.time;
1999                 // reset various persistent stuff
2000                 ent->persistent.muzzleflash = 0;
2001                 ent->persistent.trail_allowed = false;
2002         }
2003         else if ((ent->state_previous.effects & EF_TELEPORT_BIT) != (ent->state_current.effects & EF_TELEPORT_BIT))
2004         {
2005                 // don't interpolate the move
2006                 ent->persistent.lerpdeltatime = 0;
2007                 ent->persistent.lerpstarttime = cl.mtime[1];
2008                 VectorCopy(ent->state_current.origin, ent->persistent.oldorigin);
2009                 VectorCopy(ent->state_current.angles, ent->persistent.oldangles);
2010                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
2011                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
2012                 ent->persistent.trail_allowed = false;
2013
2014                 // if(ent->state_current.frame != ent->state_previous.frame)
2015                 // do this even if we did change the frame
2016                 // teleport bit is only used if an animation restart, or a jump, is necessary
2017                 // so it should be always harmless to do this
2018                 {
2019                         ent->render.framegroupblend[0].frame = ent->render.framegroupblend[1].frame = ent->state_current.frame;
2020                         ent->render.framegroupblend[0].start = ent->render.framegroupblend[1].start = cl.time;
2021                         ent->render.framegroupblend[0].lerp = 1;ent->render.framegroupblend[1].lerp = 0;
2022                 }
2023
2024                 // note that this case must do everything the following case does too
2025         }
2026         else if ((ent->state_previous.effects & EF_RESTARTANIM_BIT) != (ent->state_current.effects & EF_RESTARTANIM_BIT))
2027         {
2028                 ent->render.framegroupblend[1] = ent->render.framegroupblend[0];
2029                 ent->render.framegroupblend[1].lerp = 1;
2030                 ent->render.framegroupblend[0].frame = ent->state_current.frame;
2031                 ent->render.framegroupblend[0].start = cl.time;
2032                 ent->render.framegroupblend[0].lerp = 0;
2033         }
2034         else if (DotProduct(odelta, odelta) > 1000*1000
2035                 || (cl.fixangle[0] && !cl.fixangle[1])
2036                 || (ent->state_previous.tagindex != ent->state_current.tagindex)
2037                 || (ent->state_previous.tagentity != ent->state_current.tagentity))
2038         {
2039                 // don't interpolate the move
2040                 // (the fixangle[] check detects teleports, but not constant fixangles
2041                 //  such as when spectating)
2042                 ent->persistent.lerpdeltatime = 0;
2043                 ent->persistent.lerpstarttime = cl.mtime[1];
2044                 VectorCopy(ent->state_current.origin, ent->persistent.oldorigin);
2045                 VectorCopy(ent->state_current.angles, ent->persistent.oldangles);
2046                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
2047                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
2048                 ent->persistent.trail_allowed = false;
2049         }
2050         else if (ent->state_current.flags & RENDER_STEP)
2051         {
2052                 // monster interpolation
2053                 if (DotProduct(odelta, odelta) + DotProduct(adelta, adelta) > 0.01)
2054                 {
2055                         ent->persistent.lerpdeltatime = bound(0, cl.mtime[1] - ent->persistent.lerpstarttime, 0.1);
2056                         ent->persistent.lerpstarttime = cl.mtime[1];
2057                         VectorCopy(ent->persistent.neworigin, ent->persistent.oldorigin);
2058                         VectorCopy(ent->persistent.newangles, ent->persistent.oldangles);
2059                         VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
2060                         VectorCopy(ent->state_current.angles, ent->persistent.newangles);
2061                 }
2062         }
2063         else
2064         {
2065                 // not a monster
2066                 ent->persistent.lerpstarttime = ent->state_previous.time;
2067                 // no lerp if it's singleplayer
2068                 if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
2069                         ent->persistent.lerpdeltatime = 0;
2070                 else
2071                         ent->persistent.lerpdeltatime = bound(0, ent->state_current.time - ent->state_previous.time, 0.1);
2072                 VectorCopy(ent->persistent.neworigin, ent->persistent.oldorigin);
2073                 VectorCopy(ent->persistent.newangles, ent->persistent.oldangles);
2074                 VectorCopy(ent->state_current.origin, ent->persistent.neworigin);
2075                 VectorCopy(ent->state_current.angles, ent->persistent.newangles);
2076         }
2077         // trigger muzzleflash effect if necessary
2078         if (ent->state_current.effects & EF_MUZZLEFLASH)
2079                 ent->persistent.muzzleflash = 1;
2080
2081         // restart animation bit
2082         if ((ent->state_previous.effects & EF_RESTARTANIM_BIT) != (ent->state_current.effects & EF_RESTARTANIM_BIT))
2083         {
2084                 ent->render.framegroupblend[1] = ent->render.framegroupblend[0];
2085                 ent->render.framegroupblend[1].lerp = 1;
2086                 ent->render.framegroupblend[0].frame = ent->state_current.frame;
2087                 ent->render.framegroupblend[0].start = cl.time;
2088                 ent->render.framegroupblend[0].lerp = 0;
2089         }
2090 }
2091
2092 /*
2093 ==================
2094 CL_ParseBaseline
2095 ==================
2096 */
2097 static void CL_ParseBaseline (entity_t *ent, int large)
2098 {
2099         int i;
2100
2101         ent->state_baseline = defaultstate;
2102         // FIXME: set ent->state_baseline.number?
2103         ent->state_baseline.active = true;
2104         if (large)
2105         {
2106                 ent->state_baseline.modelindex = (unsigned short) MSG_ReadShort(&cl_message);
2107                 ent->state_baseline.frame = (unsigned short) MSG_ReadShort(&cl_message);
2108         }
2109         else if (cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
2110         {
2111                 ent->state_baseline.modelindex = (unsigned short) MSG_ReadShort(&cl_message);
2112                 ent->state_baseline.frame = MSG_ReadByte(&cl_message);
2113         }
2114         else
2115         {
2116                 ent->state_baseline.modelindex = MSG_ReadByte(&cl_message);
2117                 ent->state_baseline.frame = MSG_ReadByte(&cl_message);
2118         }
2119         ent->state_baseline.colormap = MSG_ReadByte(&cl_message);
2120         ent->state_baseline.skin = MSG_ReadByte(&cl_message);
2121         for (i = 0;i < 3;i++)
2122         {
2123                 ent->state_baseline.origin[i] = MSG_ReadCoord(&cl_message, cls.protocol);
2124                 ent->state_baseline.angles[i] = MSG_ReadAngle(&cl_message, cls.protocol);
2125         }
2126         ent->state_previous = ent->state_current = ent->state_baseline;
2127 }
2128
2129
2130 /*
2131 ==================
2132 CL_ParseClientdata
2133
2134 Server information pertaining to this client only
2135 ==================
2136 */
2137 static void CL_ParseClientdata (void)
2138 {
2139         int i, bits;
2140
2141         VectorCopy (cl.mpunchangle[0], cl.mpunchangle[1]);
2142         VectorCopy (cl.mpunchvector[0], cl.mpunchvector[1]);
2143         VectorCopy (cl.mvelocity[0], cl.mvelocity[1]);
2144         cl.mviewzoom[1] = cl.mviewzoom[0];
2145
2146         if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4 || cls.protocol == PROTOCOL_DARKPLACES5)
2147         {
2148                 cl.stats[STAT_VIEWHEIGHT] = DEFAULT_VIEWHEIGHT;
2149                 cl.stats[STAT_ITEMS] = 0;
2150                 cl.stats[STAT_VIEWZOOM] = 255;
2151         }
2152         cl.idealpitch = 0;
2153         cl.mpunchangle[0][0] = 0;
2154         cl.mpunchangle[0][1] = 0;
2155         cl.mpunchangle[0][2] = 0;
2156         cl.mpunchvector[0][0] = 0;
2157         cl.mpunchvector[0][1] = 0;
2158         cl.mpunchvector[0][2] = 0;
2159         cl.mvelocity[0][0] = 0;
2160         cl.mvelocity[0][1] = 0;
2161         cl.mvelocity[0][2] = 0;
2162         cl.mviewzoom[0] = 1;
2163
2164         bits = (unsigned short) MSG_ReadShort(&cl_message);
2165         if (bits & SU_EXTEND1)
2166                 bits |= (MSG_ReadByte(&cl_message) << 16);
2167         if (bits & SU_EXTEND2)
2168                 bits |= (MSG_ReadByte(&cl_message) << 24);
2169
2170         if (bits & SU_VIEWHEIGHT)
2171                 cl.stats[STAT_VIEWHEIGHT] = MSG_ReadChar(&cl_message);
2172
2173         if (bits & SU_IDEALPITCH)
2174                 cl.idealpitch = MSG_ReadChar(&cl_message);
2175
2176         for (i = 0;i < 3;i++)
2177         {
2178                 if (bits & (SU_PUNCH1<<i) )
2179                 {
2180                         if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
2181                                 cl.mpunchangle[0][i] = MSG_ReadChar(&cl_message);
2182                         else
2183                                 cl.mpunchangle[0][i] = MSG_ReadAngle16i(&cl_message);
2184                 }
2185                 if (bits & (SU_PUNCHVEC1<<i))
2186                 {
2187                         if (cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
2188                                 cl.mpunchvector[0][i] = MSG_ReadCoord16i(&cl_message);
2189                         else
2190                                 cl.mpunchvector[0][i] = MSG_ReadCoord32f(&cl_message);
2191                 }
2192                 if (bits & (SU_VELOCITY1<<i) )
2193                 {
2194                         if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
2195                                 cl.mvelocity[0][i] = MSG_ReadChar(&cl_message)*16;
2196                         else
2197                                 cl.mvelocity[0][i] = MSG_ReadCoord32f(&cl_message);
2198                 }
2199         }
2200
2201         // LordHavoc: hipnotic demos don't have this bit set but should
2202         if (bits & SU_ITEMS || cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4 || cls.protocol == PROTOCOL_DARKPLACES5)
2203                 cl.stats[STAT_ITEMS] = MSG_ReadLong(&cl_message);
2204
2205         cl.onground = (bits & SU_ONGROUND) != 0;
2206         cl.inwater = (bits & SU_INWATER) != 0;
2207
2208         if (cls.protocol == PROTOCOL_DARKPLACES5)
2209         {
2210                 cl.stats[STAT_WEAPONFRAME] = (bits & SU_WEAPONFRAME) ? MSG_ReadShort(&cl_message) : 0;
2211                 cl.stats[STAT_ARMOR] = (bits & SU_ARMOR) ? MSG_ReadShort(&cl_message) : 0;
2212                 cl.stats[STAT_WEAPON] = (bits & SU_WEAPON) ? MSG_ReadShort(&cl_message) : 0;
2213                 cl.stats[STAT_HEALTH] = MSG_ReadShort(&cl_message);
2214                 cl.stats[STAT_AMMO] = MSG_ReadShort(&cl_message);
2215                 cl.stats[STAT_SHELLS] = MSG_ReadShort(&cl_message);
2216                 cl.stats[STAT_NAILS] = MSG_ReadShort(&cl_message);
2217                 cl.stats[STAT_ROCKETS] = MSG_ReadShort(&cl_message);
2218                 cl.stats[STAT_CELLS] = MSG_ReadShort(&cl_message);
2219                 cl.stats[STAT_ACTIVEWEAPON] = (unsigned short) MSG_ReadShort(&cl_message);
2220         }
2221         else if (cls.protocol == PROTOCOL_QUAKE || cls.protocol == PROTOCOL_QUAKEDP || cls.protocol == PROTOCOL_NEHAHRAMOVIE || cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3 || cls.protocol == PROTOCOL_DARKPLACES1 || cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
2222         {
2223                 cl.stats[STAT_WEAPONFRAME] = (bits & SU_WEAPONFRAME) ? MSG_ReadByte(&cl_message) : 0;
2224                 cl.stats[STAT_ARMOR] = (bits & SU_ARMOR) ? MSG_ReadByte(&cl_message) : 0;
2225                 if (cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
2226                         cl.stats[STAT_WEAPON] = (bits & SU_WEAPON) ? (unsigned short)MSG_ReadShort(&cl_message) : 0;
2227                 else
2228                         cl.stats[STAT_WEAPON] = (bits & SU_WEAPON) ? MSG_ReadByte(&cl_message) : 0;
2229                 cl.stats[STAT_HEALTH] = MSG_ReadShort(&cl_message);
2230                 cl.stats[STAT_AMMO] = MSG_ReadByte(&cl_message);
2231                 cl.stats[STAT_SHELLS] = MSG_ReadByte(&cl_message);
2232                 cl.stats[STAT_NAILS] = MSG_ReadByte(&cl_message);
2233                 cl.stats[STAT_ROCKETS] = MSG_ReadByte(&cl_message);
2234                 cl.stats[STAT_CELLS] = MSG_ReadByte(&cl_message);
2235                 if (gamemode == GAME_HIPNOTIC || gamemode == GAME_ROGUE || gamemode == GAME_QUOTH || IS_OLDNEXUIZ_DERIVED(gamemode))
2236                         cl.stats[STAT_ACTIVEWEAPON] = (1<<MSG_ReadByte(&cl_message));
2237                 else
2238                         cl.stats[STAT_ACTIVEWEAPON] = MSG_ReadByte(&cl_message);
2239         }
2240
2241         if (bits & SU_VIEWZOOM)
2242         {
2243                 if (cls.protocol == PROTOCOL_DARKPLACES2 || cls.protocol == PROTOCOL_DARKPLACES3 || cls.protocol == PROTOCOL_DARKPLACES4)
2244                         cl.stats[STAT_VIEWZOOM] = MSG_ReadByte(&cl_message);
2245                 else
2246                         cl.stats[STAT_VIEWZOOM] = (unsigned short) MSG_ReadShort(&cl_message);
2247         }
2248
2249         // viewzoom interpolation
2250         cl.mviewzoom[0] = (float) max(cl.stats[STAT_VIEWZOOM], 2) * (1.0f / 255.0f);
2251 }
2252
2253 /*
2254 =====================
2255 CL_ParseStatic
2256 =====================
2257 */
2258 static void CL_ParseStatic (int large)
2259 {
2260         entity_t *ent;
2261
2262         if (cl.num_static_entities >= cl.max_static_entities)
2263                 Host_Error ("Too many static entities");
2264         ent = &cl.static_entities[cl.num_static_entities++];
2265         CL_ParseBaseline (ent, large);
2266
2267         if (ent->state_baseline.modelindex == 0)
2268         {
2269                 Con_DPrintf("svc_parsestatic: static entity without model at %f %f %f\n", ent->state_baseline.origin[0], ent->state_baseline.origin[1], ent->state_baseline.origin[2]);
2270                 cl.num_static_entities--;
2271                 // This is definitely a cheesy way to conserve resources...
2272                 return;
2273         }
2274
2275 // copy it to the current state
2276         ent->render.model = CL_GetModelByIndex(ent->state_baseline.modelindex);
2277         ent->render.framegroupblend[0].frame = ent->state_baseline.frame;
2278         ent->render.framegroupblend[0].lerp = 1;
2279         // make torchs play out of sync
2280         ent->render.framegroupblend[0].start = lhrandom(-10, -1);
2281         ent->render.skinnum = ent->state_baseline.skin;
2282         ent->render.effects = ent->state_baseline.effects;
2283         ent->render.alpha = 1;
2284
2285         //VectorCopy (ent->state_baseline.origin, ent->render.origin);
2286         //VectorCopy (ent->state_baseline.angles, ent->render.angles);
2287
2288         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, ent->state_baseline.origin[0], ent->state_baseline.origin[1], ent->state_baseline.origin[2], ent->state_baseline.angles[0], ent->state_baseline.angles[1], ent->state_baseline.angles[2], 1);
2289         ent->render.allowdecals = true;
2290         CL_UpdateRenderEntity(&ent->render);
2291 }
2292
2293 /*
2294 ===================
2295 CL_ParseStaticSound
2296 ===================
2297 */
2298 static void CL_ParseStaticSound (int large)
2299 {
2300         vec3_t          org;
2301         int                     sound_num, vol, atten;
2302
2303         MSG_ReadVector(&cl_message, org, cls.protocol);
2304         if (large || cls.protocol == PROTOCOL_NEHAHRABJP2)
2305                 sound_num = (unsigned short) MSG_ReadShort(&cl_message);
2306         else
2307                 sound_num = MSG_ReadByte(&cl_message);
2308
2309         if (sound_num < 0 || sound_num >= MAX_SOUNDS)
2310         {
2311                 Con_Printf("CL_ParseStaticSound: sound_num(%i) >= MAX_SOUNDS (%i)\n", sound_num, MAX_SOUNDS);
2312                 return;
2313         }
2314
2315         vol = MSG_ReadByte(&cl_message);
2316         atten = MSG_ReadByte(&cl_message);
2317
2318         S_StaticSound (cl.sound_precache[sound_num], org, vol/255.0f, atten);
2319 }
2320
2321 static void CL_ParseEffect (void)
2322 {
2323         vec3_t          org;
2324         int                     modelindex, startframe, framecount, framerate;
2325
2326         MSG_ReadVector(&cl_message, org, cls.protocol);
2327         modelindex = MSG_ReadByte(&cl_message);
2328         startframe = MSG_ReadByte(&cl_message);
2329         framecount = MSG_ReadByte(&cl_message);
2330         framerate = MSG_ReadByte(&cl_message);
2331
2332         CL_Effect(org, modelindex, startframe, framecount, framerate);
2333 }
2334
2335 static void CL_ParseEffect2 (void)
2336 {
2337         vec3_t          org;
2338         int                     modelindex, startframe, framecount, framerate;
2339
2340         MSG_ReadVector(&cl_message, org, cls.protocol);
2341         modelindex = (unsigned short) MSG_ReadShort(&cl_message);
2342         startframe = (unsigned short) MSG_ReadShort(&cl_message);
2343         framecount = MSG_ReadByte(&cl_message);
2344         framerate = MSG_ReadByte(&cl_message);
2345
2346         CL_Effect(org, modelindex, startframe, framecount, framerate);
2347 }
2348
2349 void CL_NewBeam (int ent, vec3_t start, vec3_t end, dp_model_t *m, int lightning)
2350 {
2351         int i;
2352         beam_t *b = NULL;
2353
2354         if (ent >= MAX_EDICTS)
2355         {
2356                 Con_Printf("CL_NewBeam: invalid entity number %i\n", ent);
2357                 ent = 0;
2358         }
2359
2360         if (ent >= cl.max_entities)
2361                 CL_ExpandEntities(ent);
2362
2363         // override any beam with the same entity
2364         i = cl.max_beams;
2365         if (ent)
2366                 for (i = 0, b = cl.beams;i < cl.max_beams;i++, b++)
2367                         if (b->entity == ent)
2368                                 break;
2369         // if the entity was not found then just replace an unused beam
2370         if (i == cl.max_beams)
2371                 for (i = 0, b = cl.beams;i < cl.max_beams;i++, b++)
2372                         if (!b->model)
2373                                 break;
2374         if (i < cl.max_beams)
2375         {
2376                 cl.num_beams = max(cl.num_beams, i + 1);
2377                 b->entity = ent;
2378                 b->lightning = lightning;
2379                 b->model = m;
2380                 b->endtime = cl.mtime[0] + 0.2;
2381                 VectorCopy (start, b->start);
2382                 VectorCopy (end, b->end);
2383         }
2384         else
2385                 Con_Print("beam list overflow!\n");
2386 }
2387
2388 static void CL_ParseBeam (dp_model_t *m, int lightning)
2389 {
2390         int ent;
2391         vec3_t start, end;
2392
2393         ent = (unsigned short) MSG_ReadShort(&cl_message);
2394         MSG_ReadVector(&cl_message, start, cls.protocol);
2395         MSG_ReadVector(&cl_message, end, cls.protocol);
2396
2397         if (ent >= MAX_EDICTS)
2398         {
2399                 Con_Printf("CL_ParseBeam: invalid entity number %i\n", ent);
2400                 ent = 0;
2401         }
2402
2403         CL_NewBeam(ent, start, end, m, lightning);
2404 }
2405
2406 static void CL_ParseTempEntity(void)
2407 {
2408         int type;
2409         vec3_t pos, pos2;
2410         vec3_t vel1, vel2;
2411         vec3_t dir;
2412         vec3_t color;
2413         int rnd;
2414         int colorStart, colorLength, count;
2415         float velspeed, radius;
2416         unsigned char *tempcolor;
2417         matrix4x4_t tempmatrix;
2418
2419         if (cls.protocol == PROTOCOL_QUAKEWORLD)
2420         {
2421                 type = MSG_ReadByte(&cl_message);
2422                 switch (type)
2423                 {
2424                 case QW_TE_WIZSPIKE:
2425                         // spike hitting wall
2426                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2427                         CL_FindNonSolidLocation(pos, pos, 4);
2428                         CL_ParticleEffect(EFFECT_TE_WIZSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2429                         S_StartSound(-1, 0, cl.sfx_wizhit, pos, 1, 1);
2430                         break;
2431
2432                 case QW_TE_KNIGHTSPIKE:
2433                         // spike hitting wall
2434                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2435                         CL_FindNonSolidLocation(pos, pos, 4);
2436                         CL_ParticleEffect(EFFECT_TE_KNIGHTSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2437                         S_StartSound(-1, 0, cl.sfx_knighthit, pos, 1, 1);
2438                         break;
2439
2440                 case QW_TE_SPIKE:
2441                         // spike hitting wall
2442                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2443                         CL_FindNonSolidLocation(pos, pos, 4);
2444                         CL_ParticleEffect(EFFECT_TE_SPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2445                         if (rand() % 5)
2446                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2447                         else
2448                         {
2449                                 rnd = rand() & 3;
2450                                 if (rnd == 1)
2451                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2452                                 else if (rnd == 2)
2453                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2454                                 else
2455                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2456                         }
2457                         break;
2458                 case QW_TE_SUPERSPIKE:
2459                         // super spike hitting wall
2460                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2461                         CL_FindNonSolidLocation(pos, pos, 4);
2462                         CL_ParticleEffect(EFFECT_TE_SUPERSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2463                         if (rand() % 5)
2464                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2465                         else
2466                         {
2467                                 rnd = rand() & 3;
2468                                 if (rnd == 1)
2469                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2470                                 else if (rnd == 2)
2471                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2472                                 else
2473                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2474                         }
2475                         break;
2476
2477                 case QW_TE_EXPLOSION:
2478                         // rocket explosion
2479                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2480                         CL_FindNonSolidLocation(pos, pos, 10);
2481                         CL_ParticleEffect(EFFECT_TE_EXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2482                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2483                         CL_Effect(pos, cl.qw_modelindex_s_explod, 0, 6, 10);
2484                         break;
2485
2486                 case QW_TE_TAREXPLOSION:
2487                         // tarbaby explosion
2488                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2489                         CL_FindNonSolidLocation(pos, pos, 10);
2490                         CL_ParticleEffect(EFFECT_TE_TAREXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2491                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2492                         break;
2493
2494                 case QW_TE_LIGHTNING1:
2495                         // lightning bolts
2496                         CL_ParseBeam(cl.model_bolt, true);
2497                         break;
2498
2499                 case QW_TE_LIGHTNING2:
2500                         // lightning bolts
2501                         CL_ParseBeam(cl.model_bolt2, true);
2502                         break;
2503
2504                 case QW_TE_LIGHTNING3:
2505                         // lightning bolts
2506                         CL_ParseBeam(cl.model_bolt3, false);
2507                         break;
2508
2509                 case QW_TE_LAVASPLASH:
2510                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2511                         CL_ParticleEffect(EFFECT_TE_LAVASPLASH, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2512                         break;
2513
2514                 case QW_TE_TELEPORT:
2515                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2516                         CL_ParticleEffect(EFFECT_TE_TELEPORT, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2517                         break;
2518
2519                 case QW_TE_GUNSHOT:
2520                         // bullet hitting wall
2521                         radius = MSG_ReadByte(&cl_message);
2522                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2523                         CL_FindNonSolidLocation(pos, pos, 4);
2524                         VectorSet(pos2, pos[0] + radius, pos[1] + radius, pos[2] + radius);
2525                         VectorSet(pos, pos[0] - radius, pos[1] - radius, pos[2] - radius);
2526                         CL_ParticleEffect(EFFECT_TE_GUNSHOT, radius, pos, pos2, vec3_origin, vec3_origin, NULL, 0);
2527                         if(cl_sound_ric_gunshot.integer & RIC_GUNSHOT)
2528                         {
2529                                 if (rand() % 5)
2530                                         S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2531                                 else
2532                                 {
2533                                         rnd = rand() & 3;
2534                                         if (rnd == 1)
2535                                                 S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2536                                         else if (rnd == 2)
2537                                                 S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2538                                         else
2539                                                 S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2540                                 }
2541                         }
2542                         break;
2543
2544                 case QW_TE_BLOOD:
2545                         count = MSG_ReadByte(&cl_message);
2546                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2547                         CL_FindNonSolidLocation(pos, pos, 4);
2548                         CL_ParticleEffect(EFFECT_TE_BLOOD, count, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2549                         break;
2550
2551                 case QW_TE_LIGHTNINGBLOOD:
2552                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2553                         CL_FindNonSolidLocation(pos, pos, 4);
2554                         CL_ParticleEffect(EFFECT_TE_BLOOD, 2.5, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2555                         break;
2556
2557                 default:
2558                         Host_Error("CL_ParseTempEntity: bad type %d (hex %02X)", type, type);
2559                 }
2560         }
2561         else
2562         {
2563                 type = MSG_ReadByte(&cl_message);
2564                 switch (type)
2565                 {
2566                 case TE_WIZSPIKE:
2567                         // spike hitting wall
2568                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2569                         CL_FindNonSolidLocation(pos, pos, 4);
2570                         CL_ParticleEffect(EFFECT_TE_WIZSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2571                         S_StartSound(-1, 0, cl.sfx_wizhit, pos, 1, 1);
2572                         break;
2573
2574                 case TE_KNIGHTSPIKE:
2575                         // spike hitting wall
2576                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2577                         CL_FindNonSolidLocation(pos, pos, 4);
2578                         CL_ParticleEffect(EFFECT_TE_KNIGHTSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2579                         S_StartSound(-1, 0, cl.sfx_knighthit, pos, 1, 1);
2580                         break;
2581
2582                 case TE_SPIKE:
2583                         // spike hitting wall
2584                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2585                         CL_FindNonSolidLocation(pos, pos, 4);
2586                         CL_ParticleEffect(EFFECT_TE_SPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2587                         if (rand() % 5)
2588                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2589                         else
2590                         {
2591                                 rnd = rand() & 3;
2592                                 if (rnd == 1)
2593                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2594                                 else if (rnd == 2)
2595                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2596                                 else
2597                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2598                         }
2599                         break;
2600                 case TE_SPIKEQUAD:
2601                         // quad spike hitting wall
2602                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2603                         CL_FindNonSolidLocation(pos, pos, 4);
2604                         CL_ParticleEffect(EFFECT_TE_SPIKEQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2605                         if (rand() % 5)
2606                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2607                         else
2608                         {
2609                                 rnd = rand() & 3;
2610                                 if (rnd == 1)
2611                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2612                                 else if (rnd == 2)
2613                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2614                                 else
2615                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2616                         }
2617                         break;
2618                 case TE_SUPERSPIKE:
2619                         // super spike hitting wall
2620                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2621                         CL_FindNonSolidLocation(pos, pos, 4);
2622                         CL_ParticleEffect(EFFECT_TE_SUPERSPIKE, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2623                         if (rand() % 5)
2624                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2625                         else
2626                         {
2627                                 rnd = rand() & 3;
2628                                 if (rnd == 1)
2629                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2630                                 else if (rnd == 2)
2631                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2632                                 else
2633                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2634                         }
2635                         break;
2636                 case TE_SUPERSPIKEQUAD:
2637                         // quad super spike hitting wall
2638                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2639                         CL_FindNonSolidLocation(pos, pos, 4);
2640                         CL_ParticleEffect(EFFECT_TE_SUPERSPIKEQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2641                         if (rand() % 5)
2642                                 S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2643                         else
2644                         {
2645                                 rnd = rand() & 3;
2646                                 if (rnd == 1)
2647                                         S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2648                                 else if (rnd == 2)
2649                                         S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2650                                 else
2651                                         S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2652                         }
2653                         break;
2654                         // LordHavoc: added for improved blood splatters
2655                 case TE_BLOOD:
2656                         // blood puff
2657                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2658                         CL_FindNonSolidLocation(pos, pos, 4);
2659                         dir[0] = MSG_ReadChar(&cl_message);
2660                         dir[1] = MSG_ReadChar(&cl_message);
2661                         dir[2] = MSG_ReadChar(&cl_message);
2662                         count = MSG_ReadByte(&cl_message);
2663                         CL_ParticleEffect(EFFECT_TE_BLOOD, count, pos, pos, dir, dir, NULL, 0);
2664                         break;
2665                 case TE_SPARK:
2666                         // spark shower
2667                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2668                         CL_FindNonSolidLocation(pos, pos, 4);
2669                         dir[0] = MSG_ReadChar(&cl_message);
2670                         dir[1] = MSG_ReadChar(&cl_message);
2671                         dir[2] = MSG_ReadChar(&cl_message);
2672                         count = MSG_ReadByte(&cl_message);
2673                         CL_ParticleEffect(EFFECT_TE_SPARK, count, pos, pos, dir, dir, NULL, 0);
2674                         break;
2675                 case TE_PLASMABURN:
2676                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2677                         CL_FindNonSolidLocation(pos, pos, 4);
2678                         CL_ParticleEffect(EFFECT_TE_PLASMABURN, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2679                         break;
2680                         // LordHavoc: added for improved gore
2681                 case TE_BLOODSHOWER:
2682                         // vaporized body
2683                         MSG_ReadVector(&cl_message, pos, cls.protocol); // mins
2684                         MSG_ReadVector(&cl_message, pos2, cls.protocol); // maxs
2685                         velspeed = MSG_ReadCoord(&cl_message, cls.protocol); // speed
2686                         count = (unsigned short) MSG_ReadShort(&cl_message); // number of particles
2687                         vel1[0] = -velspeed;
2688                         vel1[1] = -velspeed;
2689                         vel1[2] = -velspeed;
2690                         vel2[0] = velspeed;
2691                         vel2[1] = velspeed;
2692                         vel2[2] = velspeed;
2693                         CL_ParticleEffect(EFFECT_TE_BLOOD, count, pos, pos2, vel1, vel2, NULL, 0);
2694                         break;
2695
2696                 case TE_PARTICLECUBE:
2697                         // general purpose particle effect
2698                         MSG_ReadVector(&cl_message, pos, cls.protocol); // mins
2699                         MSG_ReadVector(&cl_message, pos2, cls.protocol); // maxs
2700                         MSG_ReadVector(&cl_message, dir, cls.protocol); // dir
2701                         count = (unsigned short) MSG_ReadShort(&cl_message); // number of particles
2702                         colorStart = MSG_ReadByte(&cl_message); // color
2703                         colorLength = MSG_ReadByte(&cl_message); // gravity (1 or 0)
2704                         velspeed = MSG_ReadCoord(&cl_message, cls.protocol); // randomvel
2705                         CL_ParticleCube(pos, pos2, dir, count, colorStart, colorLength != 0, velspeed);
2706                         break;
2707
2708                 case TE_PARTICLERAIN:
2709                         // general purpose particle effect
2710                         MSG_ReadVector(&cl_message, pos, cls.protocol); // mins
2711                         MSG_ReadVector(&cl_message, pos2, cls.protocol); // maxs
2712                         MSG_ReadVector(&cl_message, dir, cls.protocol); // dir
2713                         count = (unsigned short) MSG_ReadShort(&cl_message); // number of particles
2714                         colorStart = MSG_ReadByte(&cl_message); // color
2715                         CL_ParticleRain(pos, pos2, dir, count, colorStart, 0);
2716                         break;
2717
2718                 case TE_PARTICLESNOW:
2719                         // general purpose particle effect
2720                         MSG_ReadVector(&cl_message, pos, cls.protocol); // mins
2721                         MSG_ReadVector(&cl_message, pos2, cls.protocol); // maxs
2722                         MSG_ReadVector(&cl_message, dir, cls.protocol); // dir
2723                         count = (unsigned short) MSG_ReadShort(&cl_message); // number of particles
2724                         colorStart = MSG_ReadByte(&cl_message); // color
2725                         CL_ParticleRain(pos, pos2, dir, count, colorStart, 1);
2726                         break;
2727
2728                 case TE_GUNSHOT:
2729                         // bullet hitting wall
2730                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2731                         CL_FindNonSolidLocation(pos, pos, 4);
2732                         CL_ParticleEffect(EFFECT_TE_GUNSHOT, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2733                         if(cl_sound_ric_gunshot.integer & RIC_GUNSHOT)
2734                         {
2735                                 if (rand() % 5)
2736                                         S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2737                                 else
2738                                 {
2739                                         rnd = rand() & 3;
2740                                         if (rnd == 1)
2741                                                 S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2742                                         else if (rnd == 2)
2743                                                 S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2744                                         else
2745                                                 S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2746                                 }
2747                         }
2748                         break;
2749
2750                 case TE_GUNSHOTQUAD:
2751                         // quad bullet hitting wall
2752                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2753                         CL_FindNonSolidLocation(pos, pos, 4);
2754                         CL_ParticleEffect(EFFECT_TE_GUNSHOTQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2755                         if(cl_sound_ric_gunshot.integer & RIC_GUNSHOTQUAD)
2756                         {
2757                                 if (rand() % 5)
2758                                         S_StartSound(-1, 0, cl.sfx_tink1, pos, 1, 1);
2759                                 else
2760                                 {
2761                                         rnd = rand() & 3;
2762                                         if (rnd == 1)
2763                                                 S_StartSound(-1, 0, cl.sfx_ric1, pos, 1, 1);
2764                                         else if (rnd == 2)
2765                                                 S_StartSound(-1, 0, cl.sfx_ric2, pos, 1, 1);
2766                                         else
2767                                                 S_StartSound(-1, 0, cl.sfx_ric3, pos, 1, 1);
2768                                 }
2769                         }
2770                         break;
2771
2772                 case TE_EXPLOSION:
2773                         // rocket explosion
2774                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2775                         CL_FindNonSolidLocation(pos, pos, 10);
2776                         CL_ParticleEffect(EFFECT_TE_EXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2777                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2778                         break;
2779
2780                 case TE_EXPLOSIONQUAD:
2781                         // quad rocket explosion
2782                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2783                         CL_FindNonSolidLocation(pos, pos, 10);
2784                         CL_ParticleEffect(EFFECT_TE_EXPLOSIONQUAD, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2785                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2786                         break;
2787
2788                 case TE_EXPLOSION3:
2789                         // Nehahra movie colored lighting explosion
2790                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2791                         CL_FindNonSolidLocation(pos, pos, 10);
2792                         color[0] = MSG_ReadCoord(&cl_message, cls.protocol) * (2.0f / 1.0f);
2793                         color[1] = MSG_ReadCoord(&cl_message, cls.protocol) * (2.0f / 1.0f);
2794                         color[2] = MSG_ReadCoord(&cl_message, cls.protocol) * (2.0f / 1.0f);
2795                         CL_ParticleExplosion(pos);
2796                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2797                         CL_AllocLightFlash(NULL, &tempmatrix, 350, color[0], color[1], color[2], 700, 0.5, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2798                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2799                         break;
2800
2801                 case TE_EXPLOSIONRGB:
2802                         // colored lighting explosion
2803                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2804                         CL_FindNonSolidLocation(pos, pos, 10);
2805                         CL_ParticleExplosion(pos);
2806                         color[0] = MSG_ReadByte(&cl_message) * (2.0f / 255.0f);
2807                         color[1] = MSG_ReadByte(&cl_message) * (2.0f / 255.0f);
2808                         color[2] = MSG_ReadByte(&cl_message) * (2.0f / 255.0f);
2809                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2810                         CL_AllocLightFlash(NULL, &tempmatrix, 350, color[0], color[1], color[2], 700, 0.5, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2811                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2812                         break;
2813
2814                 case TE_TAREXPLOSION:
2815                         // tarbaby explosion
2816                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2817                         CL_FindNonSolidLocation(pos, pos, 10);
2818                         CL_ParticleEffect(EFFECT_TE_TAREXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2819                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2820                         break;
2821
2822                 case TE_SMALLFLASH:
2823                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2824                         CL_FindNonSolidLocation(pos, pos, 10);
2825                         CL_ParticleEffect(EFFECT_TE_SMALLFLASH, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2826                         break;
2827
2828                 case TE_CUSTOMFLASH:
2829                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2830                         CL_FindNonSolidLocation(pos, pos, 4);
2831                         radius = (MSG_ReadByte(&cl_message) + 1) * 8;
2832                         velspeed = (MSG_ReadByte(&cl_message) + 1) * (1.0 / 256.0);
2833                         color[0] = MSG_ReadByte(&cl_message) * (2.0f / 255.0f);
2834                         color[1] = MSG_ReadByte(&cl_message) * (2.0f / 255.0f);
2835                         color[2] = MSG_ReadByte(&cl_message) * (2.0f / 255.0f);
2836                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2837                         CL_AllocLightFlash(NULL, &tempmatrix, radius, color[0], color[1], color[2], radius / velspeed, velspeed, 0, -1, true, 1, 0.25, 1, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2838                         break;
2839
2840                 case TE_FLAMEJET:
2841                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2842                         MSG_ReadVector(&cl_message, dir, cls.protocol);
2843                         count = MSG_ReadByte(&cl_message);
2844                         CL_ParticleEffect(EFFECT_TE_FLAMEJET, count, pos, pos, dir, dir, NULL, 0);
2845                         break;
2846
2847                 case TE_LIGHTNING1:
2848                         // lightning bolts
2849                         CL_ParseBeam(cl.model_bolt, true);
2850                         break;
2851
2852                 case TE_LIGHTNING2:
2853                         // lightning bolts
2854                         CL_ParseBeam(cl.model_bolt2, true);
2855                         break;
2856
2857                 case TE_LIGHTNING3:
2858                         // lightning bolts
2859                         CL_ParseBeam(cl.model_bolt3, false);
2860                         break;
2861
2862         // PGM 01/21/97
2863                 case TE_BEAM:
2864                         // grappling hook beam
2865                         CL_ParseBeam(cl.model_beam, false);
2866                         break;
2867         // PGM 01/21/97
2868
2869         // LordHavoc: for compatibility with the Nehahra movie...
2870                 case TE_LIGHTNING4NEH:
2871                         CL_ParseBeam(Mod_ForName(MSG_ReadString(&cl_message, cl_readstring, sizeof(cl_readstring)), true, false, NULL), false);
2872                         break;
2873
2874                 case TE_LAVASPLASH:
2875                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2876                         CL_ParticleEffect(EFFECT_TE_LAVASPLASH, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2877                         break;
2878
2879                 case TE_TELEPORT:
2880                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2881                         CL_ParticleEffect(EFFECT_TE_TELEPORT, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2882                         break;
2883
2884                 case TE_EXPLOSION2:
2885                         // color mapped explosion
2886                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2887                         CL_FindNonSolidLocation(pos, pos, 10);
2888                         colorStart = MSG_ReadByte(&cl_message);
2889                         colorLength = MSG_ReadByte(&cl_message);
2890                         CL_ParticleExplosion2(pos, colorStart, colorLength);
2891                         tempcolor = palette_rgb[(rand()%colorLength) + colorStart];
2892                         color[0] = tempcolor[0] * (2.0f / 255.0f);
2893                         color[1] = tempcolor[1] * (2.0f / 255.0f);
2894                         color[2] = tempcolor[2] * (2.0f / 255.0f);
2895                         Matrix4x4_CreateTranslate(&tempmatrix, pos[0], pos[1], pos[2]);
2896                         CL_AllocLightFlash(NULL, &tempmatrix, 350, color[0], color[1], color[2], 700, 0.5, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
2897                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2898                         break;
2899
2900                 case TE_TEI_G3:
2901                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2902                         MSG_ReadVector(&cl_message, pos2, cls.protocol);
2903                         MSG_ReadVector(&cl_message, dir, cls.protocol);
2904                         CL_ParticleTrail(EFFECT_TE_TEI_G3, 1, pos, pos2, dir, dir, NULL, 0, true, true, NULL, NULL, 1);
2905                         break;
2906
2907                 case TE_TEI_SMOKE:
2908                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2909                         MSG_ReadVector(&cl_message, dir, cls.protocol);
2910                         count = MSG_ReadByte(&cl_message);
2911                         CL_FindNonSolidLocation(pos, pos, 4);
2912                         CL_ParticleEffect(EFFECT_TE_TEI_SMOKE, count, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2913                         break;
2914
2915                 case TE_TEI_BIGEXPLOSION:
2916                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2917                         CL_FindNonSolidLocation(pos, pos, 10);
2918                         CL_ParticleEffect(EFFECT_TE_TEI_BIGEXPLOSION, 1, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2919                         S_StartSound(-1, 0, cl.sfx_r_exp3, pos, 1, 1);
2920                         break;
2921
2922                 case TE_TEI_PLASMAHIT:
2923                         MSG_ReadVector(&cl_message, pos, cls.protocol);
2924                         MSG_ReadVector(&cl_message, dir, cls.protocol);
2925                         count = MSG_ReadByte(&cl_message);
2926                         CL_FindNonSolidLocation(pos, pos, 5);
2927                         CL_ParticleEffect(EFFECT_TE_TEI_PLASMAHIT, count, pos, pos, vec3_origin, vec3_origin, NULL, 0);
2928                         break;
2929
2930                 default:
2931                         Host_Error("CL_ParseTempEntity: bad type %d (hex %02X)", type, type);
2932                 }
2933         }
2934 }
2935
2936 static void CL_ParseTrailParticles(void)
2937 {
2938         int entityindex;
2939         int effectindex;
2940         vec3_t start, end;
2941         entityindex = (unsigned short)MSG_ReadShort(&cl_message);
2942         if (entityindex >= MAX_EDICTS)
2943                 entityindex = 0;
2944         if (entityindex >= cl.max_entities)
2945                 CL_ExpandEntities(entityindex);
2946         effectindex = (unsigned short)MSG_ReadShort(&cl_message);
2947         MSG_ReadVector(&cl_message, start, cls.protocol);
2948         MSG_ReadVector(&cl_message, end, cls.protocol);
2949         CL_ParticleTrail(effectindex, 1, start, end, vec3_origin, vec3_origin, entityindex > 0 ? cl.entities + entityindex : NULL, 0, true, true, NULL, NULL, 1);
2950 }
2951
2952 static void CL_ParsePointParticles(void)
2953 {
2954         int effectindex, count;
2955         vec3_t origin, velocity;
2956         effectindex = (unsigned short)MSG_ReadShort(&cl_message);
2957         MSG_ReadVector(&cl_message, origin, cls.protocol);
2958         MSG_ReadVector(&cl_message, velocity, cls.protocol);
2959         count = (unsigned short)MSG_ReadShort(&cl_message);
2960         CL_ParticleEffect(effectindex, count, origin, origin, velocity, velocity, NULL, 0);
2961 }
2962
2963 static void CL_ParsePointParticles1(void)
2964 {
2965         int effectindex;
2966         vec3_t origin;
2967         effectindex = (unsigned short)MSG_ReadShort(&cl_message);
2968         MSG_ReadVector(&cl_message, origin, cls.protocol);
2969         CL_ParticleEffect(effectindex, 1, origin, origin, vec3_origin, vec3_origin, NULL, 0);
2970 }
2971
2972 typedef struct cl_iplog_item_s
2973 {
2974         char *address;
2975         char *name;
2976 }
2977 cl_iplog_item_t;
2978
2979 static qboolean cl_iplog_loaded = false;
2980 static int cl_iplog_numitems = 0;
2981 static int cl_iplog_maxitems = 0;
2982 static cl_iplog_item_t *cl_iplog_items;
2983
2984 static void CL_IPLog_Load(void);
2985 static void CL_IPLog_Add(const char *address, const char *name, qboolean checkexisting, qboolean addtofile)
2986 {
2987         int i;
2988         size_t sz_name, sz_address;
2989         if (!address || !address[0] || !name || !name[0])
2990                 return;
2991         if (!cl_iplog_loaded)
2992                 CL_IPLog_Load();
2993         if (developer_extra.integer)
2994                 Con_DPrintf("CL_IPLog_Add(\"%s\", \"%s\", %i, %i);\n", address, name, checkexisting, addtofile);
2995         // see if it already exists
2996         if (checkexisting)
2997         {
2998                 for (i = 0;i < cl_iplog_numitems;i++)
2999                 {
3000                         if (!strcmp(cl_iplog_items[i].address, address) && !strcmp(cl_iplog_items[i].name, name))
3001                         {
3002                                 if (developer_extra.integer)
3003                                         Con_DPrintf("... found existing \"%s\" \"%s\"\n", cl_iplog_items[i].address, cl_iplog_items[i].name);
3004                                 return;
3005                         }
3006                 }
3007         }
3008         // it does not already exist in the iplog, so add it
3009         if (cl_iplog_maxitems <= cl_iplog_numitems || !cl_iplog_items)
3010         {
3011                 cl_iplog_item_t *olditems = cl_iplog_items;
3012                 cl_iplog_maxitems = max(1024, cl_iplog_maxitems + 256);
3013                 cl_iplog_items = (cl_iplog_item_t *) Mem_Alloc(cls.permanentmempool, cl_iplog_maxitems * sizeof(cl_iplog_item_t));
3014                 if (olditems)
3015                 {
3016                         if (cl_iplog_numitems)
3017                                 memcpy(cl_iplog_items, olditems, cl_iplog_numitems * sizeof(cl_iplog_item_t));
3018                         Mem_Free(olditems);
3019                 }
3020         }
3021         sz_address = strlen(address) + 1;
3022         sz_name = strlen(name) + 1;
3023         cl_iplog_items[cl_iplog_numitems].address = (char *) Mem_Alloc(cls.permanentmempool, sz_address);
3024         cl_iplog_items[cl_iplog_numitems].name = (char *) Mem_Alloc(cls.permanentmempool, sz_name);
3025         strlcpy(cl_iplog_items[cl_iplog_numitems].address, address, sz_address);
3026         // TODO: maybe it would be better to strip weird characters from name when
3027         // copying it here rather than using a straight strcpy?
3028         strlcpy(cl_iplog_items[cl_iplog_numitems].name, name, sz_name);
3029         cl_iplog_numitems++;
3030         if (addtofile)
3031         {
3032                 // add it to the iplog.txt file
3033                 // TODO: this ought to open the one in the userpath version of the base
3034                 // gamedir, not the current gamedir
3035 // not necessary for mobile
3036 #ifndef DP_MOBILETOUCH
3037                 Log_Printf(cl_iplog_name.string, "%s %s\n", address, name);
3038                 if (developer_extra.integer)
3039                         Con_DPrintf("CL_IPLog_Add: appending this line to %s: %s %s\n", cl_iplog_name.string, address, name);
3040 #endif
3041         }
3042 }
3043
3044 static void CL_IPLog_Load(void)
3045 {
3046         int i, len, linenumber;
3047         char *text, *textend;
3048         unsigned char *filedata;
3049         fs_offset_t filesize;
3050         char line[MAX_INPUTLINE];
3051         char address[MAX_INPUTLINE];
3052         cl_iplog_loaded = true;
3053         // TODO: this ought to open the one in the userpath version of the base
3054         // gamedir, not the current gamedir
3055 // not necessary for mobile
3056 #ifndef DP_MOBILETOUCH
3057         filedata = FS_LoadFile(cl_iplog_name.string, tempmempool, true, &filesize);
3058 #else
3059         filedata = NULL;
3060 #endif
3061         if (!filedata)
3062                 return;
3063         text = (char *)filedata;
3064         textend = text + filesize;
3065         for (linenumber = 1;text < textend;linenumber++)
3066         {
3067                 for (len = 0;text < textend && *text != '\r' && *text != '\n';text++)
3068                         if (len < (int)sizeof(line) - 1)
3069                                 line[len++] = *text;
3070                 line[len] = 0;
3071                 if (text < textend && *text == '\r' && text[1] == '\n')
3072                         text++;
3073                 if (text < textend && *text == '\n')
3074                         text++;
3075                 if (line[0] == '/' && line[1] == '/')
3076                         continue; // skip comments if anyone happens to add them
3077                 for (i = 0;i < len && !ISWHITESPACE(line[i]);i++)
3078                         address[i] = line[i];
3079                 address[i] = 0;
3080                 // skip exactly one space character
3081                 i++;
3082                 // address contains the address with termination,
3083                 // line + i contains the name with termination
3084                 if (address[0] && line[i])
3085                         CL_IPLog_Add(address, line + i, false, false);
3086                 else
3087                         Con_Printf("%s:%i: could not parse address and name:\n%s\n", cl_iplog_name.string, linenumber, line);
3088         }
3089 }
3090
3091 static void CL_IPLog_List_f(void)
3092 {
3093         int i, j;
3094         const char *addressprefix;
3095         if (Cmd_Argc() > 2)
3096         {
3097                 Con_Printf("usage: %s 123.456.789.\n", Cmd_Argv(0));
3098                 return;
3099         }
3100         addressprefix = "";
3101         if (Cmd_Argc() >= 2)
3102                 addressprefix = Cmd_Argv(1);
3103         if (!cl_iplog_loaded)
3104                 CL_IPLog_Load();
3105         if (addressprefix && addressprefix[0])
3106                 Con_Printf("Listing iplog addresses beginning with %s\n", addressprefix);
3107         else
3108                 Con_Printf("Listing all iplog entries\n");
3109         Con_Printf("address         name\n");
3110         for (i = 0;i < cl_iplog_numitems;i++)
3111         {
3112                 if (addressprefix && addressprefix[0])
3113                 {
3114                         for (j = 0;addressprefix[j];j++)
3115                                 if (addressprefix[j] != cl_iplog_items[i].address[j])
3116                                         break;
3117                         // if this address does not begin with the addressprefix string
3118                         // simply omit it from the output
3119                         if (addressprefix[j])
3120                                 continue;
3121                 }
3122                 // if name is less than 15 characters, left justify it and pad
3123                 // if name is more than 15 characters, print all of it, not worrying
3124                 // about the fact it will misalign the columns
3125                 if (strlen(cl_iplog_items[i].address) < 15)
3126                         Con_Printf("%-15s %s\n", cl_iplog_items[i].address, cl_iplog_items[i].name);
3127                 else
3128                         Con_Printf("%5s %s\n", cl_iplog_items[i].address, cl_iplog_items[i].name);
3129         }
3130 }
3131
3132 // look for anything interesting like player IP addresses or ping reports
3133 static qboolean CL_ExaminePrintString(const char *text)
3134 {
3135         int len;
3136         const char *t;
3137         char temp[MAX_INPUTLINE];
3138         if (!strcmp(text, "Client ping times:\n"))
3139         {
3140                 cl.parsingtextmode = CL_PARSETEXTMODE_PING;
3141                 // hide ping reports in demos
3142                 if (cls.demoplayback)
3143                         cl.parsingtextexpectingpingforscores = 1;
3144                 for(cl.parsingtextplayerindex = 0; cl.parsingtextplayerindex < cl.maxclients && !cl.scores[cl.parsingtextplayerindex].name[0]; cl.parsingtextplayerindex++)
3145                         ;
3146                 if (cl.parsingtextplayerindex >= cl.maxclients) // should never happen, since the client itself should be in cl.scores
3147                 {
3148                         Con_Printf("ping reply but empty scoreboard?!?\n");
3149                         cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
3150                         cl.parsingtextexpectingpingforscores = 0;
3151                 }
3152                 cl.parsingtextexpectingpingforscores = cl.parsingtextexpectingpingforscores ? 2 : 0;
3153                 return !cl.parsingtextexpectingpingforscores;
3154         }
3155         if (!strncmp(text, "host:    ", 9))
3156         {
3157                 // cl.parsingtextexpectingpingforscores = false; // really?
3158                 cl.parsingtextmode = CL_PARSETEXTMODE_STATUS;
3159                 cl.parsingtextplayerindex = 0;
3160                 return true;
3161         }
3162         if (cl.parsingtextmode == CL_PARSETEXTMODE_PING)
3163         {
3164                 // if anything goes wrong, we'll assume this is not a ping report
3165                 qboolean expected = cl.parsingtextexpectingpingforscores != 0;
3166                 cl.parsingtextexpectingpingforscores = 0;
3167                 cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
3168                 t = text;
3169                 while (*t == ' ')
3170                         t++;
3171                 if ((*t >= '0' && *t <= '9') || *t == '-')
3172                 {
3173                         int ping = atoi(t);
3174                         while ((*t >= '0' && *t <= '9') || *t == '-')
3175                                 t++;
3176                         if (*t == ' ')
3177                         {
3178                                 int charindex = 0;
3179                                 t++;
3180                                 if(cl.parsingtextplayerindex < cl.maxclients)
3181                                 {
3182                                         for (charindex = 0;cl.scores[cl.parsingtextplayerindex].name[charindex] == t[charindex];charindex++)
3183                                                 ;
3184                                         // note: the matching algorithm stops at the end of the player name because some servers append text such as " READY" after the player name in the scoreboard but not in the ping report
3185                                         //if (cl.scores[cl.parsingtextplayerindex].name[charindex] == 0 && t[charindex] == '\n')
3186                                         if (t[charindex] == '\n')
3187                                         {
3188                                                 cl.scores[cl.parsingtextplayerindex].qw_ping = bound(0, ping, 9999);
3189                                                 for (cl.parsingtextplayerindex++;cl.parsingtextplayerindex < cl.maxclients && !cl.scores[cl.parsingtextplayerindex].name[0];cl.parsingtextplayerindex++)
3190                                                         ;
3191                                                 //if (cl.parsingtextplayerindex < cl.maxclients) // we could still get unconnecteds!
3192                                                 {
3193                                                         // we parsed a valid ping entry, so expect another to follow
3194                                                         cl.parsingtextmode = CL_PARSETEXTMODE_PING;
3195                                                         cl.parsingtextexpectingpingforscores = expected;
3196                                                 }
3197                                                 return !expected;
3198                                         }
3199                                 }
3200                                 if (!strncmp(t, "unconnected\n", 12))
3201                                 {
3202                                         // just ignore
3203                                         cl.parsingtextmode = CL_PARSETEXTMODE_PING;
3204                                         cl.parsingtextexpectingpingforscores = expected;
3205                                         return !expected;
3206                                 }
3207                                 else
3208                                         Con_DPrintf("player names '%s' and '%s' didn't match\n", cl.scores[cl.parsingtextplayerindex].name, t);
3209                         }
3210                 }
3211         }
3212         if (cl.parsingtextmode == CL_PARSETEXTMODE_STATUS)
3213         {
3214                 if (!strncmp(text, "players: ", 9))
3215                 {
3216                         cl.parsingtextmode = CL_PARSETEXTMODE_STATUS_PLAYERID;
3217                         cl.parsingtextplayerindex = 0;
3218                         return true;
3219                 }
3220                 else if (!strstr(text, ": "))
3221                 {
3222                         cl.parsingtextmode = CL_PARSETEXTMODE_NONE; // status report ended
3223                         return true;
3224                 }
3225         }
3226         if (cl.parsingtextmode == CL_PARSETEXTMODE_STATUS_PLAYERID)
3227         {
3228                 // if anything goes wrong, we'll assume this is not a status report
3229                 cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
3230                 if (text[0] == '#' && text[1] >= '0' && text[1] <= '9')
3231                 {
3232                         t = text + 1;
3233                         cl.parsingtextplayerindex = atoi(t) - 1;
3234                         while (*t >= '0' && *t <= '9')
3235                                 t++;
3236                         if (*t == ' ')
3237                         {
3238                                 cl.parsingtextmode = CL_PARSETEXTMODE_STATUS_PLAYERIP;
3239                                 return true;
3240                         }
3241                         // the player name follows here, along with frags and time
3242                 }
3243         }
3244         if (cl.parsingtextmode == CL_PARSETEXTMODE_STATUS_PLAYERIP)
3245         {
3246                 // if anything goes wrong, we'll assume this is not a status report
3247                 cl.parsingtextmode = CL_PARSETEXTMODE_NONE;
3248                 if (text[0] == ' ')
3249                 {
3250                         t = text;
3251                         while (*t == ' ')
3252                                 t++;
3253                         for (len = 0;*t && *t != '\n';t++)
3254                                 if (len < (int)sizeof(temp) - 1)
3255                                         temp[len++] = *t;
3256                         temp[len] = 0;
3257                         // botclient is perfectly valid, but we don't care about bots
3258                         // also don't try to look up the name of an invalid player index
3259                         if (strcmp(temp, "botclient")
3260                          && cl.parsingtextplayerindex >= 0
3261                          && cl.parsingtextplayerindex < cl.maxclients
3262                          && cl.scores[cl.parsingtextplayerindex].name[0])
3263                         {
3264                                 // log the player name and IP address string
3265                                 // (this operates entirely on strings to avoid issues with the
3266                                 //  nature of a network address)
3267                                 CL_IPLog_Add(temp, cl.scores[cl.parsingtextplayerindex].name, true, true);
3268                         }
3269                         cl.parsingtextmode = CL_PARSETEXTMODE_STATUS_PLAYERID;
3270                         return true;
3271                 }
3272         }
3273         return true;
3274 }
3275
3276 extern cvar_t slowmo;
3277 extern cvar_t cl_lerpexcess;
3278 static void CL_NetworkTimeReceived(double newtime)
3279 {
3280         double timehigh;
3281         cl.mtime[1] = cl.mtime[0];
3282         cl.mtime[0] = newtime;
3283         if (cl_nolerp.integer || cls.timedemo || (cl.islocalgame && !sv_fixedframeratesingleplayer.integer) || cl.mtime[1] == cl.mtime[0] || cls.signon < SIGNONS)
3284                 cl.time = cl.mtime[1] = newtime;
3285         else if (cls.demoplayback)
3286         {
3287                 // when time falls behind during demo playback it means the cl.mtime[1] was altered
3288                 // due to a large time gap, so treat it as an instant change in time
3289                 // (this can also happen during heavy packet loss in the demo)
3290                 if (cl.time < newtime - 0.1)
3291                         cl.mtime[1] = cl.time = newtime;
3292         }
3293         else if (cls.protocol != PROTOCOL_QUAKEWORLD)
3294         {
3295                 cl.mtime[1] = max(cl.mtime[1], cl.mtime[0] - 0.1);
3296                 if (developer_extra.integer && vid_activewindow)
3297                 {
3298                         if (cl.time < cl.mtime[1] - (cl.mtime[0] - cl.mtime[1]))
3299                                 Con_DPrintf("--- cl.time < cl.mtime[1] (%f < %f ... %f)\n", cl.time, cl.mtime[1], cl.mtime[0]);
3300                         else if (cl.time > cl.mtime[0] + (cl.mtime[0] - cl.mtime[1]))
3301                                 Con_DPrintf("--- cl.time > cl.mtime[0] (%f > %f ... %f)\n", cl.time, cl.mtime[1], cl.mtime[0]);
3302                 }
3303                 cl.time += (cl.mtime[1] - cl.time) * bound(0, cl_nettimesyncfactor.value, 1);
3304                 timehigh = cl.mtime[1] + (cl.mtime[0] - cl.mtime[1]) * cl_nettimesyncboundtolerance.value;
3305                 if (cl_nettimesyncboundmode.integer == 1)
3306                         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
3307                 else if (cl_nettimesyncboundmode.integer == 2)
3308                 {
3309                         if (cl.time < cl.mtime[1] || cl.time > timehigh)
3310                                 cl.time = cl.mtime[1];
3311                 }
3312                 else if (cl_nettimesyncboundmode.integer == 3)
3313                 {
3314                         if ((cl.time < cl.mtime[1] && cl.oldtime < cl.mtime[1]) || (cl.time > timehigh && cl.oldtime > timehigh))
3315                                 cl.time = cl.mtime[1];
3316                 }
3317                 else if (cl_nettimesyncboundmode.integer == 4)
3318                 {
3319                         if (fabs(cl.time - cl.mtime[1]) > 0.5)
3320                                 cl.time = cl.mtime[1]; // reset
3321                         else if (fabs(cl.time - cl.mtime[1]) > 0.1)
3322                                 cl.time += 0.5 * (cl.mtime[1] - cl.time); // fast
3323                         else if (cl.time > cl.mtime[1])
3324                                 cl.time -= 0.002 * cl.movevars_timescale; // fall into the past by 2ms
3325                         else
3326                                 cl.time += 0.001 * cl.movevars_timescale; // creep forward 1ms
3327                 }
3328                 else if (cl_nettimesyncboundmode.integer == 5)
3329                 {
3330                         if (fabs(cl.time - cl.mtime[1]) > 0.5)
3331                                 cl.time = cl.mtime[1]; // reset
3332                         else if (fabs(cl.time - cl.mtime[1]) > 0.1)
3333                                 cl.time += 0.5 * (cl.mtime[1] - cl.time); // fast
3334                         else
3335                                 cl.time = bound(cl.time - 0.002 * cl.movevars_timescale, cl.mtime[1], cl.time + 0.001 * cl.movevars_timescale);
3336                 }
3337                 else if (cl_nettimesyncboundmode.integer == 6)
3338                 {
3339                         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
3340                         cl.time = bound(cl.time - 0.002 * cl.movevars_timescale, cl.mtime[1], cl.time + 0.001 * cl.movevars_timescale);
3341                 }
3342         }
3343         // this packet probably contains a player entity update, so we will need
3344         // to update the prediction
3345         cl.movement_replay = true;
3346         // this may get updated later in parsing by svc_clientdata
3347         cl.onground = false;
3348         // if true the cl.viewangles are interpolated from cl.mviewangles[]
3349         // during this frame
3350         // (makes spectating players much smoother and prevents mouse movement from turning)
3351         cl.fixangle[1] = cl.fixangle[0];
3352         cl.fixangle[0] = false;
3353         if (!cls.demoplayback)
3354                 VectorCopy(cl.mviewangles[0], cl.mviewangles[1]);
3355         // update the csqc's server timestamps, critical for proper sync
3356         CSQC_UpdateNetworkTimes(cl.mtime[0], cl.mtime[1]);
3357
3358         if (cl.mtime[0] > cl.mtime[1])
3359                 World_Physics_Frame(&cl.world, cl.mtime[0] - cl.mtime[1], cl.movevars_gravity);
3360
3361         // only lerp entities that also get an update in this frame, when lerp excess is used
3362         if(cl_lerpexcess.value > 0)
3363         {
3364                 int i;
3365                 for (i = 1;i < cl.num_entities;i++)
3366                 {
3367                         if (cl.entities_active[i])
3368                         {
3369                                 entity_t *ent = cl.entities + i;
3370                                 ent->persistent.lerpdeltatime = 0;
3371                         }
3372                 }
3373         }
3374 }
3375
3376 #define SHOWNET(x) if(cl_shownet.integer==2)Con_Printf("%3i:%s(%i)\n", cl_message.readcount-1, x, cmd);
3377
3378 /*
3379 =====================
3380 CL_ParseServerMessage
3381 =====================
3382 */
3383 int parsingerror = false;
3384 void CL_ParseServerMessage(void)
3385 {
3386         int                     cmd;
3387         int                     i;
3388         protocolversion_t protocol;
3389         unsigned char           cmdlog[32];
3390         const char              *cmdlogname[32], *temp;
3391         int                     cmdindex, cmdcount = 0;
3392         qboolean        qwplayerupdatereceived;
3393         qboolean        strip_pqc;
3394         char vabuf[1024];
3395
3396         // LordHavoc: moved demo message writing from before the packet parse to
3397         // after the packet parse so that CL_Stop_f can be called by cl_autodemo
3398         // code in CL_ParseServerinfo
3399         //if (cls.demorecording)
3400         //      CL_WriteDemoMessage (&cl_message);
3401
3402         cl.last_received_message = realtime;
3403
3404         CL_KeepaliveMessage(false);
3405
3406 //
3407 // if recording demos, copy the message out
3408 //
3409         if (cl_shownet.integer == 1)
3410                 Con_Printf("%f %i\n", realtime, cl_message.cursize);
3411         else if (cl_shownet.integer == 2)
3412                 Con_Print("------------------\n");
3413
3414 //
3415 // parse the message
3416 //
3417         //MSG_BeginReading ();
3418
3419         parsingerror = true;
3420
3421         if (cls.protocol == PROTOCOL_QUAKEWORLD)
3422         {
3423                 CL_NetworkTimeReceived(realtime); // qw has no clock
3424
3425                 // kill all qw nails
3426                 cl.qw_num_nails = 0;
3427
3428                 // fade weapon view kick
3429                 cl.qw_weaponkick = min(cl.qw_weaponkick + 10 * bound(0, cl.time - cl.oldtime, 0.1), 0);
3430
3431                 cls.servermovesequence = cls.netcon->qw.incoming_sequence;
3432
3433                 qwplayerupdatereceived = false;
3434
3435                 while (1)
3436                 {
3437                         if (cl_message.badread)
3438                                 Host_Error ("CL_ParseServerMessage: Bad QW server message");
3439
3440                         cmd = MSG_ReadByte(&cl_message);
3441
3442                         if (cmd == -1)
3443                         {
3444                                 SHOWNET("END OF MESSAGE");
3445                                 break;          // end of message
3446                         }
3447
3448