]> git.xonotic.org Git - xonotic/darkplaces.git/blob - cl_main.c
cl_main: Disconnect when connection is established, only if we're already connected
[xonotic/darkplaces.git] / cl_main.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_main.c  -- client main loop
21
22 #include "quakedef.h"
23 #include "cl_collision.h"
24 #include "cl_video.h"
25 #include "image.h"
26 #include "csprogs.h"
27 #include "r_shadow.h"
28 #include "libcurl.h"
29 #include "snd_main.h"
30 #include "cdaudio.h"
31
32 // we need to declare some mouse variables here, because the menu system
33 // references them even when on a unix system.
34
35 cvar_t csqc_progname = {CF_CLIENT | CF_SERVER, "csqc_progname","csprogs.dat","name of csprogs.dat file to load"};
36 cvar_t csqc_progcrc = {CF_CLIENT | CF_READONLY, "csqc_progcrc","-1","CRC of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"};
37 cvar_t csqc_progsize = {CF_CLIENT | CF_READONLY, "csqc_progsize","-1","file size of csprogs.dat file to load (-1 is none), only used during level changes and then reset to -1"};
38 cvar_t csqc_usedemoprogs = {CF_CLIENT, "csqc_usedemoprogs","1","use csprogs stored in demos"};
39 cvar_t csqc_polygons_defaultmaterial_nocullface = {CF_CLIENT, "csqc_polygons_defaultmaterial_nocullface", "0", "use 'cull none' behavior in the default shader for rendering R_PolygonBegin - warning: enabling this is not consistent with FTEQW behavior on this feature"};
40
41 cvar_t cl_shownet = {CF_CLIENT, "cl_shownet","0","1 = print packet size, 2 = print packet message list"};
42 cvar_t cl_nolerp = {CF_CLIENT, "cl_nolerp", "0","network update smoothing"};
43 cvar_t cl_lerpexcess = {CF_CLIENT, "cl_lerpexcess", "0","maximum allowed lerp excess (hides, not fixes, some packet loss)"};
44 cvar_t cl_lerpanim_maxdelta_server = {CF_CLIENT, "cl_lerpanim_maxdelta_server", "0.1","maximum frame delta for smoothing between server-controlled animation frames (when 0, one network frame)"};
45 cvar_t cl_lerpanim_maxdelta_framegroups = {CF_CLIENT, "cl_lerpanim_maxdelta_framegroups", "0.1","maximum frame delta for smoothing between framegroups (when 0, one network frame)"};
46
47 cvar_t cl_itembobheight = {CF_CLIENT, "cl_itembobheight", "0","how much items bob up and down (try 8)"};
48 cvar_t cl_itembobspeed = {CF_CLIENT, "cl_itembobspeed", "0.5","how frequently items bob up and down"};
49
50 cvar_t lookspring = {CF_CLIENT | CF_ARCHIVE, "lookspring","0","returns pitch to level with the floor when no longer holding a pitch key"};
51 cvar_t lookstrafe = {CF_CLIENT | CF_ARCHIVE, "lookstrafe","0","move instead of turning"};
52 cvar_t sensitivity = {CF_CLIENT | CF_ARCHIVE, "sensitivity","3","mouse speed multiplier"};
53
54 cvar_t m_pitch = {CF_CLIENT | CF_ARCHIVE, "m_pitch","0.022","mouse pitch speed multiplier"};
55 cvar_t m_yaw = {CF_CLIENT | CF_ARCHIVE, "m_yaw","0.022","mouse yaw speed multiplier"};
56 cvar_t m_forward = {CF_CLIENT | CF_ARCHIVE, "m_forward","1","mouse forward speed multiplier"};
57 cvar_t m_side = {CF_CLIENT | CF_ARCHIVE, "m_side","0.8","mouse side speed multiplier"};
58
59 cvar_t freelook = {CF_CLIENT | CF_ARCHIVE, "freelook", "1","mouse controls pitch instead of forward/back"};
60
61 cvar_t cl_autodemo = {CF_CLIENT | CF_ARCHIVE, "cl_autodemo", "0", "records every game played, using the date/time and map name to name the demo file" };
62 cvar_t cl_autodemo_nameformat = {CF_CLIENT | CF_ARCHIVE, "cl_autodemo_nameformat", "autodemos/%Y-%m-%d_%H-%M", "The format of the cl_autodemo filename, followed by the map name (the date is encoded using strftime escapes)" };
63 cvar_t cl_autodemo_delete = {CF_CLIENT, "cl_autodemo_delete", "0", "Delete demos after recording.  This is a bitmask, bit 1 gives the default, bit 0 the value for the current demo.  Thus, the values are: 0 = disabled; 1 = delete current demo only; 2 = delete all demos except the current demo; 3 = delete all demos from now on" };
64
65 cvar_t r_draweffects = {CF_CLIENT, "r_draweffects", "1","renders temporary sprite effects"};
66
67 cvar_t cl_explosions_alpha_start = {CF_CLIENT | CF_ARCHIVE, "cl_explosions_alpha_start", "1.5","starting alpha of an explosion shell"};
68 cvar_t cl_explosions_alpha_end = {CF_CLIENT | CF_ARCHIVE, "cl_explosions_alpha_end", "0","end alpha of an explosion shell (just before it disappears)"};
69 cvar_t cl_explosions_size_start = {CF_CLIENT | CF_ARCHIVE, "cl_explosions_size_start", "16","starting size of an explosion shell"};
70 cvar_t cl_explosions_size_end = {CF_CLIENT | CF_ARCHIVE, "cl_explosions_size_end", "128","ending alpha of an explosion shell (just before it disappears)"};
71 cvar_t cl_explosions_lifetime = {CF_CLIENT | CF_ARCHIVE, "cl_explosions_lifetime", "0.5","how long an explosion shell lasts"};
72
73 cvar_t cl_stainmaps = {CF_CLIENT | CF_ARCHIVE, "cl_stainmaps", "0","stains lightmaps, much faster than decals but blurred"};
74 cvar_t cl_stainmaps_clearonload = {CF_CLIENT | CF_ARCHIVE, "cl_stainmaps_clearonload", "1","clear stainmaps on map restart"};
75
76 cvar_t cl_beams_polygons = {CF_CLIENT | CF_ARCHIVE, "cl_beams_polygons", "1","use beam polygons instead of models"};
77 cvar_t cl_beams_quakepositionhack = {CF_CLIENT | CF_ARCHIVE, "cl_beams_quakepositionhack", "1", "makes your lightning gun appear to fire from your waist (as in Quake and QuakeWorld)"};
78 cvar_t cl_beams_instantaimhack = {CF_CLIENT | CF_ARCHIVE, "cl_beams_instantaimhack", "0", "makes your lightning gun aiming update instantly"};
79 cvar_t cl_beams_lightatend = {CF_CLIENT | CF_ARCHIVE, "cl_beams_lightatend", "0", "make a light at the end of the beam"};
80
81 cvar_t cl_deathfade = {CF_CLIENT | CF_ARCHIVE, "cl_deathfade", "0", "fade screen to dark red when dead, value represents how fast the fade is (higher is faster)"};
82
83 cvar_t cl_noplayershadow = {CF_CLIENT | CF_ARCHIVE, "cl_noplayershadow", "0","hide player shadow"};
84
85 cvar_t cl_dlights_decayradius = {CF_CLIENT | CF_ARCHIVE, "cl_dlights_decayradius", "1", "reduces size of light flashes over time"};
86 cvar_t cl_dlights_decaybrightness = {CF_CLIENT | CF_ARCHIVE, "cl_dlights_decaybrightness", "1", "reduces brightness of light flashes over time"};
87
88 cvar_t qport = {CF_CLIENT, "qport", "0", "identification key for playing on qw servers (allows you to maintain a connection to a quakeworld server even if your port changes)"};
89
90 cvar_t cl_prydoncursor = {CF_CLIENT, "cl_prydoncursor", "0", "enables a mouse pointer which is able to click on entities in the world, useful for point and click mods, see PRYDON_CLIENTCURSOR extension in dpextensions.qc"};
91 cvar_t cl_prydoncursor_notrace = {CF_CLIENT, "cl_prydoncursor_notrace", "0", "disables traceline used in prydon cursor reporting to the game, saving some cpu time"};
92
93 cvar_t cl_deathnoviewmodel = {CF_CLIENT, "cl_deathnoviewmodel", "1", "hides gun model when dead"};
94
95 cvar_t cl_locs_enable = {CF_CLIENT | CF_ARCHIVE, "locs_enable", "1", "enables replacement of certain % codes in chat messages: %l (location), %d (last death location), %h (health), %a (armor), %x (rockets), %c (cells), %r (rocket launcher status), %p (powerup status), %w (weapon status), %t (current time in level)"};
96 cvar_t cl_locs_show = {CF_CLIENT, "locs_show", "0", "shows defined locations for editing purposes"};
97
98 cvar_t cl_minfps = {CF_CLIENT | CF_ARCHIVE, "cl_minfps", "40", "minimum fps target - while the rendering performance is below this, it will drift toward lower quality"};
99 cvar_t cl_minfps_fade = {CF_CLIENT | CF_ARCHIVE, "cl_minfps_fade", "1", "how fast the quality adapts to varying framerate"};
100 cvar_t cl_minfps_qualitymax = {CF_CLIENT | CF_ARCHIVE, "cl_minfps_qualitymax", "1", "highest allowed drawdistance multiplier"};
101 cvar_t cl_minfps_qualitymin = {CF_CLIENT | CF_ARCHIVE, "cl_minfps_qualitymin", "0.25", "lowest allowed drawdistance multiplier"};
102 cvar_t cl_minfps_qualitymultiply = {CF_CLIENT | CF_ARCHIVE, "cl_minfps_qualitymultiply", "0.2", "multiplier for quality changes in quality change per second render time (1 assumes linearity of quality and render time)"};
103 cvar_t cl_minfps_qualityhysteresis = {CF_CLIENT | CF_ARCHIVE, "cl_minfps_qualityhysteresis", "0.05", "reduce all quality increments by this to reduce flickering"};
104 cvar_t cl_minfps_qualitystepmax = {CF_CLIENT | CF_ARCHIVE, "cl_minfps_qualitystepmax", "0.1", "maximum quality change in a single frame"};
105 cvar_t cl_minfps_force = {CF_CLIENT, "cl_minfps_force", "0", "also apply quality reductions in timedemo/capturevideo"};
106 cvar_t cl_maxfps = {CF_CLIENT | CF_ARCHIVE, "cl_maxfps", "0", "maximum fps cap, 0 = unlimited, if game is running faster than this it will wait before running another frame (useful to make cpu time available to other programs)"};
107 cvar_t cl_maxfps_alwayssleep = {CF_CLIENT | CF_ARCHIVE, "cl_maxfps_alwayssleep","1", "gives up some processing time to other applications each frame, value in milliseconds, disabled if cl_maxfps is 0"};
108 cvar_t cl_maxidlefps = {CF_CLIENT | CF_ARCHIVE, "cl_maxidlefps", "20", "maximum fps cap when the game is not the active window (makes cpu time available to other programs"};
109
110 client_static_t cls;
111 client_state_t  cl;
112
113 /*
114 =====================
115 CL_ClearState
116
117 =====================
118 */
119 void CL_ClearState(void)
120 {
121         int i;
122         entity_t *ent;
123
124         CL_VM_ShutDown();
125
126 // wipe the entire cl structure
127         Mem_EmptyPool(cls.levelmempool);
128         memset (&cl, 0, sizeof(cl));
129
130         S_StopAllSounds();
131
132         // reset the view zoom interpolation
133         cl.mviewzoom[0] = cl.mviewzoom[1] = 1;
134         cl.sensitivityscale = 1.0f;
135
136         // enable rendering of the world and such
137         cl.csqc_vidvars.drawworld = r_drawworld.integer != 0;
138         cl.csqc_vidvars.drawenginesbar = true;
139         cl.csqc_vidvars.drawcrosshair = true;
140
141         // set up the float version of the stats array for easier access to float stats
142         cl.statsf = (float *)cl.stats;
143
144         cl.num_entities = 0;
145         cl.num_static_entities = 0;
146         cl.num_brushmodel_entities = 0;
147
148         // tweak these if the game runs out
149         cl.max_csqcrenderentities = 0;
150         cl.max_entities = MAX_ENTITIES_INITIAL;
151         cl.max_static_entities = MAX_STATICENTITIES;
152         cl.max_effects = MAX_EFFECTS;
153         cl.max_beams = MAX_BEAMS;
154         cl.max_dlights = MAX_DLIGHTS;
155         cl.max_lightstyle = MAX_LIGHTSTYLES;
156         cl.max_brushmodel_entities = MAX_EDICTS;
157         cl.max_particles = MAX_PARTICLES_INITIAL; // grows dynamically
158         cl.max_showlmps = 0;
159
160         cl.num_dlights = 0;
161         cl.num_effects = 0;
162         cl.num_beams = 0;
163
164         cl.csqcrenderentities = NULL;
165         cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
166         cl.entities_active = (unsigned char *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(unsigned char));
167         cl.static_entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_static_entities * sizeof(entity_t));
168         cl.effects = (cl_effect_t *)Mem_Alloc(cls.levelmempool, cl.max_effects * sizeof(cl_effect_t));
169         cl.beams = (beam_t *)Mem_Alloc(cls.levelmempool, cl.max_beams * sizeof(beam_t));
170         cl.dlights = (dlight_t *)Mem_Alloc(cls.levelmempool, cl.max_dlights * sizeof(dlight_t));
171         cl.lightstyle = (lightstyle_t *)Mem_Alloc(cls.levelmempool, cl.max_lightstyle * sizeof(lightstyle_t));
172         cl.brushmodel_entities = (int *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(int));
173         cl.particles = (particle_t *) Mem_Alloc(cls.levelmempool, cl.max_particles * sizeof(particle_t));
174         cl.showlmps = NULL;
175
176         // LadyHavoc: have to set up the baseline info for alpha and other stuff
177         for (i = 0;i < cl.max_entities;i++)
178         {
179                 cl.entities[i].state_baseline = defaultstate;
180                 cl.entities[i].state_previous = defaultstate;
181                 cl.entities[i].state_current = defaultstate;
182         }
183
184         if (IS_NEXUIZ_DERIVED(gamemode))
185         {
186                 VectorSet(cl.playerstandmins, -16, -16, -24);
187                 VectorSet(cl.playerstandmaxs, 16, 16, 45);
188                 VectorSet(cl.playercrouchmins, -16, -16, -24);
189                 VectorSet(cl.playercrouchmaxs, 16, 16, 25);
190         }
191         else
192         {
193                 VectorSet(cl.playerstandmins, -16, -16, -24);
194                 VectorSet(cl.playerstandmaxs, 16, 16, 24);
195                 VectorSet(cl.playercrouchmins, -16, -16, -24);
196                 VectorSet(cl.playercrouchmaxs, 16, 16, 24);
197         }
198
199         // disable until we get textures for it
200         R_ResetSkyBox();
201
202         ent = &cl.entities[0];
203         // entire entity array was cleared, so just fill in a few fields
204         ent->state_current.active = true;
205         ent->render.model = cl.worldmodel = NULL; // no world model yet
206         ent->render.alpha = 1;
207         ent->render.flags = RENDER_SHADOW | RENDER_LIGHT;
208         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, 0, 0, 0, 0, 0, 0, 1);
209         ent->render.allowdecals = true;
210         CL_UpdateRenderEntity(&ent->render);
211
212         // noclip is turned off at start
213         noclip_anglehack = false;
214
215         // mark all frames invalid for delta
216         memset(cl.qw_deltasequence, -1, sizeof(cl.qw_deltasequence));
217
218         // set bestweapon data back to Quake data
219         IN_BestWeapon_ResetData();
220
221         CL_Screen_NewMap();
222 }
223
224 extern cvar_t cl_topcolor;
225 extern cvar_t cl_bottomcolor;
226
227 void CL_SetInfo(const char *key, const char *value, qbool send, qbool allowstarkey, qbool allowmodel, qbool quiet)
228 {
229         int i;
230         qbool fail = false;
231         char vabuf[1024];
232         if (!allowstarkey && key[0] == '*')
233                 fail = true;
234         if (!allowmodel && (!strcasecmp(key, "pmodel") || !strcasecmp(key, "emodel")))
235                 fail = true;
236         for (i = 0;key[i];i++)
237                 if (ISWHITESPACE(key[i]) || key[i] == '\"')
238                         fail = true;
239         for (i = 0;value[i];i++)
240                 if (value[i] == '\r' || value[i] == '\n' || value[i] == '\"')
241                         fail = true;
242         if (fail)
243         {
244                 if (!quiet)
245                         Con_Printf("Can't setinfo \"%s\" \"%s\"\n", key, value);
246                 return;
247         }
248         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), key, value);
249         if (cls.state == ca_connected && cls.netcon)
250         {
251                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
252                 {
253                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
254                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "setinfo \"%s\" \"%s\"", key, value));
255                 }
256                 else if (!strcasecmp(key, "name"))
257                 {
258                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
259                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "name \"%s\"", value));
260                 }
261                 else if (!strcasecmp(key, "playermodel"))
262                 {
263                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
264                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "playermodel \"%s\"", value));
265                 }
266                 else if (!strcasecmp(key, "playerskin"))
267                 {
268                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
269                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "playerskin \"%s\"", value));
270                 }
271                 else if (!strcasecmp(key, "topcolor"))
272                 {
273                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
274                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "color %i %i", atoi(value), cl_bottomcolor.integer));
275                 }
276                 else if (!strcasecmp(key, "bottomcolor"))
277                 {
278                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
279                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "color %i %i", cl_topcolor.integer, atoi(value)));
280                 }
281                 else if (!strcasecmp(key, "rate"))
282                 {
283                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
284                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "rate \"%s\"", value));
285                 }
286                 else if (!strcasecmp(key, "rate_burstsize"))
287                 {
288                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
289                         MSG_WriteString(&cls.netcon->message, va(vabuf, sizeof(vabuf), "rate_burstsize \"%s\"", value));
290                 }
291         }
292 }
293
294 void CL_ExpandEntities(int num)
295 {
296         int i, oldmaxentities;
297         entity_t *oldentities;
298         if (num >= cl.max_entities)
299         {
300                 if (!cl.entities)
301                         Sys_Error("CL_ExpandEntities: cl.entities not initialized");
302                 if (num >= MAX_EDICTS)
303                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
304                 oldmaxentities = cl.max_entities;
305                 oldentities = cl.entities;
306                 cl.max_entities = (num & ~255) + 256;
307                 cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
308                 memcpy(cl.entities, oldentities, oldmaxentities * sizeof(entity_t));
309                 Mem_Free(oldentities);
310                 for (i = oldmaxentities;i < cl.max_entities;i++)
311                 {
312                         cl.entities[i].state_baseline = defaultstate;
313                         cl.entities[i].state_previous = defaultstate;
314                         cl.entities[i].state_current = defaultstate;
315                 }
316         }
317 }
318
319 void CL_ExpandCSQCRenderEntities(int num)
320 {
321         int i;
322         int oldmaxcsqcrenderentities;
323         entity_render_t *oldcsqcrenderentities;
324         if (num >= cl.max_csqcrenderentities)
325         {
326                 if (num >= MAX_EDICTS)
327                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
328                 oldmaxcsqcrenderentities = cl.max_csqcrenderentities;
329                 oldcsqcrenderentities = cl.csqcrenderentities;
330                 cl.max_csqcrenderentities = (num & ~255) + 256;
331                 cl.csqcrenderentities = (entity_render_t *)Mem_Alloc(cls.levelmempool, cl.max_csqcrenderentities * sizeof(entity_render_t));
332                 if (oldcsqcrenderentities)
333                 {
334                         memcpy(cl.csqcrenderentities, oldcsqcrenderentities, oldmaxcsqcrenderentities * sizeof(entity_render_t));
335                         for (i = 0;i < r_refdef.scene.numentities;i++)
336                                 if(r_refdef.scene.entities[i] >= oldcsqcrenderentities && r_refdef.scene.entities[i] < (oldcsqcrenderentities + oldmaxcsqcrenderentities))
337                                         r_refdef.scene.entities[i] = cl.csqcrenderentities + (r_refdef.scene.entities[i] - oldcsqcrenderentities);
338                         Mem_Free(oldcsqcrenderentities);
339                 }
340         }
341 }
342
343 extern cvar_t rcon_secure;
344
345 /*
346 =====================
347 CL_Disconnect
348
349 Sends a disconnect message to the server
350 This is also called on Host_Error, so it shouldn't cause any errors
351 =====================
352 */
353 void CL_Disconnect(void)
354 {
355         if (cls.state == ca_dedicated)
356                 return;
357
358         if (Sys_CheckParm("-profilegameonly"))
359                 Sys_AllowProfiling(false);
360
361         Curl_Clear_forthismap();
362
363         Con_DPrintf("CL_Disconnect\n");
364
365     Cvar_SetValueQuick(&csqc_progcrc, -1);
366         Cvar_SetValueQuick(&csqc_progsize, -1);
367         CL_VM_ShutDown();
368 // stop sounds (especially looping!)
369         S_StopAllSounds ();
370
371         cl.parsingtextexpectingpingforscores = 0; // just in case no reply has come yet
372
373         // clear contents blends
374         cl.cshifts[0].percent = 0;
375         cl.cshifts[1].percent = 0;
376         cl.cshifts[2].percent = 0;
377         cl.cshifts[3].percent = 0;
378
379         cl.worldmodel = NULL;
380
381         CL_Parse_ErrorCleanUp();
382
383         if (cls.demoplayback)
384                 CL_StopPlayback();
385         else if (cls.netcon)
386         {
387                 sizebuf_t buf;
388                 unsigned char bufdata[8];
389                 if (cls.demorecording)
390                         CL_Stop_f(&cmd_client);
391
392                 // send disconnect message 3 times to improve chances of server
393                 // receiving it (but it still fails sometimes)
394                 memset(&buf, 0, sizeof(buf));
395                 buf.data = bufdata;
396                 buf.maxsize = sizeof(bufdata);
397                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
398                 {
399                         Con_DPrint("Sending drop command\n");
400                         MSG_WriteByte(&buf, qw_clc_stringcmd);
401                         MSG_WriteString(&buf, "drop");
402                 }
403                 else
404                 {
405                         Con_DPrint("Sending clc_disconnect\n");
406                         MSG_WriteByte(&buf, clc_disconnect);
407                 }
408                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, 0, false);
409                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, 0, false);
410                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, 0, false);
411                 NetConn_Close(cls.netcon);
412                 cls.netcon = NULL;
413                 Con_Printf("Disconnected\n");
414         }
415         cls.state = ca_disconnected;
416         cl.islocalgame = false;
417
418         cls.demoplayback = cls.timedemo = host.restless = false;
419         cls.signon = 0;
420
421         // If we're dropped mid-connection attempt, it won't clear otherwise.
422         SCR_ClearLoadingScreen(false);
423 }
424
425 /*
426 ==================
427 CL_Reconnect_f
428
429 This command causes the client to wait for the signon messages again.
430 This is sent just before a server changes levels
431 ==================
432 */
433 void CL_Reconnect_f(cmd_state_t *cmd)
434 {
435         char temp[128];
436         // if not connected, reconnect to the most recent server
437         if (!cls.netcon)
438         {
439                 // if we have connected to a server recently, the userinfo
440                 // will still contain its IP address, so get the address...
441                 InfoString_GetValue(cls.userinfo, "*ip", temp, sizeof(temp));
442                 if (temp[0])
443                         CL_EstablishConnection(temp, -1);
444                 else
445                         Con_Printf("Reconnect to what server?  (you have not connected to a server yet)\n");
446                 return;
447         }
448         // if connected, do something based on protocol
449         if (cls.protocol == PROTOCOL_QUAKEWORLD)
450         {
451                 // quakeworld can just re-login
452                 if (cls.qw_downloadmemory)  // don't change when downloading
453                         return;
454
455                 S_StopAllSounds();
456
457                 if (cls.state == ca_connected)
458                 {
459                         Con_Printf("Server is changing level...\n");
460                         MSG_WriteChar(&cls.netcon->message, qw_clc_stringcmd);
461                         MSG_WriteString(&cls.netcon->message, "new");
462                 }
463         }
464         else
465         {
466                 // netquake uses reconnect on level changes (silly)
467                 if (Cmd_Argc(cmd) != 1)
468                 {
469                         Con_Print("reconnect : wait for signon messages again\n");
470                         return;
471                 }
472                 if (!cls.signon)
473                 {
474                         Con_Print("reconnect: no signon, ignoring reconnect\n");
475                         return;
476                 }
477                 cls.signon = 0;         // need new connection messages
478         }
479 }
480
481 /*
482 =====================
483 CL_Connect_f
484
485 User command to connect to server
486 =====================
487 */
488 static void CL_Connect_f(cmd_state_t *cmd)
489 {
490         if (Cmd_Argc(cmd) < 2)
491         {
492                 Con_Print("connect <serveraddress> [<key> <value> ...]: connect to a multiplayer game\n");
493                 return;
494         }
495         // clear the rcon password, to prevent vulnerability by stuffcmd-ing a connect command
496         if(rcon_secure.integer <= 0)
497                 Cvar_SetQuick(&rcon_password, "");
498         CL_EstablishConnection(Cmd_Argv(cmd, 1), 2);
499 }
500
501 void CL_Disconnect_f(cmd_state_t *cmd)
502 {
503         CL_Disconnect ();
504         if (sv.active)
505                 SV_Shutdown ();
506 }
507
508
509
510
511 /*
512 =====================
513 CL_EstablishConnection
514
515 Host should be either "local" or a net address
516 =====================
517 */
518 void CL_EstablishConnection(const char *address, int firstarg)
519 {
520         if (cls.state == ca_dedicated)
521                 return;
522
523         // don't connect to a server if we're benchmarking a demo
524         if (Sys_CheckParm("-benchmark"))
525                 return;
526
527         // clear menu's connect error message
528 #ifdef CONFIG_MENU
529         M_Update_Return_Reason("");
530 #endif
531
532         // make sure the client ports are open before attempting to connect
533         NetConn_UpdateSockets();
534
535         if (LHNETADDRESS_FromString(&cls.connect_address, address, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address)))
536         {
537                 // Disconnect from the current server, or stop a running demo.
538                 cls.connect_trying = true;
539                 cls.connect_remainingtries = 3;
540                 cls.connect_nextsendtime = 0;
541
542                 // only NOW, set connect_userinfo
543                 if(firstarg >= 0)
544                 {
545                         int i;
546                         *cls.connect_userinfo = 0;
547                         for(i = firstarg; i+2 <= Cmd_Argc(&cmd_client); i += 2)
548                                 InfoString_SetValue(cls.connect_userinfo, sizeof(cls.connect_userinfo), Cmd_Argv(&cmd_client, i), Cmd_Argv(&cmd_client, i+1));
549                 }
550                 else if(firstarg < -1)
551                 {
552                         // -1: keep as is (reconnect)
553                         // -2: clear
554                         *cls.connect_userinfo = 0;
555                 }
556
557 #ifdef CONFIG_MENU
558                 M_Update_Return_Reason("Trying to connect...");
559 #endif
560         }
561         else
562         {
563                 Con_Print("Unable to find a suitable network socket to connect to server.\n");
564 #ifdef CONFIG_MENU
565                 M_Update_Return_Reason("No network");
566 #endif
567         }
568 }
569
570 static void CL_EstablishConnection_Local(void)
571 {
572         if(cls.state == ca_disconnected)
573                 CL_EstablishConnection("local:1", -2);
574 }
575
576 /*
577 ==============
578 CL_PrintEntities_f
579 ==============
580 */
581 static void CL_PrintEntities_f(cmd_state_t *cmd)
582 {
583         entity_t *ent;
584         int i;
585
586         for (i = 0, ent = cl.entities;i < cl.num_entities;i++, ent++)
587         {
588                 const char* modelname;
589
590                 if (!ent->state_current.active)
591                         continue;
592
593                 if (ent->render.model)
594                         modelname = ent->render.model->name;
595                 else
596                         modelname = "--no model--";
597                 Con_Printf("%3i: %-25s:%4i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, modelname, ent->render.framegroupblend[0].frame, (int) ent->state_current.origin[0], (int) ent->state_current.origin[1], (int) ent->state_current.origin[2], (int) ent->state_current.angles[0] % 360, (int) ent->state_current.angles[1] % 360, (int) ent->state_current.angles[2] % 360, ent->render.scale, ent->render.alpha);
598         }
599 }
600
601 /*
602 ===============
603 CL_ModelIndexList_f
604
605 List information on all models in the client modelindex
606 ===============
607 */
608 static void CL_ModelIndexList_f(cmd_state_t *cmd)
609 {
610         int i;
611         dp_model_t *model;
612
613         // Print Header
614         Con_Printf("%3s: %-30s %-8s %-8s\n", "ID", "Name", "Type", "Triangles");
615
616         for (i = -MAX_MODELS;i < MAX_MODELS;i++)
617         {
618                 model = CL_GetModelByIndex(i);
619                 if (!model)
620                         continue;
621                 if(model->loaded || i == 1)
622                         Con_Printf("%3i: %-30s %-8s %-10i\n", i, model->name, model->modeldatatypestring, model->surfmesh.num_triangles);
623                 else
624                         Con_Printf("%3i: %-30s %-30s\n", i, model->name, "--no local model found--");
625                 i++;
626         }
627 }
628
629 /*
630 ===============
631 CL_SoundIndexList_f
632
633 List all sounds in the client soundindex
634 ===============
635 */
636 static void CL_SoundIndexList_f(cmd_state_t *cmd)
637 {
638         int i = 1;
639
640         while(cl.sound_precache[i] && i != MAX_SOUNDS)
641         { // Valid Sound
642                 Con_Printf("%i : %s\n", i, cl.sound_precache[i]->name);
643                 i++;
644         }
645 }
646
647 /*
648 ===============
649 CL_UpdateRenderEntity
650
651 Updates inversematrix, animation interpolation factors, scale, and mins/maxs
652 ===============
653 */
654 void CL_UpdateRenderEntity(entity_render_t *ent)
655 {
656         vec3_t org;
657         vec_t scale;
658         dp_model_t *model = ent->model;
659         // update the inverse matrix for the renderer
660         Matrix4x4_Invert_Simple(&ent->inversematrix, &ent->matrix);
661         // update the animation blend state
662         VM_FrameBlendFromFrameGroupBlend(ent->frameblend, ent->framegroupblend, ent->model, cl.time);
663         // we need the matrix origin to center the box
664         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
665         // update entity->render.scale because the renderer needs it
666         ent->scale = scale = Matrix4x4_ScaleFromMatrix(&ent->matrix);
667         if (model)
668         {
669                 // NOTE: this directly extracts vector components from the matrix, which relies on the matrix orientation!
670 #ifdef MATRIX4x4_OPENGLORIENTATION
671                 if (ent->matrix.m[0][2] != 0 || ent->matrix.m[1][2] != 0)
672 #else
673                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
674 #endif
675                 {
676                         // pitch or roll
677                         VectorMA(org, scale, model->rotatedmins, ent->mins);
678                         VectorMA(org, scale, model->rotatedmaxs, ent->maxs);
679                 }
680 #ifdef MATRIX4x4_OPENGLORIENTATION
681                 else if (ent->matrix.m[1][0] != 0 || ent->matrix.m[0][1] != 0)
682 #else
683                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
684 #endif
685                 {
686                         // yaw
687                         VectorMA(org, scale, model->yawmins, ent->mins);
688                         VectorMA(org, scale, model->yawmaxs, ent->maxs);
689                 }
690                 else
691                 {
692                         VectorMA(org, scale, model->normalmins, ent->mins);
693                         VectorMA(org, scale, model->normalmaxs, ent->maxs);
694                 }
695         }
696         else
697         {
698                 ent->mins[0] = org[0] - 16;
699                 ent->mins[1] = org[1] - 16;
700                 ent->mins[2] = org[2] - 16;
701                 ent->maxs[0] = org[0] + 16;
702                 ent->maxs[1] = org[1] + 16;
703                 ent->maxs[2] = org[2] + 16;
704         }
705 }
706
707 /*
708 ===============
709 CL_LerpPoint
710
711 Determines the fraction between the last two messages that the objects
712 should be put at.
713 ===============
714 */
715 static float CL_LerpPoint(void)
716 {
717         float f;
718
719         if (cl_nettimesyncboundmode.integer == 1)
720                 cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
721
722         // LadyHavoc: lerp in listen games as the server is being capped below the client (usually)
723         if (cl.mtime[0] <= cl.mtime[1])
724         {
725                 cl.time = cl.mtime[0];
726                 return 1;
727         }
728
729         f = (cl.time - cl.mtime[1]) / (cl.mtime[0] - cl.mtime[1]);
730         return bound(0, f, 1 + cl_lerpexcess.value);
731 }
732
733 void CL_ClearTempEntities (void)
734 {
735         r_refdef.scene.numtempentities = 0;
736         // grow tempentities buffer on request
737         if (r_refdef.scene.expandtempentities)
738         {
739                 Con_Printf("CL_NewTempEntity: grow maxtempentities from %i to %i\n", r_refdef.scene.maxtempentities, r_refdef.scene.maxtempentities * 2);
740                 r_refdef.scene.maxtempentities *= 2;
741                 r_refdef.scene.tempentities = (entity_render_t *)Mem_Realloc(cls.permanentmempool, r_refdef.scene.tempentities, sizeof(entity_render_t) * r_refdef.scene.maxtempentities);
742                 r_refdef.scene.expandtempentities = false;
743         }
744 }
745
746 entity_render_t *CL_NewTempEntity(double shadertime)
747 {
748         entity_render_t *render;
749
750         if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
751                 return NULL;
752         if (r_refdef.scene.numtempentities >= r_refdef.scene.maxtempentities)
753         {
754                 r_refdef.scene.expandtempentities = true; // will be reallocated next frame since current frame may have pointers set already
755                 return NULL;
756         }
757         render = &r_refdef.scene.tempentities[r_refdef.scene.numtempentities++];
758         memset (render, 0, sizeof(*render));
759         r_refdef.scene.entities[r_refdef.scene.numentities++] = render;
760
761         render->shadertime = shadertime;
762         render->alpha = 1;
763         VectorSet(render->colormod, 1, 1, 1);
764         VectorSet(render->glowmod, 1, 1, 1);
765         return render;
766 }
767
768 void CL_Effect(vec3_t org, dp_model_t *model, int startframe, int framecount, float framerate)
769 {
770         int i;
771         cl_effect_t *e;
772         if (!model) // sanity check
773                 return;
774         if (framerate < 1)
775         {
776                 Con_Printf("CL_Effect: framerate %f is < 1\n", framerate);
777                 return;
778         }
779         if (framecount < 1)
780         {
781                 Con_Printf("CL_Effect: framecount %i is < 1\n", framecount);
782                 return;
783         }
784         for (i = 0, e = cl.effects;i < cl.max_effects;i++, e++)
785         {
786                 if (e->active)
787                         continue;
788                 e->active = true;
789                 VectorCopy(org, e->origin);
790                 e->model = model;
791                 e->starttime = cl.time;
792                 e->startframe = startframe;
793                 e->endframe = startframe + framecount;
794                 e->framerate = framerate;
795
796                 e->frame = 0;
797                 e->frame1time = cl.time;
798                 e->frame2time = cl.time;
799                 cl.num_effects = max(cl.num_effects, i + 1);
800                 break;
801         }
802 }
803
804 void CL_AllocLightFlash(entity_render_t *ent, matrix4x4_t *matrix, float radius, float red, float green, float blue, float decay, float lifetime, char *cubemapname, int style, int shadowenable, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
805 {
806         int i;
807         dlight_t *dl;
808
809 // then look for anything else
810         dl = cl.dlights;
811         for (i = 0;i < cl.max_dlights;i++, dl++)
812                 if (!dl->radius)
813                         break;
814
815         // unable to find one
816         if (i == cl.max_dlights)
817                 return;
818
819         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
820         memset (dl, 0, sizeof(*dl));
821         cl.num_dlights = max(cl.num_dlights, i + 1);
822         Matrix4x4_Normalize(&dl->matrix, matrix);
823         dl->ent = ent;
824         Matrix4x4_OriginFromMatrix(&dl->matrix, dl->origin);
825         CL_FindNonSolidLocation(dl->origin, dl->origin, 6);
826         Matrix4x4_SetOrigin(&dl->matrix, dl->origin[0], dl->origin[1], dl->origin[2]);
827         dl->radius = radius;
828         dl->color[0] = red;
829         dl->color[1] = green;
830         dl->color[2] = blue;
831         dl->initialradius = radius;
832         dl->initialcolor[0] = red;
833         dl->initialcolor[1] = green;
834         dl->initialcolor[2] = blue;
835         dl->decay = decay / radius; // changed decay to be a percentage decrease
836         dl->intensity = 1; // this is what gets decayed
837         if (lifetime)
838                 dl->die = cl.time + lifetime;
839         else
840                 dl->die = 0;
841         dl->cubemapname[0] = 0;
842         if (cubemapname && cubemapname[0])
843                 strlcpy(dl->cubemapname, cubemapname, sizeof(dl->cubemapname));
844         dl->style = style;
845         dl->shadow = shadowenable;
846         dl->corona = corona;
847         dl->flags = flags;
848         dl->coronasizescale = coronasizescale;
849         dl->ambientscale = ambientscale;
850         dl->diffusescale = diffusescale;
851         dl->specularscale = specularscale;
852 }
853
854 static void CL_DecayLightFlashes(void)
855 {
856         int i, oldmax;
857         dlight_t *dl;
858         float time;
859
860         time = bound(0, cl.time - cl.oldtime, 0.1);
861         oldmax = cl.num_dlights;
862         cl.num_dlights = 0;
863         for (i = 0, dl = cl.dlights;i < oldmax;i++, dl++)
864         {
865                 if (dl->radius)
866                 {
867                         dl->intensity -= time * dl->decay;
868                         if (cl.time < dl->die && dl->intensity > 0)
869                         {
870                                 if (cl_dlights_decayradius.integer)
871                                         dl->radius = dl->initialradius * dl->intensity;
872                                 else
873                                         dl->radius = dl->initialradius;
874                                 if (cl_dlights_decaybrightness.integer)
875                                         VectorScale(dl->initialcolor, dl->intensity, dl->color);
876                                 else
877                                         VectorCopy(dl->initialcolor, dl->color);
878                                 cl.num_dlights = i + 1;
879                         }
880                         else
881                                 dl->radius = 0;
882                 }
883         }
884 }
885
886 // called before entity relinking
887 void CL_RelinkLightFlashes(void)
888 {
889         int i, j, k, l;
890         dlight_t *dl;
891         float frac, f;
892         matrix4x4_t tempmatrix;
893
894         if (r_dynamic.integer)
895         {
896                 for (i = 0, dl = cl.dlights;i < cl.num_dlights && r_refdef.scene.numlights < MAX_DLIGHTS;i++, dl++)
897                 {
898                         if (dl->radius)
899                         {
900                                 tempmatrix = dl->matrix;
901                                 Matrix4x4_Scale(&tempmatrix, dl->radius, 1);
902                                 // we need the corona fading to be persistent
903                                 R_RTLight_Update(&dl->rtlight, false, &tempmatrix, dl->color, dl->style, dl->cubemapname, dl->shadow, dl->corona, dl->coronasizescale, dl->ambientscale, dl->diffusescale, dl->specularscale, dl->flags);
904                                 r_refdef.scene.lights[r_refdef.scene.numlights++] = &dl->rtlight;
905                         }
906                 }
907         }
908
909         if (!cl.lightstyle)
910         {
911                 for (j = 0;j < cl.max_lightstyle;j++)
912                 {
913                         r_refdef.scene.rtlightstylevalue[j] = 1;
914                         r_refdef.scene.lightstylevalue[j] = 256;
915                 }
916                 return;
917         }
918
919 // light animations
920 // 'm' is normal light, 'a' is no light, 'z' is double bright
921         f = cl.time * 10;
922         i = (int)floor(f);
923         frac = f - i;
924         for (j = 0;j < cl.max_lightstyle;j++)
925         {
926                 if (!cl.lightstyle[j].length)
927                 {
928                         r_refdef.scene.rtlightstylevalue[j] = 1;
929                         r_refdef.scene.lightstylevalue[j] = 256;
930                         continue;
931                 }
932                 // static lightstyle "=value"
933                 if (cl.lightstyle[j].map[0] == '=')
934                 {
935                         r_refdef.scene.rtlightstylevalue[j] = atof(cl.lightstyle[j].map + 1);
936                         if ( r_lerplightstyles.integer || ((int)f - f) < 0.01)
937                                 r_refdef.scene.lightstylevalue[j] = r_refdef.scene.rtlightstylevalue[j];
938                         continue;
939                 }
940                 k = i % cl.lightstyle[j].length;
941                 l = (i-1) % cl.lightstyle[j].length;
942                 k = cl.lightstyle[j].map[k] - 'a';
943                 l = cl.lightstyle[j].map[l] - 'a';
944                 // rtlightstylevalue is always interpolated because it has no bad
945                 // consequences for performance
946                 // lightstylevalue is subject to a cvar for performance reasons;
947                 // skipping lightmap updates on most rendered frames substantially
948                 // improves framerates (but makes light fades look bad)
949                 r_refdef.scene.rtlightstylevalue[j] = ((k*frac)+(l*(1-frac)))*(22/256.0f);
950                 r_refdef.scene.lightstylevalue[j] = r_lerplightstyles.integer ? (unsigned short)(((k*frac)+(l*(1-frac)))*22) : k*22;
951         }
952 }
953
954 static void CL_AddQWCTFFlagModel(entity_t *player, int skin)
955 {
956         int frame = player->render.framegroupblend[0].frame;
957         float f;
958         entity_render_t *flagrender;
959         matrix4x4_t flagmatrix;
960
961         // this code taken from QuakeWorld
962         f = 14;
963         if (frame >= 29 && frame <= 40)
964         {
965                 if (frame >= 29 && frame <= 34)
966                 { //axpain
967                         if      (frame == 29) f = f + 2;
968                         else if (frame == 30) f = f + 8;
969                         else if (frame == 31) f = f + 12;
970                         else if (frame == 32) f = f + 11;
971                         else if (frame == 33) f = f + 10;
972                         else if (frame == 34) f = f + 4;
973                 }
974                 else if (frame >= 35 && frame <= 40)
975                 { // pain
976                         if      (frame == 35) f = f + 2;
977                         else if (frame == 36) f = f + 10;
978                         else if (frame == 37) f = f + 10;
979                         else if (frame == 38) f = f + 8;
980                         else if (frame == 39) f = f + 4;
981                         else if (frame == 40) f = f + 2;
982                 }
983         }
984         else if (frame >= 103 && frame <= 118)
985         {
986                 if      (frame >= 103 && frame <= 104) f = f + 6;  //nailattack
987                 else if (frame >= 105 && frame <= 106) f = f + 6;  //light
988                 else if (frame >= 107 && frame <= 112) f = f + 7;  //rocketattack
989                 else if (frame >= 112 && frame <= 118) f = f + 7;  //shotattack
990         }
991         // end of code taken from QuakeWorld
992
993         flagrender = CL_NewTempEntity(player->render.shadertime);
994         if (!flagrender)
995                 return;
996
997         flagrender->model = CL_GetModelByIndex(cl.qw_modelindex_flag);
998         flagrender->skinnum = skin;
999         flagrender->alpha = 1;
1000         VectorSet(flagrender->colormod, 1, 1, 1);
1001         VectorSet(flagrender->glowmod, 1, 1, 1);
1002         // attach the flag to the player matrix
1003         Matrix4x4_CreateFromQuakeEntity(&flagmatrix, -f, -22, 0, 0, 0, -45, 1);
1004         Matrix4x4_Concat(&flagrender->matrix, &player->render.matrix, &flagmatrix);
1005         CL_UpdateRenderEntity(flagrender);
1006 }
1007
1008 matrix4x4_t viewmodelmatrix_withbob;
1009 matrix4x4_t viewmodelmatrix_nobob;
1010
1011 static const vec3_t muzzleflashorigin = {18, 0, 0};
1012
1013 void CL_SetEntityColormapColors(entity_render_t *ent, int colormap)
1014 {
1015         const unsigned char *cbcolor;
1016         if (colormap >= 0)
1017         {
1018                 cbcolor = palette_rgb_pantscolormap[colormap & 0xF];
1019                 VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_pantscolor);
1020                 cbcolor = palette_rgb_shirtcolormap[(colormap & 0xF0) >> 4];
1021                 VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_shirtcolor);
1022         }
1023         else
1024         {
1025                 VectorClear(ent->colormap_pantscolor);
1026                 VectorClear(ent->colormap_shirtcolor);
1027         }
1028 }
1029
1030 // note this is a recursive function, recursionlimit should be 32 or so on the initial call
1031 static void CL_UpdateNetworkEntity(entity_t *e, int recursionlimit, qbool interpolate)
1032 {
1033         const matrix4x4_t *matrix;
1034         matrix4x4_t blendmatrix, tempmatrix, matrix2;
1035         int frame;
1036         vec_t origin[3], angles[3], lerp;
1037         entity_t *t;
1038         entity_render_t *r;
1039         //entity_persistent_t *p = &e->persistent;
1040         //entity_render_t *r = &e->render;
1041         // skip inactive entities and world
1042         if (!e->state_current.active || e == cl.entities)
1043                 return;
1044         if (recursionlimit < 1)
1045                 return;
1046         e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
1047         e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
1048         e->render.flags = e->state_current.flags;
1049         e->render.effects = e->state_current.effects;
1050         VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod);
1051         VectorScale(e->state_current.glowmod, (1.0f / 32.0f), e->render.glowmod);
1052         if(e >= cl.entities && e < cl.entities + cl.num_entities)
1053                 e->render.entitynumber = e - cl.entities;
1054         else
1055                 e->render.entitynumber = 0;
1056         if (e->state_current.flags & RENDER_COLORMAPPED)
1057                 CL_SetEntityColormapColors(&e->render, e->state_current.colormap);
1058         else if (e->state_current.colormap > 0 && e->state_current.colormap <= cl.maxclients && cl.scores != NULL)
1059                 CL_SetEntityColormapColors(&e->render, cl.scores[e->state_current.colormap-1].colors);
1060         else
1061                 CL_SetEntityColormapColors(&e->render, -1);
1062         e->render.skinnum = e->state_current.skin;
1063         if (e->state_current.tagentity)
1064         {
1065                 // attached entity (gun held in player model's hand, etc)
1066                 // if the tag entity is currently impossible, skip it
1067                 if (e->state_current.tagentity >= cl.num_entities)
1068                         return;
1069                 t = cl.entities + e->state_current.tagentity;
1070                 // if the tag entity is inactive, skip it
1071                 if (t->state_current.active)
1072                 {
1073                         // update the parent first
1074                         CL_UpdateNetworkEntity(t, recursionlimit - 1, interpolate);
1075                         r = &t->render;
1076                 }
1077                 else
1078                 {
1079                         // it may still be a CSQC entity... trying to use its
1080                         // info from last render frame (better than nothing)
1081                         if(!cl.csqc_server2csqcentitynumber[e->state_current.tagentity])
1082                                 return;
1083                         r = cl.csqcrenderentities + cl.csqc_server2csqcentitynumber[e->state_current.tagentity];
1084                         if(!r->entitynumber)
1085                                 return; // neither CSQC nor legacy entity... can't attach
1086                 }
1087                 // make relative to the entity
1088                 matrix = &r->matrix;
1089                 // some properties of the tag entity carry over
1090                 e->render.flags |= r->flags & (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL);
1091                 // if a valid tagindex is used, make it relative to that tag instead
1092                 if (e->state_current.tagentity && e->state_current.tagindex >= 1 && r->model)
1093                 {
1094                         if(!Mod_Alias_GetTagMatrix(r->model, r->frameblend, r->skeleton, e->state_current.tagindex - 1, &blendmatrix)) // i.e. no error
1095                         {
1096                                 // concat the tag matrices onto the entity matrix
1097                                 Matrix4x4_Concat(&tempmatrix, &r->matrix, &blendmatrix);
1098                                 // use the constructed tag matrix
1099                                 matrix = &tempmatrix;
1100                         }
1101                 }
1102         }
1103         else if (e->render.flags & RENDER_VIEWMODEL)
1104         {
1105                 // view-relative entity (guns and such)
1106                 if (e->render.effects & EF_NOGUNBOB)
1107                         matrix = &viewmodelmatrix_nobob; // really attached to view
1108                 else
1109                         matrix = &viewmodelmatrix_withbob; // attached to gun bob matrix
1110         }
1111         else
1112         {
1113                 // world-relative entity (the normal kind)
1114                 matrix = &identitymatrix;
1115         }
1116
1117         // movement lerp
1118         // if it's the predicted player entity, update according to client movement
1119         // but don't lerp if going through a teleporter as it causes a bad lerp
1120         // also don't use the predicted location if fixangle was set on both of
1121         // the most recent server messages, as that cause means you are spectating
1122         // someone or watching a cutscene of some sort
1123         if (cl_nolerp.integer || cls.timedemo)
1124                 interpolate = false;
1125         if (e == cl.entities + cl.playerentity && cl.movement_predicted && (!cl.fixangle[1] || !cl.fixangle[0]))
1126         {
1127                 VectorCopy(cl.movement_origin, origin);
1128                 VectorSet(angles, 0, cl.viewangles[1], 0);
1129         }
1130         else if (interpolate && e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1 + cl_lerpexcess.value)
1131         {
1132                 // interpolate the origin and angles
1133                 lerp = max(0, lerp);
1134                 VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin);
1135 #if 0
1136                 // this fails at the singularity of euler angles
1137                 VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta);
1138                 if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
1139                 if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
1140                 if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
1141                 VectorMA(e->persistent.oldangles, lerp, delta, angles);
1142 #else
1143                 {
1144                         vec3_t f0, u0, f1, u1;
1145                         AngleVectors(e->persistent.oldangles, f0, NULL, u0);
1146                         AngleVectors(e->persistent.newangles, f1, NULL, u1);
1147                         VectorMAM(1-lerp, f0, lerp, f1, f0);
1148                         VectorMAM(1-lerp, u0, lerp, u1, u0);
1149                         AnglesFromVectors(angles, f0, u0, false);
1150                 }
1151 #endif
1152         }
1153         else
1154         {
1155                 // no interpolation
1156                 VectorCopy(e->persistent.neworigin, origin);
1157                 VectorCopy(e->persistent.newangles, angles);
1158         }
1159
1160         // model setup and some modelflags
1161         frame = e->state_current.frame;
1162         e->render.model = CL_GetModelByIndex(e->state_current.modelindex);
1163         if (e->render.model)
1164         {
1165                 if (e->render.skinnum >= e->render.model->numskins)
1166                         e->render.skinnum = 0;
1167                 if (frame >= e->render.model->numframes)
1168                         frame = 0;
1169                 // models can set flags such as EF_ROCKET
1170                 // this 0xFF800000 mask is EF_NOMODELFLAGS plus all the higher EF_ flags such as EF_ROCKET
1171                 if (!(e->render.effects & 0xFF800000))
1172                         e->render.effects |= e->render.model->effects;
1173                 // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
1174                 if (e->render.model->type == mod_alias)
1175                         angles[0] = -angles[0];
1176                 if ((e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number)
1177                 {
1178                         VectorScale(e->render.colormod, 2, e->render.colormod);
1179                         VectorScale(e->render.glowmod, 2, e->render.glowmod);
1180                 }
1181         }
1182         // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
1183         else if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC)
1184                 angles[0] = -angles[0];
1185                 // NOTE: this must be synced to SV_GetPitchSign!
1186
1187         if ((e->render.effects & EF_ROTATE) && !(e->render.flags & RENDER_VIEWMODEL))
1188         {
1189                 angles[1] = ANGLEMOD(100*cl.time);
1190                 if (cl_itembobheight.value)
1191                         origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
1192         }
1193
1194         // animation lerp
1195         e->render.skeleton = NULL;
1196         if (e->render.flags & RENDER_COMPLEXANIMATION)
1197         {
1198                 e->render.framegroupblend[0] = e->state_current.framegroupblend[0];
1199                 e->render.framegroupblend[1] = e->state_current.framegroupblend[1];
1200                 e->render.framegroupblend[2] = e->state_current.framegroupblend[2];
1201                 e->render.framegroupblend[3] = e->state_current.framegroupblend[3];
1202                 if (e->state_current.skeletonobject.model && e->state_current.skeletonobject.relativetransforms)
1203                         e->render.skeleton = &e->state_current.skeletonobject;
1204         }
1205         else if (e->render.framegroupblend[0].frame == frame)
1206         {
1207                 // update frame lerp fraction
1208                 e->render.framegroupblend[0].lerp = 1;
1209                 e->render.framegroupblend[1].lerp = 0;
1210                 if (e->render.framegroupblend[0].start > e->render.framegroupblend[1].start)
1211                 {
1212                         // make sure frame lerp won't last longer than 100ms
1213                         // (this mainly helps with models that use framegroups and
1214                         // switch between them infrequently)
1215                         float maxdelta = cl_lerpanim_maxdelta_server.value;
1216                         if(e->render.model)
1217                         if(e->render.model->animscenes)
1218                         if(e->render.model->animscenes[e->render.framegroupblend[0].frame].framecount > 1 || e->render.model->animscenes[e->render.framegroupblend[1].frame].framecount > 1)
1219                                 maxdelta = cl_lerpanim_maxdelta_framegroups.value;
1220                         maxdelta = max(maxdelta, cl.mtime[0] - cl.mtime[1]);
1221                         e->render.framegroupblend[0].lerp = (cl.time - e->render.framegroupblend[0].start) / min(e->render.framegroupblend[0].start - e->render.framegroupblend[1].start, maxdelta);
1222                         e->render.framegroupblend[0].lerp = bound(0, e->render.framegroupblend[0].lerp, 1);
1223                         e->render.framegroupblend[1].lerp = 1 - e->render.framegroupblend[0].lerp;
1224                 }
1225         }
1226         else
1227         {
1228                 // begin a new frame lerp
1229                 e->render.framegroupblend[1] = e->render.framegroupblend[0];
1230                 e->render.framegroupblend[1].lerp = 1;
1231                 e->render.framegroupblend[0].frame = frame;
1232                 e->render.framegroupblend[0].start = cl.time;
1233                 e->render.framegroupblend[0].lerp = 0;
1234         }
1235
1236         // set up the render matrix
1237         if (matrix)
1238         {
1239                 // attached entity, this requires a matrix multiply (concat)
1240                 // FIXME: e->render.scale should go away
1241                 Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
1242                 // concat the matrices to make the entity relative to its tag
1243                 Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2);
1244                 // get the origin from the new matrix
1245                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1246         }
1247         else
1248         {
1249                 // unattached entities are faster to process
1250                 Matrix4x4_CreateFromQuakeEntity(&e->render.matrix, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
1251         }
1252
1253         // tenebrae's sprites are all additive mode (weird)
1254         if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite)
1255                 e->render.flags |= RENDER_ADDITIVE;
1256         // player model is only shown with chase_active on
1257         if (e->state_current.number == cl.viewentity)
1258                 e->render.flags |= RENDER_EXTERIORMODEL;
1259         // either fullbright or lit
1260         if(!r_fullbright.integer)
1261         {
1262                 if (!(e->render.effects & EF_FULLBRIGHT))
1263                         e->render.flags |= RENDER_LIGHT;
1264         }
1265         // hide player shadow during intermission or nehahra movie
1266         if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
1267          && (e->render.alpha >= 1)
1268          && !(e->render.flags & RENDER_VIEWMODEL)
1269          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
1270                 e->render.flags |= RENDER_SHADOW;
1271         if (e->render.flags & RENDER_VIEWMODEL)
1272                 e->render.flags |= RENDER_NOSELFSHADOW;
1273         if (e->render.effects & EF_NOSELFSHADOW)
1274                 e->render.flags |= RENDER_NOSELFSHADOW;
1275         if (e->render.effects & EF_NODEPTHTEST)
1276                 e->render.flags |= RENDER_NODEPTHTEST;
1277         if (e->render.effects & EF_ADDITIVE)
1278                 e->render.flags |= RENDER_ADDITIVE;
1279         if (e->render.effects & EF_DOUBLESIDED)
1280                 e->render.flags |= RENDER_DOUBLESIDED;
1281         if (e->render.effects & EF_DYNAMICMODELLIGHT)
1282                 e->render.flags |= RENDER_DYNAMICMODELLIGHT;
1283
1284         // make the other useful stuff
1285         e->render.allowdecals = true;
1286         CL_UpdateRenderEntity(&e->render);
1287 }
1288
1289 // creates light and trails from an entity
1290 static void CL_UpdateNetworkEntityTrail(entity_t *e)
1291 {
1292         effectnameindex_t trailtype;
1293         vec3_t origin;
1294
1295         // bmodels are treated specially since their origin is usually '0 0 0' and
1296         // their actual geometry is far from '0 0 0'
1297         if (e->render.model && e->render.model->soundfromcenter)
1298         {
1299                 vec3_t o;
1300                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1301                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1302         }
1303         else
1304                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1305
1306         // handle particle trails and such effects now that we know where this
1307         // entity is in the world...
1308         trailtype = EFFECT_NONE;
1309         // LadyHavoc: if the entity has no effects, don't check each
1310         if (e->render.effects & (EF_BRIGHTFIELD | EF_FLAME | EF_STARDUST))
1311         {
1312                 if (e->render.effects & EF_BRIGHTFIELD)
1313                 {
1314                         if (IS_NEXUIZ_DERIVED(gamemode))
1315                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1316                         else
1317                                 CL_EntityParticles(e);
1318                 }
1319                 if (e->render.effects & EF_FLAME)
1320                         CL_ParticleTrail(EFFECT_EF_FLAME, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true, NULL, NULL, 1);
1321                 if (e->render.effects & EF_STARDUST)
1322                         CL_ParticleTrail(EFFECT_EF_STARDUST, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true, NULL, NULL, 1);
1323         }
1324         if (e->render.internaleffects & (INTEF_FLAG1QW | INTEF_FLAG2QW))
1325         {
1326                 // these are only set on player entities
1327                 CL_AddQWCTFFlagModel(e, (e->render.internaleffects & INTEF_FLAG2QW) != 0);
1328         }
1329         // muzzleflash fades over time
1330         if (e->persistent.muzzleflash > 0)
1331                 e->persistent.muzzleflash -= bound(0, cl.time - cl.oldtime, 0.1) * 20;
1332         // LadyHavoc: if the entity has no effects, don't check each
1333         if (e->render.effects && !(e->render.flags & RENDER_VIEWMODEL))
1334         {
1335                 if (e->render.effects & EF_GIB)
1336                         trailtype = EFFECT_TR_BLOOD;
1337                 else if (e->render.effects & EF_ZOMGIB)
1338                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1339                 else if (e->render.effects & EF_TRACER)
1340                         trailtype = EFFECT_TR_WIZSPIKE;
1341                 else if (e->render.effects & EF_TRACER2)
1342                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1343                 else if (e->render.effects & EF_ROCKET)
1344                         trailtype = EFFECT_TR_ROCKET;
1345                 else if (e->render.effects & EF_GRENADE)
1346                 {
1347                         // LadyHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1348                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1349                 }
1350                 else if (e->render.effects & EF_TRACER3)
1351                         trailtype = EFFECT_TR_VORESPIKE;
1352         }
1353         // do trails
1354         if (e->render.flags & RENDER_GLOWTRAIL)
1355                 trailtype = EFFECT_TR_GLOWTRAIL;
1356         if (e->state_current.traileffectnum)
1357                 trailtype = (effectnameindex_t)e->state_current.traileffectnum;
1358         // check if a trail is allowed (it is not after a teleport for example)
1359         if (trailtype && e->persistent.trail_allowed)
1360         {
1361                 float len;
1362                 vec3_t vel;
1363                 VectorSubtract(e->state_current.origin, e->state_previous.origin, vel);
1364                 len = e->state_current.time - e->state_previous.time;
1365                 if (len > 0)
1366                         len = 1.0f / len;
1367                 VectorScale(vel, len, vel);
1368                 // pass time as count so that trails that are time based (such as an emitter) will emit properly as long as they don't use trailspacing
1369                 CL_ParticleTrail(trailtype, bound(0, cl.time - cl.oldtime, 0.1), e->persistent.trail_origin, origin, vel, vel, e, e->state_current.glowcolor, false, true, NULL, NULL, 1);
1370         }
1371         // now that the entity has survived one trail update it is allowed to
1372         // leave a real trail on later frames
1373         e->persistent.trail_allowed = true;
1374         VectorCopy(origin, e->persistent.trail_origin);
1375 }
1376
1377
1378 /*
1379 ===============
1380 CL_UpdateViewEntities
1381 ===============
1382 */
1383 void CL_UpdateViewEntities(void)
1384 {
1385         int i;
1386         // update any RENDER_VIEWMODEL entities to use the new view matrix
1387         for (i = 1;i < cl.num_entities;i++)
1388         {
1389                 if (cl.entities_active[i])
1390                 {
1391                         entity_t *ent = cl.entities + i;
1392                         if ((ent->render.flags & RENDER_VIEWMODEL) || ent->state_current.tagentity)
1393                                 CL_UpdateNetworkEntity(ent, 32, true);
1394                 }
1395         }
1396         // and of course the engine viewmodel needs updating as well
1397         CL_UpdateNetworkEntity(&cl.viewent, 32, true);
1398 }
1399
1400 /*
1401 ===============
1402 CL_UpdateNetworkCollisionEntities
1403 ===============
1404 */
1405 static void CL_UpdateNetworkCollisionEntities(void)
1406 {
1407         entity_t *ent;
1408         int i;
1409
1410         // start on the entity after the world
1411         cl.num_brushmodel_entities = 0;
1412         for (i = cl.maxclients + 1;i < cl.num_entities;i++)
1413         {
1414                 if (cl.entities_active[i])
1415                 {
1416                         ent = cl.entities + i;
1417                         if (ent->state_current.active && ent->render.model && ent->render.model->name[0] == '*' && ent->render.model->TraceBox)
1418                         {
1419                                 // do not interpolate the bmodels for this
1420                                 CL_UpdateNetworkEntity(ent, 32, false);
1421                                 cl.brushmodel_entities[cl.num_brushmodel_entities++] = i;
1422                         }
1423                 }
1424         }
1425 }
1426
1427 /*
1428 ===============
1429 CL_UpdateNetworkEntities
1430 ===============
1431 */
1432 static void CL_UpdateNetworkEntities(void)
1433 {
1434         entity_t *ent;
1435         int i;
1436
1437         // start on the entity after the world
1438         for (i = 1;i < cl.num_entities;i++)
1439         {
1440                 if (cl.entities_active[i])
1441                 {
1442                         ent = cl.entities + i;
1443                         if (ent->state_current.active)
1444                         {
1445                                 CL_UpdateNetworkEntity(ent, 32, true);
1446                                 // view models should never create light/trails
1447                                 if (!(ent->render.flags & RENDER_VIEWMODEL))
1448                                         CL_UpdateNetworkEntityTrail(ent);
1449                         }
1450                         else
1451                         {
1452                                 R_DecalSystem_Reset(&ent->render.decalsystem);
1453                                 cl.entities_active[i] = false;
1454                         }
1455                 }
1456         }
1457 }
1458
1459 static void CL_UpdateViewModel(void)
1460 {
1461         entity_t *ent;
1462         ent = &cl.viewent;
1463         ent->state_previous = ent->state_current;
1464         ent->state_current = defaultstate;
1465         ent->state_current.time = cl.time;
1466         ent->state_current.number = (unsigned short)-1;
1467         ent->state_current.active = true;
1468         ent->state_current.modelindex = cl.stats[STAT_WEAPON];
1469         ent->state_current.frame = cl.stats[STAT_WEAPONFRAME];
1470         ent->state_current.flags = RENDER_VIEWMODEL;
1471         if ((cl.stats[STAT_HEALTH] <= 0 && cl_deathnoviewmodel.integer) || cl.intermission)
1472                 ent->state_current.modelindex = 0;
1473         else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1474         {
1475                 if (gamemode == GAME_TRANSFUSION)
1476                         ent->state_current.alpha = 128;
1477                 else
1478                         ent->state_current.modelindex = 0;
1479         }
1480         ent->state_current.alpha = cl.entities[cl.viewentity].state_current.alpha;
1481         ent->state_current.effects = EF_NOSHADOW | (cl.entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_FULLBRIGHT | EF_NODEPTHTEST | EF_NOGUNBOB));
1482
1483         // reset animation interpolation on weaponmodel if model changed
1484         if (ent->state_previous.modelindex != ent->state_current.modelindex)
1485         {
1486                 ent->render.framegroupblend[0].frame = ent->render.framegroupblend[1].frame = ent->state_current.frame;
1487                 ent->render.framegroupblend[0].start = ent->render.framegroupblend[1].start = cl.time;
1488                 ent->render.framegroupblend[0].lerp = 1;ent->render.framegroupblend[1].lerp = 0;
1489         }
1490         CL_UpdateNetworkEntity(ent, 32, true);
1491 }
1492
1493 // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags)
1494 static void CL_LinkNetworkEntity(entity_t *e)
1495 {
1496         effectnameindex_t trailtype;
1497         vec3_t origin;
1498         vec3_t dlightcolor;
1499         vec_t dlightradius;
1500         char vabuf[1024];
1501
1502         // skip inactive entities and world
1503         if (!e->state_current.active || e == cl.entities)
1504                 return;
1505         if (e->state_current.tagentity)
1506         {
1507                 // if the tag entity is currently impossible, skip it
1508                 if (e->state_current.tagentity >= cl.num_entities)
1509                         return;
1510                 // if the tag entity is inactive, skip it
1511                 if (!cl.entities[e->state_current.tagentity].state_current.active)
1512                 {
1513                         if(!cl.csqc_server2csqcentitynumber[e->state_current.tagentity])
1514                                 return;
1515                         if(!cl.csqcrenderentities[cl.csqc_server2csqcentitynumber[e->state_current.tagentity]].entitynumber)
1516                                 return;
1517                         // if we get here, it's properly csqc networked and attached
1518                 }
1519         }
1520
1521         // create entity dlights associated with this entity
1522         if (e->render.model && e->render.model->soundfromcenter)
1523         {
1524                 // bmodels are treated specially since their origin is usually '0 0 0'
1525                 vec3_t o;
1526                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1527                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1528         }
1529         else
1530                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1531         trailtype = EFFECT_NONE;
1532         dlightradius = 0;
1533         dlightcolor[0] = 0;
1534         dlightcolor[1] = 0;
1535         dlightcolor[2] = 0;
1536         // LadyHavoc: if the entity has no effects, don't check each
1537         if (e->render.effects & (EF_BRIGHTFIELD | EF_DIMLIGHT | EF_BRIGHTLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
1538         {
1539                 if (e->render.effects & EF_BRIGHTFIELD)
1540                 {
1541                         if (IS_NEXUIZ_DERIVED(gamemode))
1542                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1543                 }
1544                 if (e->render.effects & EF_DIMLIGHT)
1545                 {
1546                         dlightradius = max(dlightradius, 200);
1547                         dlightcolor[0] += 1.50f;
1548                         dlightcolor[1] += 1.50f;
1549                         dlightcolor[2] += 1.50f;
1550                 }
1551                 if (e->render.effects & EF_BRIGHTLIGHT)
1552                 {
1553                         dlightradius = max(dlightradius, 400);
1554                         dlightcolor[0] += 3.00f;
1555                         dlightcolor[1] += 3.00f;
1556                         dlightcolor[2] += 3.00f;
1557                 }
1558                 // LadyHavoc: more effects
1559                 if (e->render.effects & EF_RED) // red
1560                 {
1561                         dlightradius = max(dlightradius, 200);
1562                         dlightcolor[0] += 1.50f;
1563                         dlightcolor[1] += 0.15f;
1564                         dlightcolor[2] += 0.15f;
1565                 }
1566                 if (e->render.effects & EF_BLUE) // blue
1567                 {
1568                         dlightradius = max(dlightradius, 200);
1569                         dlightcolor[0] += 0.15f;
1570                         dlightcolor[1] += 0.15f;
1571                         dlightcolor[2] += 1.50f;
1572                 }
1573                 if (e->render.effects & EF_FLAME)
1574                         CL_ParticleTrail(EFFECT_EF_FLAME, 1, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false, NULL, NULL, 1);
1575                 if (e->render.effects & EF_STARDUST)
1576                         CL_ParticleTrail(EFFECT_EF_STARDUST, 1, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false, NULL, NULL, 1);
1577         }
1578         // muzzleflash fades over time, and is offset a bit
1579         if (e->persistent.muzzleflash > 0 && r_refdef.scene.numlights < MAX_DLIGHTS)
1580         {
1581                 vec3_t v2;
1582                 vec3_t color;
1583                 trace_t trace;
1584                 matrix4x4_t tempmatrix;
1585                 Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2);
1586                 trace = CL_TraceLine(origin, v2, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY, 0, 0, collision_extendmovelength.value, true, false, NULL, false, false);
1587                 Matrix4x4_Normalize(&tempmatrix, &e->render.matrix);
1588                 Matrix4x4_SetOrigin(&tempmatrix, trace.endpos[0], trace.endpos[1], trace.endpos[2]);
1589                 Matrix4x4_Scale(&tempmatrix, 150, 1);
1590                 VectorSet(color, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f);
1591                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &tempmatrix, color, -1, NULL, true, 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1592                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++;
1593         }
1594         // LadyHavoc: if the model has no flags, don't check each
1595         if (e->render.model && e->render.effects && !(e->render.flags & RENDER_VIEWMODEL))
1596         {
1597                 if (e->render.effects & EF_GIB)
1598                         trailtype = EFFECT_TR_BLOOD;
1599                 else if (e->render.effects & EF_ZOMGIB)
1600                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1601                 else if (e->render.effects & EF_TRACER)
1602                         trailtype = EFFECT_TR_WIZSPIKE;
1603                 else if (e->render.effects & EF_TRACER2)
1604                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1605                 else if (e->render.effects & EF_ROCKET)
1606                         trailtype = EFFECT_TR_ROCKET;
1607                 else if (e->render.effects & EF_GRENADE)
1608                 {
1609                         // LadyHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1610                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1611                 }
1612                 else if (e->render.effects & EF_TRACER3)
1613                         trailtype = EFFECT_TR_VORESPIKE;
1614         }
1615         // LadyHavoc: customizable glow
1616         if (e->state_current.glowsize)
1617         {
1618                 // * 4 for the expansion from 0-255 to 0-1023 range,
1619                 // / 255 to scale down byte colors
1620                 dlightradius = max(dlightradius, e->state_current.glowsize * 4);
1621                 VectorMA(dlightcolor, (1.0f / 255.0f), palette_rgb[e->state_current.glowcolor], dlightcolor);
1622         }
1623         // custom rtlight
1624         if ((e->state_current.lightpflags & PFLAGS_FULLDYNAMIC) && r_refdef.scene.numlights < MAX_DLIGHTS)
1625         {
1626                 matrix4x4_t dlightmatrix;
1627                 vec4_t light;
1628                 VectorScale(e->state_current.light, (1.0f / 256.0f), light);
1629                 light[3] = e->state_current.light[3];
1630                 if (light[0] == 0 && light[1] == 0 && light[2] == 0)
1631                         VectorSet(light, 1, 1, 1);
1632                 if (light[3] == 0)
1633                         light[3] = 350;
1634                 // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS?
1635                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1636                 Matrix4x4_Scale(&dlightmatrix, light[3], 1);
1637                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, light, e->state_current.lightstyle, e->state_current.skin > 0 ? va(vabuf, sizeof(vabuf), "cubemaps/%i", e->state_current.skin) : NULL, !(e->state_current.lightpflags & PFLAGS_NOSHADOW), (e->state_current.lightpflags & PFLAGS_CORONA) != 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1638                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++;
1639         }
1640         // make the glow dlight
1641         else if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL) && r_refdef.scene.numlights < MAX_DLIGHTS)
1642         {
1643                 matrix4x4_t dlightmatrix;
1644                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1645                 // hack to make glowing player light shine on their gun
1646                 //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/)
1647                 //      Matrix4x4_AdjustOrigin(&dlightmatrix, 0, 0, 30);
1648                 Matrix4x4_Scale(&dlightmatrix, dlightradius, 1);
1649                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1650                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++;
1651         }
1652         // do trail light
1653         if (e->render.flags & RENDER_GLOWTRAIL)
1654                 trailtype = EFFECT_TR_GLOWTRAIL;
1655         if (e->state_current.traileffectnum)
1656                 trailtype = (effectnameindex_t)e->state_current.traileffectnum;
1657         if (trailtype)
1658                 CL_ParticleTrail(trailtype, 1, origin, origin, vec3_origin, vec3_origin, NULL, e->state_current.glowcolor, true, false, NULL, NULL, 1);
1659
1660         // don't show entities with no modelindex (note: this still shows
1661         // entities which have a modelindex that resolved to a NULL model)
1662         if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.scene.numentities < r_refdef.scene.maxentities)
1663                 r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render;
1664         //if (cl.viewentity && e->state_current.number == cl.viewentity)
1665         //      Matrix4x4_Print(&e->render.matrix);
1666 }
1667
1668 static void CL_RelinkWorld(void)
1669 {
1670         entity_t *ent = &cl.entities[0];
1671         // FIXME: this should be done at load
1672         ent->render.matrix = identitymatrix;
1673         ent->render.flags = RENDER_SHADOW;
1674         if (!r_fullbright.integer)
1675                 ent->render.flags |= RENDER_LIGHT;
1676         VectorSet(ent->render.colormod, 1, 1, 1);
1677         VectorSet(ent->render.glowmod, 1, 1, 1);
1678         ent->render.allowdecals = true;
1679         CL_UpdateRenderEntity(&ent->render);
1680         r_refdef.scene.worldentity = &ent->render;
1681         r_refdef.scene.worldmodel = cl.worldmodel;
1682
1683         // if the world is q2bsp, animate the textures
1684         if (ent->render.model && ent->render.model->brush.isq2bsp)
1685                 ent->render.framegroupblend[0].frame = (int)(cl.time * 2.0f);
1686 }
1687
1688 static void CL_RelinkStaticEntities(void)
1689 {
1690         int i;
1691         entity_t *e;
1692         for (i = 0, e = cl.static_entities;i < cl.num_static_entities && r_refdef.scene.numentities < r_refdef.scene.maxentities;i++, e++)
1693         {
1694                 e->render.flags = 0;
1695                 // if the model was not loaded when the static entity was created we
1696                 // need to re-fetch the model pointer
1697                 e->render.model = CL_GetModelByIndex(e->state_baseline.modelindex);
1698                 // either fullbright or lit
1699                 if(!r_fullbright.integer)
1700                 {
1701                         if (!(e->render.effects & EF_FULLBRIGHT))
1702                                 e->render.flags |= RENDER_LIGHT;
1703                 }
1704                 // hide player shadow during intermission or nehahra movie
1705                 if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST)) && (e->render.alpha >= 1))
1706                         e->render.flags |= RENDER_SHADOW;
1707                 VectorSet(e->render.colormod, 1, 1, 1);
1708                 VectorSet(e->render.glowmod, 1, 1, 1);
1709                 VM_FrameBlendFromFrameGroupBlend(e->render.frameblend, e->render.framegroupblend, e->render.model, cl.time);
1710                 e->render.allowdecals = true;
1711                 CL_UpdateRenderEntity(&e->render);
1712                 r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render;
1713         }
1714 }
1715
1716 /*
1717 ===============
1718 CL_RelinkEntities
1719 ===============
1720 */
1721 static void CL_RelinkNetworkEntities(void)
1722 {
1723         entity_t *ent;
1724         int i;
1725
1726         // start on the entity after the world
1727         for (i = 1;i < cl.num_entities;i++)
1728         {
1729                 if (cl.entities_active[i])
1730                 {
1731                         ent = cl.entities + i;
1732                         if (ent->state_current.active)
1733                                 CL_LinkNetworkEntity(ent);
1734                         else
1735                                 cl.entities_active[i] = false;
1736                 }
1737         }
1738 }
1739
1740 static void CL_RelinkEffects(void)
1741 {
1742         int i, intframe;
1743         cl_effect_t *e;
1744         entity_render_t *entrender;
1745         float frame;
1746
1747         for (i = 0, e = cl.effects;i < cl.num_effects;i++, e++)
1748         {
1749                 if (e->active)
1750                 {
1751                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
1752                         intframe = (int)frame;
1753                         if (intframe < 0 || intframe >= e->endframe)
1754                         {
1755                                 memset(e, 0, sizeof(*e));
1756                                 while (cl.num_effects > 0 && !cl.effects[cl.num_effects - 1].active)
1757                                         cl.num_effects--;
1758                                 continue;
1759                         }
1760
1761                         if (intframe != e->frame)
1762                         {
1763                                 e->frame = intframe;
1764                                 e->frame1time = e->frame2time;
1765                                 e->frame2time = cl.time;
1766                         }
1767
1768                         // if we're drawing effects, get a new temp entity
1769                         // (NewTempEntity adds it to the render entities list for us)
1770                         if (r_draweffects.integer && (entrender = CL_NewTempEntity(e->starttime)))
1771                         {
1772                                 // interpolation stuff
1773                                 entrender->framegroupblend[0].frame = intframe;
1774                                 entrender->framegroupblend[0].lerp = 1 - frame - intframe;
1775                                 entrender->framegroupblend[0].start = e->frame1time;
1776                                 if (intframe + 1 >= e->endframe)
1777                                 {
1778                                         entrender->framegroupblend[1].frame = 0; // disappear
1779                                         entrender->framegroupblend[1].lerp = 0;
1780                                         entrender->framegroupblend[1].start = 0;
1781                                 }
1782                                 else
1783                                 {
1784                                         entrender->framegroupblend[1].frame = intframe + 1;
1785                                         entrender->framegroupblend[1].lerp = frame - intframe;
1786                                         entrender->framegroupblend[1].start = e->frame2time;
1787                                 }
1788
1789                                 // normal stuff
1790                                 entrender->model = e->model;
1791                                 entrender->alpha = 1;
1792                                 VectorSet(entrender->colormod, 1, 1, 1);
1793                                 VectorSet(entrender->glowmod, 1, 1, 1);
1794
1795                                 Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
1796                                 CL_UpdateRenderEntity(entrender);
1797                         }
1798                 }
1799         }
1800 }
1801
1802 void CL_Beam_CalculatePositions(const beam_t *b, vec3_t start, vec3_t end)
1803 {
1804         VectorCopy(b->start, start);
1805         VectorCopy(b->end, end);
1806
1807         // if coming from the player, update the start position
1808         if (b->entity == cl.viewentity)
1809         {
1810                 if (cl_beams_quakepositionhack.integer && !chase_active.integer)
1811                 {
1812                         // LadyHavoc: this is a stupid hack from Quake that makes your
1813                         // lightning appear to come from your waist and cover less of your
1814                         // view
1815                         // in Quake this hack was applied to all players (causing the
1816                         // infamous crotch-lightning), but in darkplaces and QuakeWorld it
1817                         // only applies to your own lightning, and only in first person
1818                         Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, start);
1819                 }
1820                 if (cl_beams_instantaimhack.integer)
1821                 {
1822                         vec3_t dir, localend;
1823                         vec_t len;
1824                         // LadyHavoc: this updates the beam direction to match your
1825                         // viewangles
1826                         VectorSubtract(end, start, dir);
1827                         len = VectorLength(dir);
1828                         VectorNormalize(dir);
1829                         VectorSet(localend, len, 0, 0);
1830                         Matrix4x4_Transform(&r_refdef.view.matrix, localend, end);
1831                 }
1832         }
1833 }
1834
1835 void CL_RelinkBeams(void)
1836 {
1837         int i;
1838         beam_t *b;
1839         vec3_t dist, org, start, end;
1840         float d;
1841         entity_render_t *entrender;
1842         double yaw, pitch;
1843         float forward;
1844         matrix4x4_t tempmatrix;
1845
1846         for (i = 0, b = cl.beams;i < cl.num_beams;i++, b++)
1847         {
1848                 if (!b->model)
1849                         continue;
1850                 if (b->endtime < cl.time)
1851                 {
1852                         b->model = NULL;
1853                         continue;
1854                 }
1855
1856                 CL_Beam_CalculatePositions(b, start, end);
1857
1858                 if (b->lightning)
1859                 {
1860                         if (cl_beams_lightatend.integer && r_refdef.scene.numlights < MAX_DLIGHTS)
1861                         {
1862                                 // FIXME: create a matrix from the beam start/end orientation
1863                                 vec3_t dlightcolor;
1864                                 VectorSet(dlightcolor, 0.3, 0.7, 1);
1865                                 Matrix4x4_CreateFromQuakeEntity(&tempmatrix, end[0], end[1], end[2], 0, 0, 0, 200);
1866                                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &tempmatrix, dlightcolor, -1, NULL, true, 1, 0.25, 1, 0, 0, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1867                                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights];r_refdef.scene.numlights++;
1868                         }
1869                         if (cl_beams_polygons.integer)
1870                         {
1871                                 CL_Beam_AddPolygons(b);
1872                                 continue;
1873                         }
1874                 }
1875
1876                 // calculate pitch and yaw
1877                 // (this is similar to the QuakeC builtin function vectoangles)
1878                 VectorSubtract(end, start, dist);
1879                 if (dist[1] == 0 && dist[0] == 0)
1880                 {
1881                         yaw = 0;
1882                         if (dist[2] > 0)
1883                                 pitch = 90;
1884                         else
1885                                 pitch = 270;
1886                 }
1887                 else
1888                 {
1889                         yaw = atan2(dist[1], dist[0]) * 180 / M_PI;
1890                         if (yaw < 0)
1891                                 yaw += 360;
1892
1893                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
1894                         pitch = atan2(dist[2], forward) * 180 / M_PI;
1895                         if (pitch < 0)
1896                                 pitch += 360;
1897                 }
1898
1899                 // add new entities for the lightning
1900                 VectorCopy (start, org);
1901                 d = VectorNormalizeLength(dist);
1902                 while (d > 0)
1903                 {
1904                         entrender = CL_NewTempEntity (0);
1905                         if (!entrender)
1906                                 return;
1907                         entrender->model = b->model;
1908                         Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1909                         CL_UpdateRenderEntity(entrender);
1910                         VectorMA(org, 30, dist, org);
1911                         d -= 30;
1912                 }
1913         }
1914
1915         while (cl.num_beams > 0 && !cl.beams[cl.num_beams - 1].model)
1916                 cl.num_beams--;
1917 }
1918
1919 static void CL_RelinkQWNails(void)
1920 {
1921         int i;
1922         vec_t *v;
1923         entity_render_t *entrender;
1924
1925         for (i = 0;i < cl.qw_num_nails;i++)
1926         {
1927                 v = cl.qw_nails[i];
1928
1929                 // if we're drawing effects, get a new temp entity
1930                 // (NewTempEntity adds it to the render entities list for us)
1931                 if (!(entrender = CL_NewTempEntity(0)))
1932                         continue;
1933
1934                 // normal stuff
1935                 entrender->model = CL_GetModelByIndex(cl.qw_modelindex_spike);
1936                 entrender->alpha = 1;
1937                 VectorSet(entrender->colormod, 1, 1, 1);
1938                 VectorSet(entrender->glowmod, 1, 1, 1);
1939
1940                 Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, v[0], v[1], v[2], v[3], v[4], v[5], 1);
1941                 CL_UpdateRenderEntity(entrender);
1942         }
1943 }
1944
1945 static void CL_LerpPlayer(float frac)
1946 {
1947         int i;
1948
1949         cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]);
1950         for (i = 0;i < 3;i++)
1951         {
1952                 cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]);
1953                 cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]);
1954                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1955         }
1956
1957         // interpolate the angles if playing a demo or spectating someone
1958         if (cls.demoplayback || cl.fixangle[0])
1959         {
1960                 for (i = 0;i < 3;i++)
1961                 {
1962                         float d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1963                         if (d > 180)
1964                                 d -= 360;
1965                         else if (d < -180)
1966                                 d += 360;
1967                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1968                 }
1969         }
1970 }
1971
1972 void CSQC_RelinkAllEntities (int drawmask)
1973 {
1974         // link stuff
1975         CL_RelinkWorld();
1976         // the scene mesh is added first for easier debugging (consistent spot in render entities list)
1977         CL_MeshEntities_Scene_AddRenderEntity();
1978         CL_RelinkStaticEntities();
1979         CL_RelinkBeams();
1980         CL_RelinkEffects();
1981         CL_RelinkLightFlashes();
1982
1983         // link stuff
1984         if (drawmask & ENTMASK_ENGINE)
1985         {
1986                 CL_RelinkNetworkEntities();
1987                 if (drawmask & ENTMASK_ENGINEVIEWMODELS)
1988                         CL_LinkNetworkEntity(&cl.viewent); // link gun model
1989                 CL_RelinkQWNails();
1990         }
1991
1992         // update view blend
1993         V_CalcViewBlend();
1994 }
1995
1996 /*
1997 ===============
1998 CL_UpdateWorld
1999
2000 Update client game world for a new frame
2001 ===============
2002 */
2003 void CL_UpdateWorld(void)
2004 {
2005         r_refdef.scene.extraupdate = !r_speeds.integer;
2006         r_refdef.scene.numentities = 0;
2007         r_refdef.scene.numlights = 0;
2008         r_refdef.view.matrix = identitymatrix;
2009         r_refdef.view.quality = 1;
2010                 
2011         cl.num_brushmodel_entities = 0;
2012
2013         if (cls.state == ca_connected && cls.signon == SIGNONS)
2014         {
2015                 // prepare for a new frame
2016                 CL_LerpPlayer(CL_LerpPoint());
2017                 CL_DecayLightFlashes();
2018                 CL_ClearTempEntities();
2019                 V_DriftPitch();
2020                 V_FadeViewFlashs();
2021
2022                 // if prediction is enabled we have to update all the collidable
2023                 // network entities before the prediction code can be run
2024                 CL_UpdateNetworkCollisionEntities();
2025
2026                 // now update the player prediction
2027                 CL_ClientMovement_Replay();
2028
2029                 // update the player entity (which may be predicted)
2030                 CL_UpdateNetworkEntity(cl.entities + cl.viewentity, 32, true);
2031
2032                 // now update the view (which depends on that player entity)
2033                 V_CalcRefdef();
2034
2035                 // now update all the network entities and create particle trails
2036                 // (some entities may depend on the view)
2037                 CL_UpdateNetworkEntities();
2038
2039                 // update the engine-based viewmodel
2040                 CL_UpdateViewModel();
2041
2042                 // when csqc is loaded, it will call this in CSQC_UpdateView
2043                 if (!cl.csqc_loaded)
2044                 {
2045                         // clear the CL_Mesh_Scene() used for some engine effects
2046                         CL_MeshEntities_Scene_Clear();
2047                         // add engine entities and effects
2048                         CSQC_RelinkAllEntities(ENTMASK_ENGINE | ENTMASK_ENGINEVIEWMODELS);
2049                 }
2050
2051                 // decals, particles, and explosions will be updated during rneder
2052         }
2053
2054         r_refdef.scene.time = cl.time;
2055 }
2056
2057 /*
2058 ======================
2059 CL_Fog_f
2060 ======================
2061 */
2062 static void CL_Fog_f(cmd_state_t *cmd)
2063 {
2064         if (Cmd_Argc (cmd) == 1)
2065         {
2066                 Con_Printf("\"fog\" is \"%f %f %f %f %f %f %f %f %f\"\n", 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);
2067                 return;
2068         }
2069         FOG_clear(); // so missing values get good defaults
2070         if(Cmd_Argc(cmd) > 1)
2071                 r_refdef.fog_density = atof(Cmd_Argv(cmd, 1));
2072         if(Cmd_Argc(cmd) > 2)
2073                 r_refdef.fog_red = atof(Cmd_Argv(cmd, 2));
2074         if(Cmd_Argc(cmd) > 3)
2075                 r_refdef.fog_green = atof(Cmd_Argv(cmd, 3));
2076         if(Cmd_Argc(cmd) > 4)
2077                 r_refdef.fog_blue = atof(Cmd_Argv(cmd, 4));
2078         if(Cmd_Argc(cmd) > 5)
2079                 r_refdef.fog_alpha = atof(Cmd_Argv(cmd, 5));
2080         if(Cmd_Argc(cmd) > 6)
2081                 r_refdef.fog_start = atof(Cmd_Argv(cmd, 6));
2082         if(Cmd_Argc(cmd) > 7)
2083                 r_refdef.fog_end = atof(Cmd_Argv(cmd, 7));
2084         if(Cmd_Argc(cmd) > 8)
2085                 r_refdef.fog_height = atof(Cmd_Argv(cmd, 8));
2086         if(Cmd_Argc(cmd) > 9)
2087                 r_refdef.fog_fadedepth = atof(Cmd_Argv(cmd, 9));
2088 }
2089
2090 /*
2091 ======================
2092 CL_FogHeightTexture_f
2093 ======================
2094 */
2095 static void CL_Fog_HeightTexture_f(cmd_state_t *cmd)
2096 {
2097         if (Cmd_Argc (cmd) < 11)
2098         {
2099                 Con_Printf("\"fog_heighttexture\" is \"%f %f %f %f %f %f %f %f %f %s\"\n", 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);
2100                 return;
2101         }
2102         FOG_clear(); // so missing values get good defaults
2103         r_refdef.fog_density = atof(Cmd_Argv(cmd, 1));
2104         r_refdef.fog_red = atof(Cmd_Argv(cmd, 2));
2105         r_refdef.fog_green = atof(Cmd_Argv(cmd, 3));
2106         r_refdef.fog_blue = atof(Cmd_Argv(cmd, 4));
2107         r_refdef.fog_alpha = atof(Cmd_Argv(cmd, 5));
2108         r_refdef.fog_start = atof(Cmd_Argv(cmd, 6));
2109         r_refdef.fog_end = atof(Cmd_Argv(cmd, 7));
2110         r_refdef.fog_height = atof(Cmd_Argv(cmd, 8));
2111         r_refdef.fog_fadedepth = atof(Cmd_Argv(cmd, 9));
2112         strlcpy(r_refdef.fog_height_texturename, Cmd_Argv(cmd, 10), sizeof(r_refdef.fog_height_texturename));
2113 }
2114
2115
2116 /*
2117 ====================
2118 CL_TimeRefresh_f
2119
2120 For program optimization
2121 ====================
2122 */
2123 static void CL_TimeRefresh_f(cmd_state_t *cmd)
2124 {
2125         int i;
2126         double timestart, timedelta;
2127
2128         r_refdef.scene.extraupdate = false;
2129
2130         timestart = Sys_DirtyTime();
2131         for (i = 0;i < 128;i++)
2132         {
2133                 Matrix4x4_CreateFromQuakeEntity(&r_refdef.view.matrix, r_refdef.view.origin[0], r_refdef.view.origin[1], r_refdef.view.origin[2], 0, i / 128.0 * 360.0, 0, 1);
2134                 r_refdef.view.quality = 1;
2135                 CL_UpdateScreen();
2136         }
2137         timedelta = Sys_DirtyTime() - timestart;
2138
2139         Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta);
2140 }
2141
2142 static void CL_AreaStats_f(cmd_state_t *cmd)
2143 {
2144         World_PrintAreaStats(&cl.world, "client");
2145 }
2146
2147 cl_locnode_t *CL_Locs_FindNearest(const vec3_t point)
2148 {
2149         int i;
2150         cl_locnode_t *loc;
2151         cl_locnode_t *best;
2152         vec3_t nearestpoint;
2153         vec_t dist, bestdist;
2154         best = NULL;
2155         bestdist = 0;
2156         for (loc = cl.locnodes;loc;loc = loc->next)
2157         {
2158                 for (i = 0;i < 3;i++)
2159                         nearestpoint[i] = bound(loc->mins[i], point[i], loc->maxs[i]);
2160                 dist = VectorDistance2(nearestpoint, point);
2161                 if (bestdist > dist || !best)
2162                 {
2163                         bestdist = dist;
2164                         best = loc;
2165                         if (bestdist < 1)
2166                                 break;
2167                 }
2168         }
2169         return best;
2170 }
2171
2172 void CL_Locs_FindLocationName(char *buffer, size_t buffersize, vec3_t point)
2173 {
2174         cl_locnode_t *loc;
2175         loc = CL_Locs_FindNearest(point);
2176         if (loc)
2177                 strlcpy(buffer, loc->name, buffersize);
2178         else
2179                 dpsnprintf(buffer, buffersize, "LOC=%.0f:%.0f:%.0f", point[0], point[1], point[2]);
2180 }
2181
2182 static void CL_Locs_FreeNode(cl_locnode_t *node)
2183 {
2184         cl_locnode_t **pointer, **next;
2185         for (pointer = &cl.locnodes;*pointer;pointer = next)
2186         {
2187                 next = &(*pointer)->next;
2188                 if (*pointer == node)
2189                 {
2190                         *pointer = node->next;
2191                         Mem_Free(node);
2192                         return;
2193                 }
2194         }
2195         Con_Printf("CL_Locs_FreeNode: no such node! (%p)\n", (void *)node);
2196 }
2197
2198 static void CL_Locs_AddNode(vec3_t mins, vec3_t maxs, const char *name)
2199 {
2200         cl_locnode_t *node, **pointer;
2201         int namelen;
2202         if (!name)
2203                 name = "";
2204         namelen = (int)strlen(name);
2205         node = (cl_locnode_t *) Mem_Alloc(cls.levelmempool, sizeof(cl_locnode_t) + namelen + 1);
2206         VectorSet(node->mins, min(mins[0], maxs[0]), min(mins[1], maxs[1]), min(mins[2], maxs[2]));
2207         VectorSet(node->maxs, max(mins[0], maxs[0]), max(mins[1], maxs[1]), max(mins[2], maxs[2]));
2208         node->name = (char *)(node + 1);
2209         memcpy(node->name, name, namelen);
2210         node->name[namelen] = 0;
2211         // link it into the tail of the list to preserve the order
2212         for (pointer = &cl.locnodes;*pointer;pointer = &(*pointer)->next)
2213                 ;
2214         *pointer = node;
2215 }
2216
2217 static void CL_Locs_Add_f(cmd_state_t *cmd)
2218 {
2219         vec3_t mins, maxs;
2220         if (Cmd_Argc(cmd) != 5 && Cmd_Argc(cmd) != 8)
2221         {
2222                 Con_Printf("usage: %s x y z[ x y z] name\n", Cmd_Argv(cmd, 0));
2223                 return;
2224         }
2225         mins[0] = atof(Cmd_Argv(cmd, 1));
2226         mins[1] = atof(Cmd_Argv(cmd, 2));
2227         mins[2] = atof(Cmd_Argv(cmd, 3));
2228         if (Cmd_Argc(cmd) == 8)
2229         {
2230                 maxs[0] = atof(Cmd_Argv(cmd, 4));
2231                 maxs[1] = atof(Cmd_Argv(cmd, 5));
2232                 maxs[2] = atof(Cmd_Argv(cmd, 6));
2233                 CL_Locs_AddNode(mins, maxs, Cmd_Argv(cmd, 7));
2234         }
2235         else
2236                 CL_Locs_AddNode(mins, mins, Cmd_Argv(cmd, 4));
2237 }
2238
2239 static void CL_Locs_RemoveNearest_f(cmd_state_t *cmd)
2240 {
2241         cl_locnode_t *loc;
2242         loc = CL_Locs_FindNearest(r_refdef.view.origin);
2243         if (loc)
2244                 CL_Locs_FreeNode(loc);
2245         else
2246                 Con_Printf("no loc point or box found for your location\n");
2247 }
2248
2249 static void CL_Locs_Clear_f(cmd_state_t *cmd)
2250 {
2251         while (cl.locnodes)
2252                 CL_Locs_FreeNode(cl.locnodes);
2253 }
2254
2255 static void CL_Locs_Save_f(cmd_state_t *cmd)
2256 {
2257         cl_locnode_t *loc;
2258         qfile_t *outfile;
2259         char locfilename[MAX_QPATH];
2260         if (!cl.locnodes)
2261         {
2262                 Con_Printf("No loc points/boxes exist!\n");
2263                 return;
2264         }
2265         if (cls.state != ca_connected || !cl.worldmodel)
2266         {
2267                 Con_Printf("No level loaded!\n");
2268                 return;
2269         }
2270         dpsnprintf(locfilename, sizeof(locfilename), "%s.loc", cl.worldnamenoextension);
2271
2272         outfile = FS_OpenRealFile(locfilename, "w", false);
2273         if (!outfile)
2274                 return;
2275         // if any boxes are used then this is a proquake-format loc file, which
2276         // allows comments, so add some relevant information at the start
2277         for (loc = cl.locnodes;loc;loc = loc->next)
2278                 if (!VectorCompare(loc->mins, loc->maxs))
2279                         break;
2280         if (loc)
2281         {
2282                 FS_Printf(outfile, "// %s %s saved by %s\n// x,y,z,x,y,z,\"name\"\n\n", locfilename, Sys_TimeString("%Y-%m-%d"), engineversion);
2283                 for (loc = cl.locnodes;loc;loc = loc->next)
2284                         if (VectorCompare(loc->mins, loc->maxs))
2285                                 break;
2286                 if (loc)
2287                         Con_Printf(CON_WARN "Warning: writing loc file containing a mixture of qizmo-style points and proquake-style boxes may not work in qizmo or proquake!\n");
2288         }
2289         for (loc = cl.locnodes;loc;loc = loc->next)
2290         {
2291                 if (VectorCompare(loc->mins, loc->maxs))
2292                 {
2293                         int len;
2294                         const char *s;
2295                         const char *in = loc->name;
2296                         char name[MAX_INPUTLINE];
2297                         for (len = 0;len < (int)sizeof(name) - 1 && *in;)
2298                         {
2299                                 if (*in == ' ') {s = "$loc_name_separator";in++;}
2300                                 else if (!strncmp(in, "SSG", 3)) {s = "$loc_name_ssg";in += 3;}
2301                                 else if (!strncmp(in, "NG", 2)) {s = "$loc_name_ng";in += 2;}
2302                                 else if (!strncmp(in, "SNG", 3)) {s = "$loc_name_sng";in += 3;}
2303                                 else if (!strncmp(in, "GL", 2)) {s = "$loc_name_gl";in += 2;}
2304                                 else if (!strncmp(in, "RL", 2)) {s = "$loc_name_rl";in += 2;}
2305                                 else if (!strncmp(in, "LG", 2)) {s = "$loc_name_lg";in += 2;}
2306                                 else if (!strncmp(in, "GA", 2)) {s = "$loc_name_ga";in += 2;}
2307                                 else if (!strncmp(in, "YA", 2)) {s = "$loc_name_ya";in += 2;}
2308                                 else if (!strncmp(in, "RA", 2)) {s = "$loc_name_ra";in += 2;}
2309                                 else if (!strncmp(in, "MEGA", 4)) {s = "$loc_name_mh";in += 4;}
2310                                 else s = NULL;
2311                                 if (s)
2312                                 {
2313                                         while (len < (int)sizeof(name) - 1 && *s)
2314                                                 name[len++] = *s++;
2315                                         continue;
2316                                 }
2317                                 name[len++] = *in++;
2318                         }
2319                         name[len] = 0;
2320                         FS_Printf(outfile, "%.0f %.0f %.0f %s\n", loc->mins[0]*8, loc->mins[1]*8, loc->mins[2]*8, name);
2321                 }
2322                 else
2323                         FS_Printf(outfile, "%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,\"%s\"\n", loc->mins[0], loc->mins[1], loc->mins[2], loc->maxs[0], loc->maxs[1], loc->maxs[2], loc->name);
2324         }
2325         FS_Close(outfile);
2326 }
2327
2328 void CL_Locs_Reload_f(cmd_state_t *cmd)
2329 {
2330         int i, linenumber, limit, len;
2331         const char *s;
2332         char *filedata, *text, *textend, *linestart, *linetext, *lineend;
2333         fs_offset_t filesize;
2334         vec3_t mins, maxs;
2335         char locfilename[MAX_QPATH];
2336         char name[MAX_INPUTLINE];
2337
2338         if (cls.state != ca_connected || !cl.worldmodel)
2339         {
2340                 Con_Printf("No level loaded!\n");
2341                 return;
2342         }
2343
2344         CL_Locs_Clear_f(cmd);
2345
2346         // try maps/something.loc first (LadyHavoc: where I think they should be)
2347         dpsnprintf(locfilename, sizeof(locfilename), "%s.loc", cl.worldnamenoextension);
2348         filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize);
2349         if (!filedata)
2350         {
2351                 // try proquake name as well (LadyHavoc: I hate path mangling)
2352                 dpsnprintf(locfilename, sizeof(locfilename), "locs/%s.loc", cl.worldbasename);
2353                 filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize);
2354                 if (!filedata)
2355                         return;
2356         }
2357         text = filedata;
2358         textend = filedata + filesize;
2359         for (linenumber = 1;text < textend;linenumber++)
2360         {
2361                 linestart = text;
2362                 for (;text < textend && *text != '\r' && *text != '\n';text++)
2363                         ;
2364                 lineend = text;
2365                 if (text + 1 < textend && *text == '\r' && text[1] == '\n')
2366                         text++;
2367                 if (text < textend)
2368                         text++;
2369                 // trim trailing whitespace
2370                 while (lineend > linestart && ISWHITESPACE(lineend[-1]))
2371                         lineend--;
2372                 // trim leading whitespace
2373                 while (linestart < lineend && ISWHITESPACE(*linestart))
2374                         linestart++;
2375                 // check if this is a comment
2376                 if (linestart + 2 <= lineend && !strncmp(linestart, "//", 2))
2377                         continue;
2378                 linetext = linestart;
2379                 limit = 3;
2380                 for (i = 0;i < limit;i++)
2381                 {
2382                         if (linetext >= lineend)
2383                                 break;
2384                         // note: a missing number is interpreted as 0
2385                         if (i < 3)
2386                                 mins[i] = atof(linetext);
2387                         else
2388                                 maxs[i - 3] = atof(linetext);
2389                         // now advance past the number
2390                         while (linetext < lineend && !ISWHITESPACE(*linetext) && *linetext != ',')
2391                                 linetext++;
2392                         // advance through whitespace
2393                         if (linetext < lineend)
2394                         {
2395                                 if (*linetext == ',')
2396                                 {
2397                                         linetext++;
2398                                         limit = 6;
2399                                         // note: comma can be followed by whitespace
2400                                 }
2401                                 if (ISWHITESPACE(*linetext))
2402                                 {
2403                                         // skip whitespace
2404                                         while (linetext < lineend && ISWHITESPACE(*linetext))
2405                                                 linetext++;
2406                                 }
2407                         }
2408                 }
2409                 // if this is a quoted name, remove the quotes
2410                 if (i == 6)
2411                 {
2412                         if (linetext >= lineend || *linetext != '"')
2413                                 continue; // proquake location names are always quoted
2414                         lineend--;
2415                         linetext++;
2416                         len = min(lineend - linetext, (int)sizeof(name) - 1);
2417                         memcpy(name, linetext, len);
2418                         name[len] = 0;
2419                         // add the box to the list
2420                         CL_Locs_AddNode(mins, maxs, name);
2421                 }
2422                 // if a point was parsed, it needs to be scaled down by 8 (since
2423                 // point-based loc files were invented by a proxy which dealt
2424                 // directly with quake protocol coordinates, which are *8), turn
2425                 // it into a box
2426                 else if (i == 3)
2427                 {
2428                         // interpret silly fuhquake macros
2429                         for (len = 0;len < (int)sizeof(name) - 1 && linetext < lineend;)
2430                         {
2431                                 if (*linetext == '$')
2432                                 {
2433                                         if (linetext + 18 <= lineend && !strncmp(linetext, "$loc_name_separator", 19)) {s = " ";linetext += 19;}
2434                                         else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_ssg", 13)) {s = "SSG";linetext += 13;}
2435                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ng", 12)) {s = "NG";linetext += 12;}
2436                                         else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_sng", 13)) {s = "SNG";linetext += 13;}
2437                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_gl", 12)) {s = "GL";linetext += 12;}
2438                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_rl", 12)) {s = "RL";linetext += 12;}
2439                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_lg", 12)) {s = "LG";linetext += 12;}
2440                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ga", 12)) {s = "GA";linetext += 12;}
2441                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ya", 12)) {s = "YA";linetext += 12;}
2442                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ra", 12)) {s = "RA";linetext += 12;}
2443                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_mh", 12)) {s = "MEGA";linetext += 12;}
2444                                         else s = NULL;
2445                                         if (s)
2446                                         {
2447                                                 while (len < (int)sizeof(name) - 1 && *s)
2448                                                         name[len++] = *s++;
2449                                                 continue;
2450                                         }
2451                                 }
2452                                 name[len++] = *linetext++;
2453                         }
2454                         name[len] = 0;
2455                         // add the point to the list
2456                         VectorScale(mins, (1.0 / 8.0), mins);
2457                         CL_Locs_AddNode(mins, mins, name);
2458                 }
2459                 else
2460                         continue;
2461         }
2462 }
2463
2464 entity_t cl_meshentities[NUM_MESHENTITIES];
2465 dp_model_t cl_meshentitymodels[NUM_MESHENTITIES];
2466 const char *cl_meshentitynames[NUM_MESHENTITIES] =
2467 {
2468         "MESH_SCENE",
2469         "MESH_UI",
2470 };
2471
2472 static void CL_MeshEntities_Restart(void)
2473 {
2474         int i;
2475         entity_t *ent;
2476         for (i = 0; i < NUM_MESHENTITIES; i++)
2477         {
2478                 ent = cl_meshentities + i;
2479                 Mod_Mesh_Create(ent->render.model, cl_meshentitynames[i]);
2480         }
2481 }
2482
2483 static void CL_MeshEntities_Init(void)
2484 {
2485         int i;
2486         entity_t *ent;
2487         for (i = 0; i < NUM_MESHENTITIES; i++)
2488         {
2489                 ent = cl_meshentities + i;
2490                 ent->state_current.active = true;
2491                 ent->render.model = cl_meshentitymodels + i;
2492                 Mod_Mesh_Create(ent->render.model, cl_meshentitynames[i]);      
2493                 ent->render.alpha = 1;
2494                 ent->render.flags = RENDER_SHADOW | RENDER_LIGHT;
2495                 ent->render.framegroupblend[0].lerp = 1;
2496                 ent->render.frameblend[0].lerp = 1;
2497                 VectorSet(ent->render.colormod, 1, 1, 1);
2498                 VectorSet(ent->render.glowmod, 1, 1, 1);
2499                 VectorSet(ent->render.custommodellight_ambient, 1, 1, 1);
2500                 VectorSet(ent->render.custommodellight_diffuse, 0, 0, 0);
2501                 VectorSet(ent->render.custommodellight_lightdir, 0, 0, 1);
2502                 VectorSet(ent->render.render_fullbright, 1, 1, 1);
2503                 VectorSet(ent->render.render_glowmod, 0, 0, 0);
2504                 VectorSet(ent->render.render_modellight_ambient, 1, 1, 1);
2505                 VectorSet(ent->render.render_modellight_diffuse, 0, 0, 0);
2506                 VectorSet(ent->render.render_modellight_specular, 0, 0, 0);
2507                 VectorSet(ent->render.render_modellight_lightdir_world, 0, 0, 1);
2508                 VectorSet(ent->render.render_modellight_lightdir_local, 0, 0, 1); // local doesn't matter because no diffuse/specular color
2509                 VectorSet(ent->render.render_lightmap_ambient, 0, 0, 0);
2510                 VectorSet(ent->render.render_lightmap_diffuse, 1, 1, 1);
2511                 VectorSet(ent->render.render_lightmap_specular, 1, 1, 1);
2512                 VectorSet(ent->render.render_rtlight_diffuse, 1, 1, 1);
2513                 VectorSet(ent->render.render_rtlight_specular, 1, 1, 1);
2514
2515                 Matrix4x4_CreateIdentity(&ent->render.matrix);
2516                 CL_UpdateRenderEntity(&ent->render);
2517         }
2518         cl_meshentities[MESH_UI].render.flags = RENDER_NOSELFSHADOW;
2519         R_RegisterModule("cl_meshentities", CL_MeshEntities_Restart, CL_MeshEntities_Restart, CL_MeshEntities_Restart, CL_MeshEntities_Restart, CL_MeshEntities_Restart);
2520 }
2521
2522 void CL_MeshEntities_Scene_Clear(void)
2523 {
2524         Mod_Mesh_Reset(CL_Mesh_Scene());
2525 }
2526
2527 void CL_MeshEntities_Scene_AddRenderEntity(void)
2528 {
2529         entity_t* ent = &cl_meshentities[MESH_SCENE];
2530         r_refdef.scene.entities[r_refdef.scene.numentities++] = &ent->render;
2531 }
2532
2533 void CL_MeshEntities_Scene_FinalizeRenderEntity(void)
2534 {
2535         entity_t *ent = &cl_meshentities[MESH_SCENE];
2536         Mod_Mesh_Finalize(ent->render.model);
2537         VectorCopy(ent->render.model->normalmins, ent->render.mins);
2538         VectorCopy(ent->render.model->normalmaxs, ent->render.maxs);
2539 }
2540
2541 static void CL_MeshEntities_Shutdown(void)
2542 {
2543 }
2544
2545 extern cvar_t r_overheadsprites_pushback;
2546 extern cvar_t r_fullbright_directed_pitch_relative;
2547 extern cvar_t r_fullbright_directed_pitch;
2548 extern cvar_t r_fullbright_directed_ambient;
2549 extern cvar_t r_fullbright_directed_diffuse;
2550 extern cvar_t r_fullbright_directed;
2551 extern cvar_t r_hdr_glowintensity;
2552
2553 static void CL_UpdateEntityShading_GetDirectedFullbright(vec3_t ambient, vec3_t diffuse, vec3_t worldspacenormal)
2554 {
2555         vec3_t angles;
2556
2557         VectorSet(ambient, r_fullbright_directed_ambient.value, r_fullbright_directed_ambient.value, r_fullbright_directed_ambient.value);
2558         VectorSet(diffuse, r_fullbright_directed_diffuse.value, r_fullbright_directed_diffuse.value, r_fullbright_directed_diffuse.value);
2559
2560         // Use cl.viewangles and not r_refdef.view.forward here so it is the
2561         // same for all stereo views, and to better handle pitches outside
2562         // [-90, 90] (in_pitch_* cvars allow that).
2563         VectorCopy(cl.viewangles, angles);
2564         if (r_fullbright_directed_pitch_relative.integer) {
2565                 angles[PITCH] += r_fullbright_directed_pitch.value;
2566         }
2567         else {
2568                 angles[PITCH] = r_fullbright_directed_pitch.value;
2569         }
2570         AngleVectors(angles, worldspacenormal, NULL, NULL);
2571         VectorNegate(worldspacenormal, worldspacenormal);
2572 }
2573
2574 static void CL_UpdateEntityShading_Entity(entity_render_t *ent)
2575 {
2576         float shadingorigin[3], a[3], c[3], dir[3];
2577         int q;
2578
2579         for (q = 0; q < 3; q++)
2580                 a[q] = c[q] = dir[q] = 0;
2581
2582         ent->render_lightgrid = false;
2583         ent->render_modellight_forced = false;
2584         ent->render_rtlight_disabled = false;
2585
2586         // pick an appropriate value for render_modellight_origin - if this is an
2587         // attachment we want to use the parent's render_modellight_origin so that
2588         // shading is the same (also important for r_shadows to cast shadows in the
2589         // same direction)
2590         if (VectorLength2(ent->custommodellight_origin))
2591         {
2592                 // CSQC entities always provide this (via CL_GetTagMatrix)
2593                 for (q = 0; q < 3; q++)
2594                         shadingorigin[q] = ent->custommodellight_origin[q];
2595         }
2596         else if (ent->entitynumber > 0 && ent->entitynumber < cl.num_entities)
2597         {
2598                 // network entity - follow attachment chain back to a root entity,
2599                 int entnum = ent->entitynumber, recursion;
2600                 for (recursion = 32; recursion > 0; --recursion)
2601                 {
2602                         int parentnum = cl.entities[entnum].state_current.tagentity;
2603                         if (parentnum < 1 || parentnum >= cl.num_entities || !cl.entities_active[parentnum])
2604                                 break;
2605                         entnum = parentnum;
2606                 }
2607                 // grab the root entity's origin
2608                 Matrix4x4_OriginFromMatrix(&cl.entities[entnum].render.matrix, shadingorigin);
2609         }
2610         else
2611         {
2612                 // not a CSQC entity (which sets custommodellight_origin), not a network
2613                 // entity - so it's probably not attached to anything
2614                 Matrix4x4_OriginFromMatrix(&ent->matrix, shadingorigin);
2615         }
2616
2617         if (!(ent->flags & RENDER_LIGHT) || r_fullbright.integer)
2618         {
2619                 // intentionally EF_FULLBRIGHT entity
2620                 // the only type that is not scaled by r_refdef.scene.lightmapintensity
2621                 // CSQC can still provide its own customized modellight values
2622                 ent->render_rtlight_disabled = true;
2623                 ent->render_modellight_forced = true;
2624                 if (ent->flags & RENDER_CUSTOMIZEDMODELLIGHT)
2625                 {
2626                         // custom colors provided by CSQC
2627                         for (q = 0; q < 3; q++)
2628                         {
2629                                 a[q] = ent->custommodellight_ambient[q];
2630                                 c[q] = ent->custommodellight_diffuse[q];
2631                                 dir[q] = ent->custommodellight_lightdir[q];
2632                         }
2633                 }
2634                 else if (r_fullbright_directed.integer)
2635                         CL_UpdateEntityShading_GetDirectedFullbright(a, c, dir);
2636                 else
2637                         for (q = 0; q < 3; q++)
2638                                 a[q] = 1;
2639         }
2640         else
2641         {
2642                 // fetch the lighting from the worldmodel data
2643
2644                 // CSQC can provide its own customized modellight values
2645                 if (ent->flags & RENDER_CUSTOMIZEDMODELLIGHT)
2646                 {
2647                         ent->render_modellight_forced = true;
2648                         for (q = 0; q < 3; q++)
2649                         {
2650                                 a[q] = ent->custommodellight_ambient[q];
2651                                 c[q] = ent->custommodellight_diffuse[q];
2652                                 dir[q] = ent->custommodellight_lightdir[q];
2653                         }
2654                 }
2655                 else if (ent->model->type == mod_sprite && !(ent->model->data_textures[0].basematerialflags & MATERIALFLAG_FULLBRIGHT))
2656                 {
2657                         if (ent->model->sprite.sprnum_type == SPR_OVERHEAD) // apply offset for overhead sprites
2658                                 shadingorigin[2] = shadingorigin[2] + r_overheadsprites_pushback.value;
2659                         R_CompleteLightPoint(a, c, dir, shadingorigin, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT, r_refdef.scene.lightmapintensity, r_refdef.scene.ambientintensity);
2660                         ent->render_modellight_forced = true;
2661                         ent->render_rtlight_disabled = true;
2662                 }
2663                 else if (((ent->model && !ent->model->lit) || (ent->model == r_refdef.scene.worldmodel ? mod_q3bsp_lightgrid_world_surfaces.integer : mod_q3bsp_lightgrid_bsp_surfaces.integer))
2664                         && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brushq3.lightgridtexture && mod_q3bsp_lightgrid_texture.integer)
2665                 {
2666                         ent->render_lightgrid = true;
2667                         // no need to call R_CompleteLightPoint as we base it on render_lightmap_*
2668                 }
2669                 else if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint)
2670                         R_CompleteLightPoint(a, c, dir, shadingorigin, LP_LIGHTMAP, r_refdef.scene.lightmapintensity, r_refdef.scene.ambientintensity);
2671                 else if (r_fullbright_directed.integer)
2672                         CL_UpdateEntityShading_GetDirectedFullbright(a, c, dir);
2673                 else
2674                         R_CompleteLightPoint(a, c, dir, shadingorigin, LP_LIGHTMAP, r_refdef.scene.lightmapintensity, r_refdef.scene.ambientintensity);
2675         }
2676
2677         for (q = 0; q < 3; q++)
2678         {
2679                 ent->render_fullbright[q] = ent->colormod[q];
2680                 ent->render_glowmod[q] = ent->glowmod[q] * r_hdr_glowintensity.value;
2681                 ent->render_modellight_ambient[q] = a[q] * ent->colormod[q];
2682                 ent->render_modellight_diffuse[q] = c[q] * ent->colormod[q];
2683                 ent->render_modellight_specular[q] = c[q];
2684                 ent->render_modellight_lightdir_world[q] = dir[q];
2685                 ent->render_lightmap_ambient[q] = ent->colormod[q] * r_refdef.scene.ambientintensity;
2686                 ent->render_lightmap_diffuse[q] = ent->colormod[q] * r_refdef.scene.lightmapintensity;
2687                 ent->render_lightmap_specular[q] = r_refdef.scene.lightmapintensity;
2688                 ent->render_rtlight_diffuse[q] = ent->colormod[q];
2689                 ent->render_rtlight_specular[q] = 1;
2690         }
2691
2692         // these flags disable code paths, make sure it's obvious if they're ignored by storing 0 1 2
2693         if (ent->render_modellight_forced)
2694                 for (q = 0; q < 3; q++)
2695                         ent->render_lightmap_ambient[q] = ent->render_lightmap_diffuse[q] = ent->render_lightmap_specular[q] = q;
2696         if (ent->render_rtlight_disabled)
2697                 for (q = 0; q < 3; q++)
2698                         ent->render_rtlight_diffuse[q] = ent->render_rtlight_specular[q] = q;
2699
2700         if (VectorLength2(ent->render_modellight_lightdir_world) == 0)
2701                 VectorSet(ent->render_modellight_lightdir_world, 0, 0, 1); // have to set SOME valid vector here
2702         VectorNormalize(ent->render_modellight_lightdir_world);
2703         // transform into local space for the entity as well
2704         Matrix4x4_Transform3x3(&ent->inversematrix, ent->render_modellight_lightdir_world, ent->render_modellight_lightdir_local);
2705         VectorNormalize(ent->render_modellight_lightdir_local);
2706 }
2707
2708
2709 void CL_UpdateEntityShading(void)
2710 {
2711         int i;
2712         CL_UpdateEntityShading_Entity(r_refdef.scene.worldentity);
2713         for (i = 0; i < r_refdef.scene.numentities; i++)
2714                 CL_UpdateEntityShading_Entity(r_refdef.scene.entities[i]);
2715 }
2716
2717 extern cvar_t host_framerate;
2718 extern cvar_t host_speeds;
2719
2720 double CL_Frame (double time)
2721 {
2722         static double clframetime;
2723         static double cl_timer = 0;
2724         static double time1 = 0, time2 = 0, time3 = 0;
2725         static double wait;
2726         int pass1, pass2, pass3;
2727
2728         CL_VM_PreventInformationLeaks();
2729
2730         // get new key events
2731         Key_EventQueue_Unblock();
2732         SndSys_SendKeyEvents();
2733         Sys_SendKeyEvents();
2734
2735         if((cl_timer += time) < 0)
2736                 return cl_timer;
2737
2738         // limit the frametime steps to no more than 100ms each
2739         if (cl_timer > 0.1)
2740                 cl_timer = 0.1;
2741
2742         if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
2743         {
2744                 R_TimeReport("---");
2745                 Collision_Cache_NewFrame();
2746                 R_TimeReport("photoncache");
2747 #ifdef CONFIG_VIDEO_CAPTURE
2748                 // decide the simulation time
2749                 if (cls.capturevideo.active)
2750                 {
2751                         //***
2752                         if (cls.capturevideo.realtime)
2753                                 clframetime = cl.realframetime = max(time, 1.0 / cls.capturevideo.framerate);
2754                         else
2755                         {
2756                                 clframetime = 1.0 / cls.capturevideo.framerate;
2757                                 cl.realframetime = max(time, clframetime);
2758                         }
2759                 }
2760                 else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
2761
2762 #else
2763                 if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
2764 #endif
2765                 {
2766                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
2767                         // when running slow, we need to sleep to keep input responsive
2768                         wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
2769                         if (wait > 0)
2770                                 Sys_Sleep((int)wait);
2771                 }
2772                 else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
2773                         clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
2774                 else
2775                         clframetime = cl.realframetime = cl_timer;
2776
2777                 // apply slowmo scaling
2778                 clframetime *= cl.movevars_timescale;
2779                 // scale playback speed of demos by slowmo cvar
2780                 if (cls.demoplayback)
2781                 {
2782                         clframetime *= host_timescale.value;
2783                         // if demo playback is paused, don't advance time at all
2784                         if (cls.demopaused)
2785                                 clframetime = 0;
2786                 }
2787                 else
2788                 {
2789                         // host_framerate overrides all else
2790                         if (host_framerate.value)
2791                                 clframetime = host_framerate.value;
2792
2793                         if (cl.paused || host.paused)
2794                                 clframetime = 0;
2795                 }
2796
2797                 if (cls.timedemo)
2798                         clframetime = cl.realframetime = cl_timer;
2799
2800                 // deduct the frame time from the accumulator
2801                 cl_timer -= cl.realframetime;
2802
2803                 cl.oldtime = cl.time;
2804                 cl.time += clframetime;
2805
2806                 // update video
2807                 if (host_speeds.integer)
2808                         time1 = Sys_DirtyTime();
2809                 R_TimeReport("pre-input");
2810
2811                 // Collect input into cmd
2812                 CL_Input();
2813
2814                 R_TimeReport("input");
2815
2816                 // check for new packets
2817                 NetConn_ClientFrame();
2818
2819                 // read a new frame from a demo if needed
2820                 CL_ReadDemoMessage();
2821                 R_TimeReport("clientnetwork");
2822
2823                 // now that packets have been read, send input to server
2824                 CL_SendMove();
2825                 R_TimeReport("sendmove");
2826
2827                 // update client world (interpolate entities, create trails, etc)
2828                 CL_UpdateWorld();
2829                 R_TimeReport("lerpworld");
2830
2831                 CL_Video_Frame();
2832
2833                 R_TimeReport("client");
2834
2835                 CL_UpdateScreen();
2836                 R_TimeReport("render");
2837
2838                 if (host_speeds.integer)
2839                         time2 = Sys_DirtyTime();
2840
2841                 // update audio
2842                 if(cl.csqc_usecsqclistener)
2843                 {
2844                         S_Update(&cl.csqc_listenermatrix);
2845                         cl.csqc_usecsqclistener = false;
2846                 }
2847                 else
2848                         S_Update(&r_refdef.view.matrix);
2849
2850                 CDAudio_Update();
2851                 R_TimeReport("audio");
2852
2853                 // reset gathering of mouse input
2854                 in_mouse_x = in_mouse_y = 0;
2855
2856                 if (host_speeds.integer)
2857                 {
2858                         pass1 = (int)((time1 - time3)*1000000);
2859                         time3 = Sys_DirtyTime();
2860                         pass2 = (int)((time2 - time1)*1000000);
2861                         pass3 = (int)((time3 - time2)*1000000);
2862                         Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
2863                                                 pass1+pass2+pass3, pass1, pass2, pass3);
2864                 }
2865         }
2866         // if there is some time remaining from this frame, reset the timer
2867         return cl_timer >= 0 ? 0 : cl_timer;
2868 }
2869
2870 /*
2871 ===========
2872 CL_Shutdown
2873 ===========
2874 */
2875 void CL_Shutdown (void)
2876 {
2877         // be quiet while shutting down
2878         S_StopAllSounds();
2879         
2880         // disconnect client from server if active
2881         CL_Disconnect();
2882         
2883         CL_Video_Shutdown();
2884
2885 #ifdef CONFIG_MENU
2886         // Shutdown menu
2887         if(MR_Shutdown)
2888                 MR_Shutdown();
2889 #endif
2890
2891         CDAudio_Shutdown ();
2892         S_Terminate ();
2893         
2894         R_Modules_Shutdown();
2895         VID_Shutdown();
2896
2897         CL_Screen_Shutdown();
2898         CL_Particles_Shutdown();
2899         CL_Parse_Shutdown();
2900         CL_MeshEntities_Shutdown();
2901
2902         Key_Shutdown();
2903         S_Shutdown();
2904
2905         Mem_FreePool (&cls.permanentmempool);
2906         Mem_FreePool (&cls.levelmempool);
2907 }
2908
2909 /*
2910 =================
2911 CL_Init
2912 =================
2913 */
2914 void CL_Init (void)
2915 {
2916         if (cls.state == ca_dedicated)
2917         {
2918                 Cmd_AddCommand(CF_SERVER, "disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)");
2919         }
2920         else
2921         {
2922                 Con_Printf("Initializing client\n");
2923
2924                 Cvar_SetValueQuick(&host_isclient, 1);
2925
2926                 R_Modules_Init();
2927                 Palette_Init();
2928 #ifdef CONFIG_MENU
2929                 MR_Init_Commands();
2930 #endif
2931                 VID_Shared_Init();
2932                 VID_Init();
2933                 Render_Init();
2934                 S_Init();
2935                 CDAudio_Init();
2936                 Key_Init();
2937                 V_Init();
2938
2939                 cls.levelmempool = Mem_AllocPool("client (per-level memory)", 0, NULL);
2940                 cls.permanentmempool = Mem_AllocPool("client (long term memory)", 0, NULL);
2941
2942                 memset(&r_refdef, 0, sizeof(r_refdef));
2943                 // max entities sent to renderer per frame
2944                 r_refdef.scene.maxentities = MAX_EDICTS + 256 + 512;
2945                 r_refdef.scene.entities = (entity_render_t **)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t *) * r_refdef.scene.maxentities);
2946
2947                 // max temp entities
2948                 r_refdef.scene.maxtempentities = MAX_TEMPENTITIES;
2949                 r_refdef.scene.tempentities = (entity_render_t *)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t) * r_refdef.scene.maxtempentities);
2950
2951                 CL_InitInput ();
2952
2953         //
2954         // register our commands
2955         //
2956                 CL_InitCommands();
2957
2958                 Cvar_RegisterVariable (&cl_upspeed);
2959                 Cvar_RegisterVariable (&cl_forwardspeed);
2960                 Cvar_RegisterVariable (&cl_backspeed);
2961                 Cvar_RegisterVariable (&cl_sidespeed);
2962                 Cvar_RegisterVariable (&cl_movespeedkey);
2963                 Cvar_RegisterVariable (&cl_yawspeed);
2964                 Cvar_RegisterVariable (&cl_pitchspeed);
2965                 Cvar_RegisterVariable (&cl_anglespeedkey);
2966                 Cvar_RegisterVariable (&cl_shownet);
2967                 Cvar_RegisterVariable (&cl_nolerp);
2968                 Cvar_RegisterVariable (&cl_lerpexcess);
2969                 Cvar_RegisterVariable (&cl_lerpanim_maxdelta_server);
2970                 Cvar_RegisterVariable (&cl_lerpanim_maxdelta_framegroups);
2971                 Cvar_RegisterVariable (&cl_deathfade);
2972                 Cvar_RegisterVariable (&lookspring);
2973                 Cvar_RegisterVariable (&lookstrafe);
2974                 Cvar_RegisterVariable (&sensitivity);
2975                 Cvar_RegisterVariable (&freelook);
2976
2977                 Cvar_RegisterVariable (&m_pitch);
2978                 Cvar_RegisterVariable (&m_yaw);
2979                 Cvar_RegisterVariable (&m_forward);
2980                 Cvar_RegisterVariable (&m_side);
2981
2982                 Cvar_RegisterVariable (&cl_itembobspeed);
2983                 Cvar_RegisterVariable (&cl_itembobheight);
2984
2985                 CL_Demo_Init();
2986
2987                 Cmd_AddCommand(CF_CLIENT, "entities", CL_PrintEntities_f, "print information on network entities known to client");
2988                 Cmd_AddCommand(CF_CLIENT, "disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)");
2989                 Cmd_AddCommand(CF_CLIENT, "connect", CL_Connect_f, "connect to a server by IP address or hostname");
2990                 Cmd_AddCommand(CF_CLIENT | CF_CLIENT_FROM_SERVER, "reconnect", CL_Reconnect_f, "reconnect to the last server you were on, or resets a quakeworld connection (do not use if currently playing on a netquake server)");
2991
2992                 // Support Client-side Model Index List
2993                 Cmd_AddCommand(CF_CLIENT, "cl_modelindexlist", CL_ModelIndexList_f, "list information on all models in the client modelindex");
2994                 // Support Client-side Sound Index List
2995                 Cmd_AddCommand(CF_CLIENT, "cl_soundindexlist", CL_SoundIndexList_f, "list all sounds in the client soundindex");
2996
2997                 Cmd_AddCommand(CF_CLIENT, "fog", CL_Fog_f, "set global fog parameters (density red green blue [alpha [mindist [maxdist [top [fadedepth]]]]])");
2998                 Cmd_AddCommand(CF_CLIENT, "fog_heighttexture", CL_Fog_HeightTexture_f, "set global fog parameters (density red green blue alpha mindist maxdist top depth textures/mapname/fogheight.tga)");
2999
3000                 Cmd_AddCommand(CF_CLIENT, "cl_areastats", CL_AreaStats_f, "prints statistics on entity culling during collision traces");
3001
3002                 Cvar_RegisterVariable(&r_draweffects);
3003                 Cvar_RegisterVariable(&cl_explosions_alpha_start);
3004                 Cvar_RegisterVariable(&cl_explosions_alpha_end);
3005                 Cvar_RegisterVariable(&cl_explosions_size_start);
3006                 Cvar_RegisterVariable(&cl_explosions_size_end);
3007                 Cvar_RegisterVariable(&cl_explosions_lifetime);
3008                 Cvar_RegisterVariable(&cl_stainmaps);
3009                 Cvar_RegisterVariable(&cl_stainmaps_clearonload);
3010                 Cvar_RegisterVariable(&cl_beams_polygons);
3011                 Cvar_RegisterVariable(&cl_beams_quakepositionhack);
3012                 Cvar_RegisterVariable(&cl_beams_instantaimhack);
3013                 Cvar_RegisterVariable(&cl_beams_lightatend);
3014                 Cvar_RegisterVariable(&cl_noplayershadow);
3015                 Cvar_RegisterVariable(&cl_dlights_decayradius);
3016                 Cvar_RegisterVariable(&cl_dlights_decaybrightness);
3017
3018                 Cvar_RegisterVariable(&cl_prydoncursor);
3019                 Cvar_RegisterVariable(&cl_prydoncursor_notrace);
3020
3021                 Cvar_RegisterVariable(&cl_deathnoviewmodel);
3022
3023                 // for QW connections
3024                 Cvar_RegisterVariable(&qport);
3025                 Cvar_SetValueQuick(&qport, (rand() * RAND_MAX + rand()) & 0xffff);
3026
3027                 Cmd_AddCommand(CF_CLIENT, "timerefresh", CL_TimeRefresh_f, "turn quickly and print rendering statistcs");
3028
3029                 Cvar_RegisterVariable(&cl_locs_enable);
3030                 Cvar_RegisterVariable(&cl_locs_show);
3031                 Cmd_AddCommand(CF_CLIENT, "locs_add", CL_Locs_Add_f, "add a point or box location (usage: x y z[ x y z] \"name\", if two sets of xyz are supplied it is a box, otherwise point)");
3032                 Cmd_AddCommand(CF_CLIENT, "locs_removenearest", CL_Locs_RemoveNearest_f, "remove the nearest point or box (note: you need to be very near a box to remove it)");
3033                 Cmd_AddCommand(CF_CLIENT, "locs_clear", CL_Locs_Clear_f, "remove all loc points/boxes");
3034                 Cmd_AddCommand(CF_CLIENT, "locs_reload", CL_Locs_Reload_f, "reload .loc file for this map");
3035                 Cmd_AddCommand(CF_CLIENT, "locs_save", CL_Locs_Save_f, "save .loc file for this map containing currently defined points and boxes");
3036
3037                 Cvar_RegisterVariable(&csqc_polygons_defaultmaterial_nocullface);
3038
3039                 Cvar_RegisterVariable (&cl_minfps);
3040                 Cvar_RegisterVariable (&cl_minfps_fade);
3041                 Cvar_RegisterVariable (&cl_minfps_qualitymax);
3042                 Cvar_RegisterVariable (&cl_minfps_qualitymin);
3043                 Cvar_RegisterVariable (&cl_minfps_qualitystepmax);
3044                 Cvar_RegisterVariable (&cl_minfps_qualityhysteresis);
3045                 Cvar_RegisterVariable (&cl_minfps_qualitymultiply);
3046                 Cvar_RegisterVariable (&cl_minfps_force);
3047                 Cvar_RegisterVariable (&cl_maxfps);
3048                 Cvar_RegisterVariable (&cl_maxfps_alwayssleep);
3049                 Cvar_RegisterVariable (&cl_maxidlefps);
3050
3051                 CL_Parse_Init();
3052                 CL_Particles_Init();
3053                 CL_Screen_Init();
3054                 CL_MeshEntities_Init();
3055
3056                 CL_Video_Init();
3057
3058                 host.hook.ConnectLocal = CL_EstablishConnection_Local;
3059         }
3060 }