]> icculus.org git repositories - divverent/darkplaces.git/blob - cl_main.c
reworked animcache code to store information in ent->animcache_vertex3f
[divverent/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_gecko.h"
25 #include "cl_video.h"
26 #include "image.h"
27 #include "csprogs.h"
28 #include "r_shadow.h"
29 #include "libcurl.h"
30 #include "snd_main.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 = {0, "csqc_progname","csprogs.dat","name of csprogs.dat file to load"};
36 cvar_t csqc_progcrc = {CVAR_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 = {CVAR_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
39 cvar_t cl_shownet = {0, "cl_shownet","0","1 = print packet size, 2 = print packet message list"};
40 cvar_t cl_nolerp = {0, "cl_nolerp", "0","network update smoothing"};
41
42 cvar_t cl_itembobheight = {0, "cl_itembobheight", "0","how much items bob up and down (try 8)"};
43 cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5","how frequently items bob up and down"};
44
45 cvar_t lookspring = {CVAR_SAVE, "lookspring","0","returns pitch to level with the floor when no longer holding a pitch key"};
46 cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0","move instead of turning"};
47 cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3","mouse speed multiplier"};
48
49 cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022","mouse pitch speed multiplier"};
50 cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022","mouse yaw speed multiplier"};
51 cvar_t m_forward = {CVAR_SAVE, "m_forward","1","mouse forward speed multiplier"};
52 cvar_t m_side = {CVAR_SAVE, "m_side","0.8","mouse side speed multiplier"};
53
54 cvar_t freelook = {CVAR_SAVE, "freelook", "1","mouse controls pitch instead of forward/back"};
55
56 cvar_t cl_autodemo = {CVAR_SAVE, "cl_autodemo", "0", "records every game played, using the date/time and map name to name the demo file" };
57 cvar_t cl_autodemo_nameformat = {CVAR_SAVE, "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)" };
58
59 cvar_t r_draweffects = {0, "r_draweffects", "1","renders temporary sprite effects"};
60
61 cvar_t cl_explosions_alpha_start = {CVAR_SAVE, "cl_explosions_alpha_start", "1.5","starting alpha of an explosion shell"};
62 cvar_t cl_explosions_alpha_end = {CVAR_SAVE, "cl_explosions_alpha_end", "0","end alpha of an explosion shell (just before it disappears)"};
63 cvar_t cl_explosions_size_start = {CVAR_SAVE, "cl_explosions_size_start", "16","starting size of an explosion shell"};
64 cvar_t cl_explosions_size_end = {CVAR_SAVE, "cl_explosions_size_end", "128","ending alpha of an explosion shell (just before it disappears)"};
65 cvar_t cl_explosions_lifetime = {CVAR_SAVE, "cl_explosions_lifetime", "0.5","how long an explosion shell lasts"};
66
67 cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "0","stains lightmaps, much faster than decals but blurred"};
68 cvar_t cl_stainmaps_clearonload = {CVAR_SAVE, "cl_stainmaps_clearonload", "1","clear stainmaps on map restart"};
69
70 cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1","use beam polygons instead of models"};
71 cvar_t cl_beams_quakepositionhack = {CVAR_SAVE, "cl_beams_quakepositionhack", "1", "makes your lightning gun appear to fire from your waist (as in Quake and QuakeWorld)"};
72 cvar_t cl_beams_instantaimhack = {CVAR_SAVE, "cl_beams_instantaimhack", "0", "makes your lightning gun aiming update instantly"};
73 cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0", "make a light at the end of the beam"};
74
75 cvar_t cl_deathfade = {CVAR_SAVE, "cl_deathfade", "0", "fade screen to dark red when dead, value = how fast the fade is"};
76
77 cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0","hide player shadow"};
78
79 cvar_t cl_dlights_decayradius = {CVAR_SAVE, "cl_dlights_decayradius", "1", "reduces size of light flashes over time"};
80 cvar_t cl_dlights_decaybrightness = {CVAR_SAVE, "cl_dlights_decaybrightness", "1", "reduces brightness of light flashes over time"};
81
82 cvar_t qport = {0, "qport", "0", "identification key for playing on qw servers (allows you to maintain a connection to a quakeworld server even if your port changes)"};
83
84 cvar_t cl_prydoncursor = {0, "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"};
85
86 cvar_t cl_deathnoviewmodel = {0, "cl_deathnoviewmodel", "1", "hides gun model when dead"};
87
88 cvar_t cl_locs_enable = {CVAR_SAVE, "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)"};
89 cvar_t cl_locs_show = {0, "locs_show", "0", "shows defined locations for editing purposes"};
90
91 extern cvar_t r_equalize_entities_fullbright;
92
93 client_static_t cls;
94 client_state_t  cl;
95
96 /*
97 =====================
98 CL_ClearState
99
100 =====================
101 */
102 void CL_VM_ShutDown (void);
103 void CL_ClearState(void)
104 {
105         int i;
106         entity_t *ent;
107
108         CL_VM_ShutDown();
109
110 // wipe the entire cl structure
111         Mem_EmptyPool(cls.levelmempool);
112         memset (&cl, 0, sizeof(cl));
113
114         S_StopAllSounds();
115
116         // reset the view zoom interpolation
117         cl.mviewzoom[0] = cl.mviewzoom[1] = 1;
118         cl.sensitivityscale = 1.0f;
119
120         // enable rendering of the world and such
121         cl.csqc_vidvars.drawworld = true;
122         cl.csqc_vidvars.drawenginesbar = true;
123         cl.csqc_vidvars.drawcrosshair = true;
124
125         // set up the float version of the stats array for easier access to float stats
126         cl.statsf = (float *)cl.stats;
127
128         cl.num_entities = 0;
129         cl.num_static_entities = 0;
130         cl.num_brushmodel_entities = 0;
131
132         // tweak these if the game runs out
133         cl.max_csqcrenderentities = 0;
134         cl.max_entities = 256;
135         cl.max_static_entities = 256;
136         cl.max_effects = 256;
137         cl.max_beams = 256;
138         cl.max_dlights = MAX_DLIGHTS;
139         cl.max_lightstyle = MAX_LIGHTSTYLES;
140         cl.max_brushmodel_entities = MAX_EDICTS;
141         cl.max_particles = 8192; // grows dynamically
142         cl.max_decals = 2048; // grows dynamically
143         cl.max_showlmps = 0;
144
145         cl.num_dlights = 0;
146         cl.num_effects = 0;
147         cl.num_beams = 0;
148
149         cl.csqcrenderentities = NULL;
150         cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
151         cl.entities_active = (unsigned char *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(unsigned char));
152         cl.static_entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_static_entities * sizeof(entity_t));
153         cl.effects = (cl_effect_t *)Mem_Alloc(cls.levelmempool, cl.max_effects * sizeof(cl_effect_t));
154         cl.beams = (beam_t *)Mem_Alloc(cls.levelmempool, cl.max_beams * sizeof(beam_t));
155         cl.dlights = (dlight_t *)Mem_Alloc(cls.levelmempool, cl.max_dlights * sizeof(dlight_t));
156         cl.lightstyle = (lightstyle_t *)Mem_Alloc(cls.levelmempool, cl.max_lightstyle * sizeof(lightstyle_t));
157         cl.brushmodel_entities = (int *)Mem_Alloc(cls.levelmempool, cl.max_brushmodel_entities * sizeof(int));
158         cl.particles = (particle_t *) Mem_Alloc(cls.levelmempool, cl.max_particles * sizeof(particle_t));
159         cl.decals = (decal_t *) Mem_Alloc(cls.levelmempool, cl.max_decals * sizeof(decal_t));
160         cl.showlmps = NULL;
161
162         // LordHavoc: have to set up the baseline info for alpha and other stuff
163         for (i = 0;i < cl.max_entities;i++)
164         {
165                 cl.entities[i].state_baseline = defaultstate;
166                 cl.entities[i].state_previous = defaultstate;
167                 cl.entities[i].state_current = defaultstate;
168         }
169
170         if (gamemode == GAME_NEXUIZ)
171         {
172                 VectorSet(cl.playerstandmins, -16, -16, -24);
173                 VectorSet(cl.playerstandmaxs, 16, 16, 45);
174                 VectorSet(cl.playercrouchmins, -16, -16, -24);
175                 VectorSet(cl.playercrouchmaxs, 16, 16, 25);
176         }
177         else
178         {
179                 VectorSet(cl.playerstandmins, -16, -16, -24);
180                 VectorSet(cl.playerstandmaxs, 16, 16, 24);
181                 VectorSet(cl.playercrouchmins, -16, -16, -24);
182                 VectorSet(cl.playercrouchmaxs, 16, 16, 24);
183         }
184
185         // disable until we get textures for it
186         R_ResetSkyBox();
187
188         ent = &cl.entities[0];
189         // entire entity array was cleared, so just fill in a few fields
190         ent->state_current.active = true;
191         ent->render.model = cl.worldmodel = NULL; // no world model yet
192         ent->render.alpha = 1;
193         ent->render.flags = RENDER_SHADOW | RENDER_LIGHT;
194         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, 0, 0, 0, 0, 0, 0, 1);
195         ent->render.allowdecals = true;
196         CL_UpdateRenderEntity(&ent->render);
197
198         // noclip is turned off at start
199         noclip_anglehack = false;
200
201         // mark all frames invalid for delta
202         memset(cl.qw_deltasequence, -1, sizeof(cl.qw_deltasequence));
203
204         // set bestweapon data back to Quake data
205         IN_BestWeapon_ResetData();
206
207         CL_Screen_NewMap();
208 }
209
210 void CL_SetInfo(const char *key, const char *value, qboolean send, qboolean allowstarkey, qboolean allowmodel, qboolean quiet)
211 {
212         int i;
213         qboolean fail = false;
214         if (!allowstarkey && key[0] == '*')
215                 fail = true;
216         if (!allowmodel && (!strcasecmp(key, "pmodel") || !strcasecmp(key, "emodel")))
217                 fail = true;
218         for (i = 0;key[i];i++)
219                 if (ISWHITESPACE(key[i]) || key[i] == '\"')
220                         fail = true;
221         for (i = 0;value[i];i++)
222                 if (value[i] == '\r' || value[i] == '\n' || value[i] == '\"')
223                         fail = true;
224         if (fail)
225         {
226                 if (!quiet)
227                         Con_Printf("Can't setinfo \"%s\" \"%s\"\n", key, value);
228                 return;
229         }
230         InfoString_SetValue(cls.userinfo, sizeof(cls.userinfo), key, value);
231         if (cls.state == ca_connected && cls.netcon)
232         {
233                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
234                 {
235                         MSG_WriteByte(&cls.netcon->message, qw_clc_stringcmd);
236                         MSG_WriteString(&cls.netcon->message, va("setinfo \"%s\" \"%s\"", key, value));
237                 }
238                 else if (!strcasecmp(key, "name"))
239                 {
240                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
241                         MSG_WriteString(&cls.netcon->message, va("name \"%s\"", value));
242                 }
243                 else if (!strcasecmp(key, "playermodel"))
244                 {
245                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
246                         MSG_WriteString(&cls.netcon->message, va("playermodel \"%s\"", value));
247                 }
248                 else if (!strcasecmp(key, "playerskin"))
249                 {
250                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
251                         MSG_WriteString(&cls.netcon->message, va("playerskin \"%s\"", value));
252                 }
253                 else if (!strcasecmp(key, "topcolor"))
254                 {
255                         // don't send anything, the combined color code will be updated manually
256                 }
257                 else if (!strcasecmp(key, "bottomcolor"))
258                 {
259                         // don't send anything, the combined color code will be updated manually
260                 }
261                 else if (!strcasecmp(key, "rate"))
262                 {
263                         MSG_WriteByte(&cls.netcon->message, clc_stringcmd);
264                         MSG_WriteString(&cls.netcon->message, va("rate \"%s\"", value));
265                 }
266         }
267 }
268
269 void CL_ExpandEntities(int num)
270 {
271         int i, oldmaxentities;
272         entity_t *oldentities;
273         if (num >= cl.max_entities)
274         {
275                 if (!cl.entities)
276                         Sys_Error("CL_ExpandEntities: cl.entities not initialized");
277                 if (num >= MAX_EDICTS)
278                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
279                 oldmaxentities = cl.max_entities;
280                 oldentities = cl.entities;
281                 cl.max_entities = (num & ~255) + 256;
282                 cl.entities = (entity_t *)Mem_Alloc(cls.levelmempool, cl.max_entities * sizeof(entity_t));
283                 memcpy(cl.entities, oldentities, oldmaxentities * sizeof(entity_t));
284                 Mem_Free(oldentities);
285                 for (i = oldmaxentities;i < cl.max_entities;i++)
286                 {
287                         cl.entities[i].state_baseline = defaultstate;
288                         cl.entities[i].state_previous = defaultstate;
289                         cl.entities[i].state_current = defaultstate;
290                 }
291         }
292 }
293
294 void CL_ExpandCSQCRenderEntities(int num)
295 {
296         int oldmaxcsqcrenderentities;
297         entity_render_t *oldcsqcrenderentities;
298         if (num >= cl.max_csqcrenderentities)
299         {
300                 if (num >= MAX_EDICTS)
301                         Host_Error("CL_ExpandEntities: num %i >= %i", num, MAX_EDICTS);
302                 oldmaxcsqcrenderentities = cl.max_csqcrenderentities;
303                 oldcsqcrenderentities = cl.csqcrenderentities;
304                 cl.max_csqcrenderentities = (num & ~255) + 256;
305                 cl.csqcrenderentities = (entity_render_t *)Mem_Alloc(cls.levelmempool, cl.max_csqcrenderentities * sizeof(entity_render_t));
306                 if (oldcsqcrenderentities)
307                 {
308                         memcpy(cl.csqcrenderentities, oldcsqcrenderentities, oldmaxcsqcrenderentities * sizeof(entity_render_t));
309                         Mem_Free(oldcsqcrenderentities);
310                 }
311         }
312 }
313
314 /*
315 =====================
316 CL_Disconnect
317
318 Sends a disconnect message to the server
319 This is also called on Host_Error, so it shouldn't cause any errors
320 =====================
321 */
322 void CL_Disconnect(void)
323 {
324         if (cls.state == ca_dedicated)
325                 return;
326
327         if (COM_CheckParm("-profilegameonly"))
328                 Sys_AllowProfiling(false);
329
330         Curl_Clear_forthismap();
331
332         Con_DPrintf("CL_Disconnect\n");
333
334     Cvar_SetValueQuick(&csqc_progcrc, -1);
335         Cvar_SetValueQuick(&csqc_progsize, -1);
336         CL_VM_ShutDown();
337 // stop sounds (especially looping!)
338         S_StopAllSounds ();
339
340         cl.parsingtextexpectingpingforscores = 0; // just in case no reply has come yet
341
342         // clear contents blends
343         cl.cshifts[0].percent = 0;
344         cl.cshifts[1].percent = 0;
345         cl.cshifts[2].percent = 0;
346         cl.cshifts[3].percent = 0;
347
348         cl.worldmodel = NULL;
349
350         CL_Parse_ErrorCleanUp();
351
352         if (cls.demoplayback)
353                 CL_StopPlayback();
354         else if (cls.netcon)
355         {
356                 sizebuf_t buf;
357                 unsigned char bufdata[8];
358                 if (cls.demorecording)
359                         CL_Stop_f();
360
361                 // send disconnect message 3 times to improve chances of server
362                 // receiving it (but it still fails sometimes)
363                 memset(&buf, 0, sizeof(buf));
364                 buf.data = bufdata;
365                 buf.maxsize = sizeof(bufdata);
366                 if (cls.protocol == PROTOCOL_QUAKEWORLD)
367                 {
368                         Con_DPrint("Sending drop command\n");
369                         MSG_WriteByte(&buf, qw_clc_stringcmd);
370                         MSG_WriteString(&buf, "drop");
371                 }
372                 else
373                 {
374                         Con_DPrint("Sending clc_disconnect\n");
375                         MSG_WriteByte(&buf, clc_disconnect);
376                 }
377                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, false);
378                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, false);
379                 NetConn_SendUnreliableMessage(cls.netcon, &buf, cls.protocol, 10000, false);
380                 NetConn_Close(cls.netcon);
381                 cls.netcon = NULL;
382         }
383         cls.state = ca_disconnected;
384
385         cls.demoplayback = cls.timedemo = false;
386         cls.signon = 0;
387 }
388
389 void CL_Disconnect_f(void)
390 {
391         CL_Disconnect ();
392         if (sv.active)
393                 Host_ShutdownServer ();
394 }
395
396
397
398
399 /*
400 =====================
401 CL_EstablishConnection
402
403 Host should be either "local" or a net address
404 =====================
405 */
406 void CL_EstablishConnection(const char *host)
407 {
408         if (cls.state == ca_dedicated)
409                 return;
410
411         // clear menu's connect error message
412         M_Update_Return_Reason("");
413         cls.demonum = -1;
414
415         // stop demo loop in case this fails
416         if (cls.demoplayback)
417                 CL_StopPlayback();
418
419         // if downloads are running, cancel their finishing action
420         Curl_Clear_forthismap();
421
422         // make sure the client ports are open before attempting to connect
423         NetConn_UpdateSockets();
424
425         // run a network frame
426         //NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
427
428         if (LHNETADDRESS_FromString(&cls.connect_address, host, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address)))
429         {
430                 cls.connect_trying = true;
431                 cls.connect_remainingtries = 3;
432                 cls.connect_nextsendtime = 0;
433                 M_Update_Return_Reason("Trying to connect...");
434                 // run several network frames to jump into the game quickly
435                 //if (sv.active)
436                 //{
437                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
438                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
439                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
440                 //      NetConn_ClientFrame();SV_VM_Begin();NetConn_ServerFrame();SV_VM_End();
441                 //}
442         }
443         else
444         {
445                 Con_Print("Unable to find a suitable network socket to connect to server.\n");
446                 M_Update_Return_Reason("No network");
447         }
448 }
449
450 /*
451 ==============
452 CL_PrintEntities_f
453 ==============
454 */
455 static void CL_PrintEntities_f(void)
456 {
457         entity_t *ent;
458         int i;
459
460         for (i = 0, ent = cl.entities;i < cl.num_entities;i++, ent++)
461         {
462                 const char* modelname;
463
464                 if (!ent->state_current.active)
465                         continue;
466
467                 if (ent->render.model)
468                         modelname = ent->render.model->name;
469                 else
470                         modelname = "--no model--";
471                 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);
472         }
473 }
474
475 /*
476 ===============
477 CL_ModelIndexList_f
478
479 List information on all models in the client modelindex
480 ===============
481 */
482 static void CL_ModelIndexList_f(void)
483 {
484         int i;
485         dp_model_t *model;
486
487         // Print Header
488         Con_Printf("%3s: %-30s %-8s %-8s\n", "ID", "Name", "Type", "Triangles");
489
490         for (i = -MAX_MODELS;i < MAX_MODELS;i++)
491         {
492                 model = CL_GetModelByIndex(i);
493                 if(model->loaded || i == 1)
494                         Con_Printf("%3i: %-30s %-8s %-10i\n", i, model->name, model->modeldatatypestring, model->surfmesh.num_triangles);
495                 else
496                         Con_Printf("%3i: %-30s %-30s\n", i, model->name, "--no local model found--");
497                 i++;
498         }
499 }
500
501 /*
502 ===============
503 CL_SoundIndexList_f
504
505 List all sounds in the client soundindex
506 ===============
507 */
508 static void CL_SoundIndexList_f(void)
509 {
510         int i = 1;
511
512         while(cl.sound_precache[i] && i != MAX_SOUNDS)
513         { // Valid Sound
514                 Con_Printf("%i : %s\n", i, cl.sound_precache[i]->name);
515                 i++;
516         }
517 }
518
519 /*
520 ===============
521 CL_UpdateRenderEntity
522
523 Updates inversematrix, animation interpolation factors, scale, and mins/maxs
524 ===============
525 */
526 void CL_UpdateRenderEntity(entity_render_t *ent)
527 {
528         vec3_t org;
529         vec_t scale;
530         dp_model_t *model = ent->model;
531         // update the inverse matrix for the renderer
532         Matrix4x4_Invert_Simple(&ent->inversematrix, &ent->matrix);
533         // update the animation blend state
534         VM_FrameBlendFromFrameGroupBlend(ent->frameblend, ent->framegroupblend, ent->model);
535         // we need the matrix origin to center the box
536         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
537         // update entity->render.scale because the renderer needs it
538         ent->scale = scale = Matrix4x4_ScaleFromMatrix(&ent->matrix);
539         if (model)
540         {
541                 // NOTE: this directly extracts vector components from the matrix, which relies on the matrix orientation!
542 #ifdef MATRIX4x4_OPENGLORIENTATION
543                 if (ent->matrix.m[0][2] != 0 || ent->matrix.m[1][2] != 0)
544 #else
545                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
546 #endif
547                 {
548                         // pitch or roll
549                         VectorMA(org, scale, model->rotatedmins, ent->mins);
550                         VectorMA(org, scale, model->rotatedmaxs, ent->maxs);
551                 }
552 #ifdef MATRIX4x4_OPENGLORIENTATION
553                 else if (ent->matrix.m[1][0] != 0 || ent->matrix.m[0][1] != 0)
554 #else
555                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
556 #endif
557                 {
558                         // yaw
559                         VectorMA(org, scale, model->yawmins, ent->mins);
560                         VectorMA(org, scale, model->yawmaxs, ent->maxs);
561                 }
562                 else
563                 {
564                         VectorMA(org, scale, model->normalmins, ent->mins);
565                         VectorMA(org, scale, model->normalmaxs, ent->maxs);
566                 }
567         }
568         else
569         {
570                 ent->mins[0] = org[0] - 16;
571                 ent->mins[1] = org[1] - 16;
572                 ent->mins[2] = org[2] - 16;
573                 ent->maxs[0] = org[0] + 16;
574                 ent->maxs[1] = org[1] + 16;
575                 ent->maxs[2] = org[2] + 16;
576         }
577 }
578
579 /*
580 ===============
581 CL_LerpPoint
582
583 Determines the fraction between the last two messages that the objects
584 should be put at.
585 ===============
586 */
587 static float CL_LerpPoint(void)
588 {
589         float f;
590
591         if (cl_nettimesyncboundmode.integer == 1)
592                 cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
593
594         // LordHavoc: lerp in listen games as the server is being capped below the client (usually)
595         if (cl.mtime[0] <= cl.mtime[1])
596         {
597                 cl.time = cl.mtime[0];
598                 return 1;
599         }
600
601         f = (cl.time - cl.mtime[1]) / (cl.mtime[0] - cl.mtime[1]);
602         return bound(0, f, 1);
603 }
604
605 void CL_ClearTempEntities (void)
606 {
607         r_refdef.scene.numtempentities = 0;
608 }
609
610 entity_render_t *CL_NewTempEntity(double shadertime)
611 {
612         entity_render_t *render;
613
614         if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
615                 return NULL;
616         if (r_refdef.scene.numtempentities >= r_refdef.scene.maxtempentities)
617                 return NULL;
618         render = &r_refdef.scene.tempentities[r_refdef.scene.numtempentities++];
619         memset (render, 0, sizeof(*render));
620         r_refdef.scene.entities[r_refdef.scene.numentities++] = render;
621
622         render->shadertime = shadertime;
623         render->alpha = 1;
624         VectorSet(render->colormod, 1, 1, 1);
625         VectorSet(render->glowmod, 1, 1, 1);
626         return render;
627 }
628
629 void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate)
630 {
631         int i;
632         cl_effect_t *e;
633         if (!modelindex) // sanity check
634                 return;
635         if (framerate < 1)
636         {
637                 Con_Printf("CL_Effect: framerate %f is < 1\n", framerate);
638                 return;
639         }
640         if (framecount < 1)
641         {
642                 Con_Printf("CL_Effect: framecount %i is < 1\n", framecount);
643                 return;
644         }
645         for (i = 0, e = cl.effects;i < cl.max_effects;i++, e++)
646         {
647                 if (e->active)
648                         continue;
649                 e->active = true;
650                 VectorCopy(org, e->origin);
651                 e->modelindex = modelindex;
652                 e->starttime = cl.time;
653                 e->startframe = startframe;
654                 e->endframe = startframe + framecount;
655                 e->framerate = framerate;
656
657                 e->frame = 0;
658                 e->frame1time = cl.time;
659                 e->frame2time = cl.time;
660                 cl.num_effects = max(cl.num_effects, i + 1);
661                 break;
662         }
663 }
664
665 void CL_AllocLightFlash(entity_render_t *ent, matrix4x4_t *matrix, float radius, float red, float green, float blue, float decay, float lifetime, int cubemapnum, int style, int shadowenable, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags)
666 {
667         int i;
668         dlight_t *dl;
669
670 // then look for anything else
671         dl = cl.dlights;
672         for (i = 0;i < cl.max_dlights;i++, dl++)
673                 if (!dl->radius)
674                         break;
675
676         // unable to find one
677         if (i == cl.max_dlights)
678                 return;
679
680         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
681         memset (dl, 0, sizeof(*dl));
682         cl.num_dlights = max(cl.num_dlights, i + 1);
683         Matrix4x4_Normalize(&dl->matrix, matrix);
684         dl->ent = ent;
685         Matrix4x4_OriginFromMatrix(&dl->matrix, dl->origin);
686         CL_FindNonSolidLocation(dl->origin, dl->origin, 6);
687         Matrix4x4_SetOrigin(&dl->matrix, dl->origin[0], dl->origin[1], dl->origin[2]);
688         dl->radius = radius;
689         dl->color[0] = red;
690         dl->color[1] = green;
691         dl->color[2] = blue;
692         dl->initialradius = radius;
693         dl->initialcolor[0] = red;
694         dl->initialcolor[1] = green;
695         dl->initialcolor[2] = blue;
696         dl->decay = decay / radius; // changed decay to be a percentage decrease
697         dl->intensity = 1; // this is what gets decayed
698         if (lifetime)
699                 dl->die = cl.time + lifetime;
700         else
701                 dl->die = 0;
702         if (cubemapnum > 0)
703                 dpsnprintf(dl->cubemapname, sizeof(dl->cubemapname), "cubemaps/%i", cubemapnum);
704         else
705                 dl->cubemapname[0] = 0;
706         dl->style = style;
707         dl->shadow = shadowenable;
708         dl->corona = corona;
709         dl->flags = flags;
710         dl->coronasizescale = coronasizescale;
711         dl->ambientscale = ambientscale;
712         dl->diffusescale = diffusescale;
713         dl->specularscale = specularscale;
714 }
715
716 void CL_DecayLightFlashes(void)
717 {
718         int i, oldmax;
719         dlight_t *dl;
720         float time;
721
722         time = bound(0, cl.time - cl.oldtime, 0.1);
723         oldmax = cl.num_dlights;
724         cl.num_dlights = 0;
725         for (i = 0, dl = cl.dlights;i < oldmax;i++, dl++)
726         {
727                 if (dl->radius)
728                 {
729                         dl->intensity -= time * dl->decay;
730                         if (cl.time < dl->die && dl->intensity > 0)
731                         {
732                                 if (cl_dlights_decayradius.integer)
733                                         dl->radius = dl->initialradius * dl->intensity;
734                                 else
735                                         dl->radius = dl->initialradius;
736                                 if (cl_dlights_decaybrightness.integer)
737                                         VectorScale(dl->initialcolor, dl->intensity, dl->color);
738                                 else
739                                         VectorCopy(dl->initialcolor, dl->color);
740                                 cl.num_dlights = i + 1;
741                         }
742                         else
743                                 dl->radius = 0;
744                 }
745         }
746 }
747
748 // called before entity relinking
749 void CL_RelinkLightFlashes(void)
750 {
751         int i, j, k, l;
752         dlight_t *dl;
753         float frac, f;
754         matrix4x4_t tempmatrix;
755
756         if (r_dynamic.integer)
757         {
758                 for (i = 0, dl = cl.dlights;i < cl.num_dlights && r_refdef.scene.numlights < MAX_DLIGHTS;i++, dl++)
759                 {
760                         if (dl->radius)
761                         {
762                                 tempmatrix = dl->matrix;
763                                 Matrix4x4_Scale(&tempmatrix, dl->radius, 1);
764                                 // we need the corona fading to be persistent
765                                 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);
766                                 r_refdef.scene.lights[r_refdef.scene.numlights++] = &dl->rtlight;
767                         }
768                 }
769         }
770
771         if (!cl.lightstyle)
772         {
773                 for (j = 0;j < cl.max_lightstyle;j++)
774                 {
775                         r_refdef.scene.rtlightstylevalue[j] = 1;
776                         r_refdef.scene.lightstylevalue[j] = 256;
777                 }
778                 return;
779         }
780
781 // light animations
782 // 'm' is normal light, 'a' is no light, 'z' is double bright
783         f = cl.time * 10;
784         i = (int)floor(f);
785         frac = f - i;
786         for (j = 0;j < cl.max_lightstyle;j++)
787         {
788                 if (!cl.lightstyle[j].length)
789                 {
790                         r_refdef.scene.rtlightstylevalue[j] = 1;
791                         r_refdef.scene.lightstylevalue[j] = 256;
792                         continue;
793                 }
794                 // static lightstyle "=value"
795                 if (cl.lightstyle[j].map[0] == '=')
796                 {
797                         r_refdef.scene.rtlightstylevalue[j] = atof(cl.lightstyle[j].map + 1);
798                         if ( r_lerplightstyles.integer || ((int)f - f) < 0.01)
799                                 r_refdef.scene.lightstylevalue[j] = r_refdef.scene.rtlightstylevalue[j];
800                         continue;
801                 }
802                 k = i % cl.lightstyle[j].length;
803                 l = (i-1) % cl.lightstyle[j].length;
804                 k = cl.lightstyle[j].map[k] - 'a';
805                 l = cl.lightstyle[j].map[l] - 'a';
806                 // rtlightstylevalue is always interpolated because it has no bad
807                 // consequences for performance
808                 // lightstylevalue is subject to a cvar for performance reasons;
809                 // skipping lightmap updates on most rendered frames substantially
810                 // improves framerates (but makes light fades look bad)
811                 r_refdef.scene.rtlightstylevalue[j] = ((k*frac)+(l*(1-frac)))*(22/256.0f);
812                 r_refdef.scene.lightstylevalue[j] = r_lerplightstyles.integer ? (unsigned short)(((k*frac)+(l*(1-frac)))*22) : k*22;
813         }
814 }
815
816 void CL_AddQWCTFFlagModel(entity_t *player, int skin)
817 {
818         int frame = player->render.framegroupblend[0].frame;
819         float f;
820         entity_render_t *flagrender;
821         matrix4x4_t flagmatrix;
822
823         // this code taken from QuakeWorld
824         f = 14;
825         if (frame >= 29 && frame <= 40)
826         {
827                 if (frame >= 29 && frame <= 34)
828                 { //axpain
829                         if      (frame == 29) f = f + 2;
830                         else if (frame == 30) f = f + 8;
831                         else if (frame == 31) f = f + 12;
832                         else if (frame == 32) f = f + 11;
833                         else if (frame == 33) f = f + 10;
834                         else if (frame == 34) f = f + 4;
835                 }
836                 else if (frame >= 35 && frame <= 40)
837                 { // pain
838                         if      (frame == 35) f = f + 2;
839                         else if (frame == 36) f = f + 10;
840                         else if (frame == 37) f = f + 10;
841                         else if (frame == 38) f = f + 8;
842                         else if (frame == 39) f = f + 4;
843                         else if (frame == 40) f = f + 2;
844                 }
845         }
846         else if (frame >= 103 && frame <= 118)
847         {
848                 if      (frame >= 103 && frame <= 104) f = f + 6;  //nailattack
849                 else if (frame >= 105 && frame <= 106) f = f + 6;  //light
850                 else if (frame >= 107 && frame <= 112) f = f + 7;  //rocketattack
851                 else if (frame >= 112 && frame <= 118) f = f + 7;  //shotattack
852         }
853         // end of code taken from QuakeWorld
854
855         flagrender = CL_NewTempEntity(player->render.shadertime);
856         if (!flagrender)
857                 return;
858
859         flagrender->model = CL_GetModelByIndex(cl.qw_modelindex_flag);
860         flagrender->skinnum = skin;
861         flagrender->alpha = 1;
862         VectorSet(flagrender->colormod, 1, 1, 1);
863         VectorSet(flagrender->glowmod, 1, 1, 1);
864         // attach the flag to the player matrix
865         Matrix4x4_CreateFromQuakeEntity(&flagmatrix, -f, -22, 0, 0, 0, -45, 1);
866         Matrix4x4_Concat(&flagrender->matrix, &player->render.matrix, &flagmatrix);
867         CL_UpdateRenderEntity(flagrender);
868 }
869
870 matrix4x4_t viewmodelmatrix;
871
872 static const vec3_t muzzleflashorigin = {18, 0, 0};
873
874 extern void V_DriftPitch(void);
875 extern void V_FadeViewFlashs(void);
876 extern void V_CalcViewBlend(void);
877 extern void V_CalcRefdef(void);
878
879 void CL_SetEntityColormapColors(entity_render_t *ent, int colormap)
880 {
881         const unsigned char *cbcolor;
882         if (colormap >= 0)
883         {
884                 cbcolor = palette_rgb_pantscolormap[colormap & 0xF];
885                 VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_pantscolor);
886                 cbcolor = palette_rgb_shirtcolormap[(colormap & 0xF0) >> 4];
887                 VectorScale(cbcolor, (1.0f / 255.0f), ent->colormap_shirtcolor);
888         }
889         else
890         {
891                 VectorClear(ent->colormap_pantscolor);
892                 VectorClear(ent->colormap_shirtcolor);
893         }
894 }
895
896 // note this is a recursive function, recursionlimit should be 32 or so on the initial call
897 void CL_UpdateNetworkEntity(entity_t *e, int recursionlimit, qboolean interpolate)
898 {
899         const matrix4x4_t *matrix;
900         matrix4x4_t blendmatrix, tempmatrix, matrix2;
901         int frame;
902         float origin[3], angles[3], lerp;
903         entity_t *t;
904         //entity_persistent_t *p = &e->persistent;
905         //entity_render_t *r = &e->render;
906         // skip inactive entities and world
907         if (!e->state_current.active || e == cl.entities)
908                 return;
909         if (recursionlimit < 1)
910                 return;
911         e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
912         e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
913         e->render.flags = e->state_current.flags;
914         e->render.effects = e->state_current.effects;
915         VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod);
916         VectorScale(e->state_current.glowmod, (1.0f / 32.0f), e->render.glowmod);
917         if(e >= cl.entities && e < cl.entities + cl.num_entities)
918                 e->render.entitynumber = e - cl.entities;
919         else
920                 e->render.entitynumber = 0;
921         if (e->state_current.flags & RENDER_COLORMAPPED)
922                 CL_SetEntityColormapColors(&e->render, e->state_current.colormap);
923         else if (e->state_current.colormap > 0 && e->state_current.colormap <= cl.maxclients && cl.scores != NULL)
924                 CL_SetEntityColormapColors(&e->render, cl.scores[e->state_current.colormap-1].colors);
925         else
926                 CL_SetEntityColormapColors(&e->render, -1);
927         e->render.skinnum = e->state_current.skin;
928         if (e->state_current.tagentity)
929         {
930                 // attached entity (gun held in player model's hand, etc)
931                 // if the tag entity is currently impossible, skip it
932                 if (e->state_current.tagentity >= cl.num_entities)
933                         return;
934                 t = cl.entities + e->state_current.tagentity;
935                 // if the tag entity is inactive, skip it
936                 if (!t->state_current.active)
937                         return;
938                 // update the parent first
939                 CL_UpdateNetworkEntity(t, recursionlimit - 1, interpolate);
940                 // make relative to the entity
941                 matrix = &t->render.matrix;
942                 // some properties of the tag entity carry over
943                 e->render.flags |= t->render.flags & (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL);
944                 // if a valid tagindex is used, make it relative to that tag instead
945                 // FIXME: use a model function to get tag info (need to handle skeletal)
946                 if (e->state_current.tagentity && e->state_current.tagindex >= 1 && t->render.model)
947                 {
948                         if(!Mod_Alias_GetTagMatrix(t->render.model, t->render.frameblend, t->render.skeleton, e->state_current.tagindex - 1, &blendmatrix)) // i.e. no error
949                         {
950                                 // concat the tag matrices onto the entity matrix
951                                 Matrix4x4_Concat(&tempmatrix, &t->render.matrix, &blendmatrix);
952                                 // use the constructed tag matrix
953                                 matrix = &tempmatrix;
954                         }
955                 }
956         }
957         else if (e->render.flags & RENDER_VIEWMODEL)
958         {
959                 // view-relative entity (guns and such)
960                 if (e->render.effects & EF_NOGUNBOB)
961                         matrix = &r_refdef.view.matrix; // really attached to view
962                 else
963                         matrix = &viewmodelmatrix; // attached to gun bob matrix
964         }
965         else
966         {
967                 // world-relative entity (the normal kind)
968                 matrix = &identitymatrix;
969         }
970
971         // movement lerp
972         // if it's the predicted player entity, update according to client movement
973         // but don't lerp if going through a teleporter as it causes a bad lerp
974         // also don't use the predicted location if fixangle was set on both of
975         // the most recent server messages, as that cause means you are spectating
976         // someone or watching a cutscene of some sort
977         if (cl_nolerp.integer || cls.timedemo)
978                 interpolate = false;
979         if (e == cl.entities + cl.playerentity && cl.movement_predicted && (!cl.fixangle[1] || !cl.fixangle[0]))
980         {
981                 VectorCopy(cl.movement_origin, origin);
982                 VectorSet(angles, 0, cl.viewangles[1], 0);
983         }
984         else if (interpolate && e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1)
985         {
986                 // interpolate the origin and angles
987                 lerp = max(0, lerp);
988                 VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin);
989 #if 0
990                 // this fails at the singularity of euler angles
991                 VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta);
992                 if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
993                 if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
994                 if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
995                 VectorMA(e->persistent.oldangles, lerp, delta, angles);
996 #else
997                 {
998                         vec3_t f0, u0, f1, u1;
999                         AngleVectors(e->persistent.oldangles, f0, NULL, u0);
1000                         AngleVectors(e->persistent.newangles, f1, NULL, u1);
1001                         VectorMAM(1-lerp, f0, lerp, f1, f0);
1002                         VectorMAM(1-lerp, u0, lerp, u1, u0);
1003                         AnglesFromVectors(angles, f0, u0, false);
1004                 }
1005 #endif
1006         }
1007         else
1008         {
1009                 // no interpolation
1010                 VectorCopy(e->persistent.neworigin, origin);
1011                 VectorCopy(e->persistent.newangles, angles);
1012         }
1013
1014         // model setup and some modelflags
1015         frame = e->state_current.frame;
1016         e->render.model = CL_GetModelByIndex(e->state_current.modelindex);
1017         if (e->render.model)
1018         {
1019                 if (e->render.skinnum >= e->render.model->numskins)
1020                         e->render.skinnum = 0;
1021                 if (frame >= e->render.model->numframes)
1022                         frame = 0;
1023                 // models can set flags such as EF_ROCKET
1024                 // this 0xFF800000 mask is EF_NOMODELFLAGS plus all the higher EF_ flags such as EF_ROCKET
1025                 if (!(e->render.effects & 0xFF800000))
1026                         e->render.effects |= e->render.model->effects;
1027                 // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
1028                 if (e->render.model->type == mod_alias)
1029                         angles[0] = -angles[0];
1030                 if ((e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number)
1031                 {
1032                         VectorScale(e->render.colormod, 2, e->render.colormod);
1033                         VectorScale(e->render.glowmod, 2, e->render.glowmod);
1034                 }
1035         }
1036         // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
1037         else if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC)
1038                 angles[0] = -angles[0];
1039                 // NOTE: this must be synced to SV_GetPitchSign!
1040
1041         if ((e->render.effects & EF_ROTATE) && !(e->render.flags & RENDER_VIEWMODEL))
1042         {
1043                 angles[1] = ANGLEMOD(100*cl.time);
1044                 if (cl_itembobheight.value)
1045                         origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
1046         }
1047
1048         // animation lerp
1049         if (e->render.framegroupblend[0].frame == frame)
1050         {
1051                 // update frame lerp fraction
1052                 e->render.framegroupblend[0].lerp = 1;
1053                 e->render.framegroupblend[1].lerp = 0;
1054                 if (e->render.framegroupblend[0].start > e->render.framegroupblend[1].start)
1055                 {
1056                         // make sure frame lerp won't last longer than 100ms
1057                         // (this mainly helps with models that use framegroups and
1058                         // switch between them infrequently)
1059                         e->render.framegroupblend[0].lerp = (cl.time - e->render.framegroupblend[0].start) / min(e->render.framegroupblend[0].start - e->render.framegroupblend[1].start, 0.1);
1060                         e->render.framegroupblend[0].lerp = bound(0, e->render.framegroupblend[0].lerp, 1);
1061                         e->render.framegroupblend[1].lerp = 1 - e->render.framegroupblend[0].lerp;
1062                 }
1063         }
1064         else
1065         {
1066                 // begin a new frame lerp
1067                 e->render.framegroupblend[1] = e->render.framegroupblend[0];
1068                 e->render.framegroupblend[1].lerp = 1;
1069                 e->render.framegroupblend[0].frame = frame;
1070                 e->render.framegroupblend[0].start = cl.time;
1071                 e->render.framegroupblend[0].lerp = 0;
1072         }
1073
1074         // set up the render matrix
1075         if (matrix)
1076         {
1077                 // attached entity, this requires a matrix multiply (concat)
1078                 // FIXME: e->render.scale should go away
1079                 Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
1080                 // concat the matrices to make the entity relative to its tag
1081                 Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2);
1082                 // get the origin from the new matrix
1083                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1084         }
1085         else
1086         {
1087                 // unattached entities are faster to process
1088                 Matrix4x4_CreateFromQuakeEntity(&e->render.matrix, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
1089         }
1090
1091         // tenebrae's sprites are all additive mode (weird)
1092         if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite)
1093                 e->render.flags |= RENDER_ADDITIVE;
1094         // player model is only shown with chase_active on
1095         if (e->state_current.number == cl.viewentity)
1096                 e->render.flags |= RENDER_EXTERIORMODEL;
1097         // either fullbright or lit
1098         if(!r_fullbright.integer)
1099         {
1100                 if (!(e->render.effects & EF_FULLBRIGHT))
1101                         e->render.flags |= RENDER_LIGHT;
1102                 else if(r_equalize_entities_fullbright.integer)
1103                         e->render.flags |= RENDER_LIGHT | RENDER_EQUALIZE;
1104         }
1105         // hide player shadow during intermission or nehahra movie
1106         if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
1107          && (e->render.alpha >= 1)
1108          && !(e->render.flags & RENDER_VIEWMODEL)
1109          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
1110                 e->render.flags |= RENDER_SHADOW;
1111         if (e->render.flags & RENDER_VIEWMODEL)
1112                 e->render.flags |= RENDER_NOSELFSHADOW;
1113         if (e->render.effects & EF_NOSELFSHADOW)
1114                 e->render.flags |= RENDER_NOSELFSHADOW;
1115         if (e->render.effects & EF_NODEPTHTEST)
1116                 e->render.flags |= RENDER_NODEPTHTEST;
1117         if (e->render.effects & EF_ADDITIVE)
1118                 e->render.flags |= RENDER_ADDITIVE;
1119         if (e->render.effects & EF_DOUBLESIDED)
1120                 e->render.flags |= RENDER_DOUBLESIDED;
1121
1122         // make the other useful stuff
1123         e->render.allowdecals = true;
1124         CL_UpdateRenderEntity(&e->render);
1125 }
1126
1127 // creates light and trails from an entity
1128 void CL_UpdateNetworkEntityTrail(entity_t *e)
1129 {
1130         effectnameindex_t trailtype;
1131         vec3_t origin;
1132
1133         // bmodels are treated specially since their origin is usually '0 0 0' and
1134         // their actual geometry is far from '0 0 0'
1135         if (e->render.model && e->render.model->soundfromcenter)
1136         {
1137                 vec3_t o;
1138                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1139                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1140         }
1141         else
1142                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1143
1144         // handle particle trails and such effects now that we know where this
1145         // entity is in the world...
1146         trailtype = EFFECT_NONE;
1147         // LordHavoc: if the entity has no effects, don't check each
1148         if (e->render.effects & (EF_BRIGHTFIELD | EF_FLAME | EF_STARDUST))
1149         {
1150                 if (e->render.effects & EF_BRIGHTFIELD)
1151                 {
1152                         if (gamemode == GAME_NEXUIZ)
1153                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1154                         else
1155                                 CL_EntityParticles(e);
1156                 }
1157                 if (e->render.effects & EF_FLAME)
1158                         CL_ParticleTrail(EFFECT_EF_FLAME, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true);
1159                 if (e->render.effects & EF_STARDUST)
1160                         CL_ParticleTrail(EFFECT_EF_STARDUST, bound(0, cl.time - cl.oldtime, 0.1), origin, origin, vec3_origin, vec3_origin, NULL, 0, false, true);
1161         }
1162         if (e->render.internaleffects & (INTEF_FLAG1QW | INTEF_FLAG2QW))
1163         {
1164                 // these are only set on player entities
1165                 CL_AddQWCTFFlagModel(e, (e->render.internaleffects & INTEF_FLAG2QW) != 0);
1166         }
1167         // muzzleflash fades over time
1168         if (e->persistent.muzzleflash > 0)
1169                 e->persistent.muzzleflash -= bound(0, cl.time - cl.oldtime, 0.1) * 20;
1170         // LordHavoc: if the entity has no effects, don't check each
1171         if (e->render.effects && !(e->render.flags & RENDER_VIEWMODEL))
1172         {
1173                 if (e->render.effects & EF_GIB)
1174                         trailtype = EFFECT_TR_BLOOD;
1175                 else if (e->render.effects & EF_ZOMGIB)
1176                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1177                 else if (e->render.effects & EF_TRACER)
1178                         trailtype = EFFECT_TR_WIZSPIKE;
1179                 else if (e->render.effects & EF_TRACER2)
1180                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1181                 else if (e->render.effects & EF_ROCKET)
1182                         trailtype = EFFECT_TR_ROCKET;
1183                 else if (e->render.effects & EF_GRENADE)
1184                 {
1185                         // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1186                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1187                 }
1188                 else if (e->render.effects & EF_TRACER3)
1189                         trailtype = EFFECT_TR_VORESPIKE;
1190         }
1191         // do trails
1192         if (e->render.flags & RENDER_GLOWTRAIL)
1193                 trailtype = EFFECT_TR_GLOWTRAIL;
1194         // check if a trail is allowed (it is not after a teleport for example)
1195         if (trailtype && e->persistent.trail_allowed)
1196         {
1197                 float len;
1198                 vec3_t vel;
1199                 VectorSubtract(e->state_current.origin, e->state_previous.origin, vel);
1200                 len = e->state_current.time - e->state_previous.time;
1201                 if (len > 0)
1202                         len = 1.0f / len;
1203                 VectorScale(vel, len, vel);
1204                 CL_ParticleTrail(trailtype, 1, e->persistent.trail_origin, origin, vel, vel, e, e->state_current.glowcolor, false, true);
1205         }
1206         // now that the entity has survived one trail update it is allowed to
1207         // leave a real trail on later frames
1208         e->persistent.trail_allowed = true;
1209         VectorCopy(origin, e->persistent.trail_origin);
1210 }
1211
1212
1213 /*
1214 ===============
1215 CL_UpdateViewEntities
1216 ===============
1217 */
1218 void CL_UpdateViewEntities(void)
1219 {
1220         int i;
1221         // update any RENDER_VIEWMODEL entities to use the new view matrix
1222         for (i = 1;i < cl.num_entities;i++)
1223         {
1224                 if (cl.entities_active[i])
1225                 {
1226                         entity_t *ent = cl.entities + i;
1227                         if ((ent->render.flags & RENDER_VIEWMODEL) || ent->state_current.tagentity)
1228                                 CL_UpdateNetworkEntity(ent, 32, true);
1229                 }
1230         }
1231         // and of course the engine viewmodel needs updating as well
1232         CL_UpdateNetworkEntity(&cl.viewent, 32, true);
1233 }
1234
1235 /*
1236 ===============
1237 CL_UpdateNetworkCollisionEntities
1238 ===============
1239 */
1240 void CL_UpdateNetworkCollisionEntities(void)
1241 {
1242         entity_t *ent;
1243         int i;
1244
1245         // start on the entity after the world
1246         cl.num_brushmodel_entities = 0;
1247         for (i = cl.maxclients + 1;i < cl.num_entities;i++)
1248         {
1249                 if (cl.entities_active[i])
1250                 {
1251                         ent = cl.entities + i;
1252                         if (ent->state_current.active && ent->render.model && ent->render.model->name[0] == '*' && ent->render.model->TraceBox)
1253                         {
1254                                 // do not interpolate the bmodels for this
1255                                 CL_UpdateNetworkEntity(ent, 32, false);
1256                                 cl.brushmodel_entities[cl.num_brushmodel_entities++] = i;
1257                         }
1258                 }
1259         }
1260 }
1261
1262 extern void R_DecalSystem_Reset(decalsystem_t *decalsystem);
1263
1264 /*
1265 ===============
1266 CL_UpdateNetworkEntities
1267 ===============
1268 */
1269 void CL_UpdateNetworkEntities(void)
1270 {
1271         entity_t *ent;
1272         int i;
1273
1274         // start on the entity after the world
1275         for (i = 1;i < cl.num_entities;i++)
1276         {
1277                 if (cl.entities_active[i])
1278                 {
1279                         ent = cl.entities + i;
1280                         if (ent->state_current.active)
1281                         {
1282                                 CL_UpdateNetworkEntity(ent, 32, true);
1283                                 // view models should never create light/trails
1284                                 if (!(ent->render.flags & RENDER_VIEWMODEL))
1285                                         CL_UpdateNetworkEntityTrail(ent);
1286                         }
1287                         else
1288                         {
1289                                 R_DecalSystem_Reset(&ent->render.decalsystem);
1290                                 cl.entities_active[i] = false;
1291                         }
1292                 }
1293         }
1294 }
1295
1296 void CL_UpdateViewModel(void)
1297 {
1298         entity_t *ent;
1299         ent = &cl.viewent;
1300         ent->state_previous = ent->state_current;
1301         ent->state_current = defaultstate;
1302         ent->state_current.time = cl.time;
1303         ent->state_current.number = (unsigned short)-1;
1304         ent->state_current.active = true;
1305         ent->state_current.modelindex = cl.stats[STAT_WEAPON];
1306         ent->state_current.frame = cl.stats[STAT_WEAPONFRAME];
1307         ent->state_current.flags = RENDER_VIEWMODEL;
1308         if ((cl.stats[STAT_HEALTH] <= 0 && cl_deathnoviewmodel.integer) || cl.intermission)
1309                 ent->state_current.modelindex = 0;
1310         else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1311         {
1312                 if (gamemode == GAME_TRANSFUSION)
1313                         ent->state_current.alpha = 128;
1314                 else
1315                         ent->state_current.modelindex = 0;
1316         }
1317         ent->state_current.alpha = cl.entities[cl.viewentity].state_current.alpha;
1318         ent->state_current.effects = EF_NOSHADOW | (cl.entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_FULLBRIGHT | EF_NODEPTHTEST | EF_NOGUNBOB));
1319
1320         // reset animation interpolation on weaponmodel if model changed
1321         if (ent->state_previous.modelindex != ent->state_current.modelindex)
1322         {
1323                 ent->render.framegroupblend[0].frame = ent->render.framegroupblend[1].frame = ent->state_current.frame;
1324                 ent->render.framegroupblend[0].start = ent->render.framegroupblend[1].start = cl.time;
1325                 ent->render.framegroupblend[0].lerp = 1;ent->render.framegroupblend[1].lerp = 0;
1326         }
1327         CL_UpdateNetworkEntity(ent, 32, true);
1328 }
1329
1330 // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags)
1331 void CL_LinkNetworkEntity(entity_t *e)
1332 {
1333         effectnameindex_t trailtype;
1334         vec3_t origin;
1335         vec3_t dlightcolor;
1336         vec_t dlightradius;
1337
1338         // skip inactive entities and world
1339         if (!e->state_current.active || e == cl.entities)
1340                 return;
1341         if (e->state_current.tagentity)
1342         {
1343                 // if the tag entity is currently impossible, skip it
1344                 if (e->state_current.tagentity >= cl.num_entities)
1345                         return;
1346                 // if the tag entity is inactive, skip it
1347                 if (!cl.entities[e->state_current.tagentity].state_current.active)
1348                         return;
1349         }
1350
1351         // create entity dlights associated with this entity
1352         if (e->render.model && e->render.model->soundfromcenter)
1353         {
1354                 // bmodels are treated specially since their origin is usually '0 0 0'
1355                 vec3_t o;
1356                 VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
1357                 Matrix4x4_Transform(&e->render.matrix, o, origin);
1358         }
1359         else
1360                 Matrix4x4_OriginFromMatrix(&e->render.matrix, origin);
1361         trailtype = EFFECT_NONE;
1362         dlightradius = 0;
1363         dlightcolor[0] = 0;
1364         dlightcolor[1] = 0;
1365         dlightcolor[2] = 0;
1366         // LordHavoc: if the entity has no effects, don't check each
1367         if (e->render.effects & (EF_BRIGHTFIELD | EF_DIMLIGHT | EF_BRIGHTLIGHT | EF_RED | EF_BLUE | EF_FLAME | EF_STARDUST))
1368         {
1369                 if (e->render.effects & EF_BRIGHTFIELD)
1370                 {
1371                         if (gamemode == GAME_NEXUIZ)
1372                                 trailtype = EFFECT_TR_NEXUIZPLASMA;
1373                 }
1374                 if (e->render.effects & EF_DIMLIGHT)
1375                 {
1376                         dlightradius = max(dlightradius, 200);
1377                         dlightcolor[0] += 1.50f;
1378                         dlightcolor[1] += 1.50f;
1379                         dlightcolor[2] += 1.50f;
1380                 }
1381                 if (e->render.effects & EF_BRIGHTLIGHT)
1382                 {
1383                         dlightradius = max(dlightradius, 400);
1384                         dlightcolor[0] += 3.00f;
1385                         dlightcolor[1] += 3.00f;
1386                         dlightcolor[2] += 3.00f;
1387                 }
1388                 // LordHavoc: more effects
1389                 if (e->render.effects & EF_RED) // red
1390                 {
1391                         dlightradius = max(dlightradius, 200);
1392                         dlightcolor[0] += 1.50f;
1393                         dlightcolor[1] += 0.15f;
1394                         dlightcolor[2] += 0.15f;
1395                 }
1396                 if (e->render.effects & EF_BLUE) // blue
1397                 {
1398                         dlightradius = max(dlightradius, 200);
1399                         dlightcolor[0] += 0.15f;
1400                         dlightcolor[1] += 0.15f;
1401                         dlightcolor[2] += 1.50f;
1402                 }
1403                 if (e->render.effects & EF_FLAME)
1404                         CL_ParticleTrail(EFFECT_EF_FLAME, 0, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false);
1405                 if (e->render.effects & EF_STARDUST)
1406                         CL_ParticleTrail(EFFECT_EF_STARDUST, 0, origin, origin, vec3_origin, vec3_origin, NULL, 0, true, false);
1407         }
1408         // muzzleflash fades over time, and is offset a bit
1409         if (e->persistent.muzzleflash > 0 && r_refdef.scene.numlights < MAX_DLIGHTS)
1410         {
1411                 vec3_t v2;
1412                 vec3_t color;
1413                 trace_t trace;
1414                 matrix4x4_t tempmatrix;
1415                 Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2);
1416                 trace = CL_TraceLine(origin, v2, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY, true, false, NULL, false);
1417                 Matrix4x4_Normalize(&tempmatrix, &e->render.matrix);
1418                 Matrix4x4_SetOrigin(&tempmatrix, trace.endpos[0], trace.endpos[1], trace.endpos[2]);
1419                 Matrix4x4_Scale(&tempmatrix, 150, 1);
1420                 VectorSet(color, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f, e->persistent.muzzleflash * 4.0f);
1421                 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);
1422                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1423         }
1424         // LordHavoc: if the model has no flags, don't check each
1425         if (e->render.model && e->render.effects && !(e->render.flags & RENDER_VIEWMODEL))
1426         {
1427                 if (e->render.effects & EF_GIB)
1428                         trailtype = EFFECT_TR_BLOOD;
1429                 else if (e->render.effects & EF_ZOMGIB)
1430                         trailtype = EFFECT_TR_SLIGHTBLOOD;
1431                 else if (e->render.effects & EF_TRACER)
1432                         trailtype = EFFECT_TR_WIZSPIKE;
1433                 else if (e->render.effects & EF_TRACER2)
1434                         trailtype = EFFECT_TR_KNIGHTSPIKE;
1435                 else if (e->render.effects & EF_ROCKET)
1436                         trailtype = EFFECT_TR_ROCKET;
1437                 else if (e->render.effects & EF_GRENADE)
1438                 {
1439                         // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
1440                         trailtype = e->render.alpha == -1 ? EFFECT_TR_NEHAHRASMOKE : EFFECT_TR_GRENADE;
1441                 }
1442                 else if (e->render.effects & EF_TRACER3)
1443                         trailtype = EFFECT_TR_VORESPIKE;
1444         }
1445         // LordHavoc: customizable glow
1446         if (e->state_current.glowsize)
1447         {
1448                 // * 4 for the expansion from 0-255 to 0-1023 range,
1449                 // / 255 to scale down byte colors
1450                 dlightradius = max(dlightradius, e->state_current.glowsize * 4);
1451                 VectorMA(dlightcolor, (1.0f / 255.0f), palette_rgb[e->state_current.glowcolor], dlightcolor);
1452         }
1453         // custom rtlight
1454         if ((e->state_current.lightpflags & PFLAGS_FULLDYNAMIC) && r_refdef.scene.numlights < MAX_DLIGHTS)
1455         {
1456                 matrix4x4_t dlightmatrix;
1457                 float light[4];
1458                 VectorScale(e->state_current.light, (1.0f / 256.0f), light);
1459                 light[3] = e->state_current.light[3];
1460                 if (light[0] == 0 && light[1] == 0 && light[2] == 0)
1461                         VectorSet(light, 1, 1, 1);
1462                 if (light[3] == 0)
1463                         light[3] = 350;
1464                 // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS?
1465                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1466                 Matrix4x4_Scale(&dlightmatrix, light[3], 1);
1467                 R_RTLight_Update(&r_refdef.scene.templights[r_refdef.scene.numlights], false, &dlightmatrix, light, e->state_current.lightstyle, e->state_current.skin > 0 ? va("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);
1468                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1469         }
1470         // make the glow dlight
1471         else if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL) && r_refdef.scene.numlights < MAX_DLIGHTS)
1472         {
1473                 matrix4x4_t dlightmatrix;
1474                 Matrix4x4_Normalize(&dlightmatrix, &e->render.matrix);
1475                 // hack to make glowing player light shine on their gun
1476                 //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/)
1477                 //      Matrix4x4_AdjustOrigin(&dlightmatrix, 0, 0, 30);
1478                 Matrix4x4_Scale(&dlightmatrix, dlightradius, 1);
1479                 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);
1480                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1481         }
1482         // do trail light
1483         if (e->render.flags & RENDER_GLOWTRAIL)
1484                 trailtype = EFFECT_TR_GLOWTRAIL;
1485         if (trailtype)
1486                 CL_ParticleTrail(trailtype, 0, origin, origin, vec3_origin, vec3_origin, NULL, e->state_current.glowcolor, true, false);
1487
1488         // don't show viewmodels in certain situations
1489         if (e->render.flags & RENDER_VIEWMODEL)
1490                 if (!r_drawviewmodel.integer || chase_active.integer || r_refdef.envmap)
1491                         return;
1492         // don't show entities with no modelindex (note: this still shows
1493         // entities which have a modelindex that resolved to a NULL model)
1494         if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.scene.numentities < r_refdef.scene.maxentities)
1495                 r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render;
1496         //if (cl.viewentity && e->state_current.number == cl.viewentity)
1497         //      Matrix4x4_Print(&e->render.matrix);
1498 }
1499
1500 void CL_RelinkWorld(void)
1501 {
1502         entity_t *ent = &cl.entities[0];
1503         // FIXME: this should be done at load
1504         ent->render.matrix = identitymatrix;
1505         ent->render.flags = RENDER_SHADOW;
1506         if (!r_fullbright.integer)
1507                 ent->render.flags |= RENDER_LIGHT;
1508         VectorSet(ent->render.colormod, 1, 1, 1);
1509         VectorSet(ent->render.glowmod, 1, 1, 1);
1510         ent->render.allowdecals = true;
1511         CL_UpdateRenderEntity(&ent->render);
1512         r_refdef.scene.worldentity = &ent->render;
1513         r_refdef.scene.worldmodel = cl.worldmodel;
1514 }
1515
1516 static void CL_RelinkStaticEntities(void)
1517 {
1518         int i;
1519         entity_t *e;
1520         for (i = 0, e = cl.static_entities;i < cl.num_static_entities && r_refdef.scene.numentities < r_refdef.scene.maxentities;i++, e++)
1521         {
1522                 e->render.flags = 0;
1523                 // if the model was not loaded when the static entity was created we
1524                 // need to re-fetch the model pointer
1525                 e->render.model = CL_GetModelByIndex(e->state_baseline.modelindex);
1526                 // either fullbright or lit
1527                 if(!r_fullbright.integer)
1528                 {
1529                         if (!(e->render.effects & EF_FULLBRIGHT))
1530                                 e->render.flags |= RENDER_LIGHT;
1531                         else if(r_equalize_entities_fullbright.integer)
1532                                 e->render.flags |= RENDER_LIGHT | RENDER_EQUALIZE;
1533                 }
1534                 // hide player shadow during intermission or nehahra movie
1535                 if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST)) && (e->render.alpha >= 1))
1536                         e->render.flags |= RENDER_SHADOW;
1537                 VectorSet(e->render.colormod, 1, 1, 1);
1538                 VectorSet(e->render.glowmod, 1, 1, 1);
1539                 VM_FrameBlendFromFrameGroupBlend(e->render.frameblend, e->render.framegroupblend, e->render.model);
1540                 e->render.allowdecals = true;
1541                 CL_UpdateRenderEntity(&e->render);
1542                 r_refdef.scene.entities[r_refdef.scene.numentities++] = &e->render;
1543         }
1544 }
1545
1546 /*
1547 ===============
1548 CL_RelinkEntities
1549 ===============
1550 */
1551 static void CL_RelinkNetworkEntities(void)
1552 {
1553         entity_t *ent;
1554         int i;
1555
1556         // start on the entity after the world
1557         for (i = 1;i < cl.num_entities;i++)
1558         {
1559                 if (cl.entities_active[i])
1560                 {
1561                         ent = cl.entities + i;
1562                         if (ent->state_current.active)
1563                                 CL_LinkNetworkEntity(ent);
1564                         else
1565                                 cl.entities_active[i] = false;
1566                 }
1567         }
1568 }
1569
1570 static void CL_RelinkEffects(void)
1571 {
1572         int i, intframe;
1573         cl_effect_t *e;
1574         entity_render_t *entrender;
1575         float frame;
1576
1577         for (i = 0, e = cl.effects;i < cl.num_effects;i++, e++)
1578         {
1579                 if (e->active)
1580                 {
1581                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
1582                         intframe = (int)frame;
1583                         if (intframe < 0 || intframe >= e->endframe)
1584                         {
1585                                 memset(e, 0, sizeof(*e));
1586                                 while (cl.num_effects > 0 && !cl.effects[cl.num_effects - 1].active)
1587                                         cl.num_effects--;
1588                                 continue;
1589                         }
1590
1591                         if (intframe != e->frame)
1592                         {
1593                                 e->frame = intframe;
1594                                 e->frame1time = e->frame2time;
1595                                 e->frame2time = cl.time;
1596                         }
1597
1598                         // if we're drawing effects, get a new temp entity
1599                         // (NewTempEntity adds it to the render entities list for us)
1600                         if (r_draweffects.integer && (entrender = CL_NewTempEntity(e->starttime)))
1601                         {
1602                                 // interpolation stuff
1603                                 entrender->framegroupblend[0].frame = intframe;
1604                                 entrender->framegroupblend[0].lerp = 1 - frame - intframe;
1605                                 entrender->framegroupblend[0].start = e->frame1time;
1606                                 if (intframe + 1 >= e->endframe)
1607                                 {
1608                                         entrender->framegroupblend[1].frame = 0; // disappear
1609                                         entrender->framegroupblend[1].lerp = 0;
1610                                         entrender->framegroupblend[1].start = 0;
1611                                 }
1612                                 else
1613                                 {
1614                                         entrender->framegroupblend[1].frame = intframe + 1;
1615                                         entrender->framegroupblend[1].lerp = frame - intframe;
1616                                         entrender->framegroupblend[1].start = e->frame2time;
1617                                 }
1618
1619                                 // normal stuff
1620                                 entrender->model = CL_GetModelByIndex(e->modelindex);
1621                                 entrender->alpha = 1;
1622                                 VectorSet(entrender->colormod, 1, 1, 1);
1623                                 VectorSet(entrender->glowmod, 1, 1, 1);
1624
1625                                 Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
1626                                 CL_UpdateRenderEntity(entrender);
1627                         }
1628                 }
1629         }
1630 }
1631
1632 void CL_Beam_CalculatePositions(const beam_t *b, vec3_t start, vec3_t end)
1633 {
1634         VectorCopy(b->start, start);
1635         VectorCopy(b->end, end);
1636
1637         // if coming from the player, update the start position
1638         if (b->entity == cl.viewentity)
1639         {
1640                 if (cl_beams_quakepositionhack.integer && !chase_active.integer)
1641                 {
1642                         // LordHavoc: this is a stupid hack from Quake that makes your
1643                         // lightning appear to come from your waist and cover less of your
1644                         // view
1645                         // in Quake this hack was applied to all players (causing the
1646                         // infamous crotch-lightning), but in darkplaces and QuakeWorld it
1647                         // only applies to your own lightning, and only in first person
1648                         Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, start);
1649                 }
1650                 if (cl_beams_instantaimhack.integer)
1651                 {
1652                         vec3_t dir, localend;
1653                         vec_t len;
1654                         // LordHavoc: this updates the beam direction to match your
1655                         // viewangles
1656                         VectorSubtract(end, start, dir);
1657                         len = VectorLength(dir);
1658                         VectorNormalize(dir);
1659                         VectorSet(localend, len, 0, 0);
1660                         Matrix4x4_Transform(&r_refdef.view.matrix, localend, end);
1661                 }
1662         }
1663 }
1664
1665 void CL_RelinkBeams(void)
1666 {
1667         int i;
1668         beam_t *b;
1669         vec3_t dist, org, start, end;
1670         float d;
1671         entity_render_t *entrender;
1672         double yaw, pitch;
1673         float forward;
1674         matrix4x4_t tempmatrix;
1675
1676         for (i = 0, b = cl.beams;i < cl.num_beams;i++, b++)
1677         {
1678                 if (!b->model)
1679                         continue;
1680                 if (b->endtime < cl.time)
1681                 {
1682                         b->model = NULL;
1683                         continue;
1684                 }
1685
1686                 CL_Beam_CalculatePositions(b, start, end);
1687
1688                 if (b->lightning)
1689                 {
1690                         if (cl_beams_lightatend.integer && r_refdef.scene.numlights < MAX_DLIGHTS)
1691                         {
1692                                 // FIXME: create a matrix from the beam start/end orientation
1693                                 vec3_t dlightcolor;
1694                                 VectorSet(dlightcolor, 0.3, 0.7, 1);
1695                                 Matrix4x4_CreateFromQuakeEntity(&tempmatrix, end[0], end[1], end[2], 0, 0, 0, 200);
1696                                 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);
1697                                 r_refdef.scene.lights[r_refdef.scene.numlights] = &r_refdef.scene.templights[r_refdef.scene.numlights++];
1698                         }
1699                         if (cl_beams_polygons.integer)
1700                                 continue;
1701                 }
1702
1703                 // calculate pitch and yaw
1704                 // (this is similar to the QuakeC builtin function vectoangles)
1705                 VectorSubtract(end, start, dist);
1706                 if (dist[1] == 0 && dist[0] == 0)
1707                 {
1708                         yaw = 0;
1709                         if (dist[2] > 0)
1710                                 pitch = 90;
1711                         else
1712                                 pitch = 270;
1713                 }
1714                 else
1715                 {
1716                         yaw = atan2(dist[1], dist[0]) * 180 / M_PI;
1717                         if (yaw < 0)
1718                                 yaw += 360;
1719
1720                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
1721                         pitch = atan2(dist[2], forward) * 180 / M_PI;
1722                         if (pitch < 0)
1723                                 pitch += 360;
1724                 }
1725
1726                 // add new entities for the lightning
1727                 VectorCopy (start, org);
1728                 d = VectorNormalizeLength(dist);
1729                 while (d > 0)
1730                 {
1731                         entrender = CL_NewTempEntity (0);
1732                         if (!entrender)
1733                                 return;
1734                         //VectorCopy (org, ent->render.origin);
1735                         entrender->model = b->model;
1736                         //ent->render.effects = EF_FULLBRIGHT;
1737                         //ent->render.angles[0] = pitch;
1738                         //ent->render.angles[1] = yaw;
1739                         //ent->render.angles[2] = rand()%360;
1740                         Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1741                         CL_UpdateRenderEntity(entrender);
1742                         VectorMA(org, 30, dist, org);
1743                         d -= 30;
1744                 }
1745         }
1746
1747         while (cl.num_beams > 0 && !cl.beams[cl.num_beams - 1].model)
1748                 cl.num_beams--;
1749 }
1750
1751 static void CL_RelinkQWNails(void)
1752 {
1753         int i;
1754         vec_t *v;
1755         entity_render_t *entrender;
1756
1757         for (i = 0;i < cl.qw_num_nails;i++)
1758         {
1759                 v = cl.qw_nails[i];
1760
1761                 // if we're drawing effects, get a new temp entity
1762                 // (NewTempEntity adds it to the render entities list for us)
1763                 if (!(entrender = CL_NewTempEntity(0)))
1764                         continue;
1765
1766                 // normal stuff
1767                 entrender->model = CL_GetModelByIndex(cl.qw_modelindex_spike);
1768                 entrender->alpha = 1;
1769                 VectorSet(entrender->colormod, 1, 1, 1);
1770                 VectorSet(entrender->glowmod, 1, 1, 1);
1771
1772                 Matrix4x4_CreateFromQuakeEntity(&entrender->matrix, v[0], v[1], v[2], v[3], v[4], v[5], 1);
1773                 CL_UpdateRenderEntity(entrender);
1774         }
1775 }
1776
1777 void CL_LerpPlayer(float frac)
1778 {
1779         int i;
1780
1781         cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]);
1782         for (i = 0;i < 3;i++)
1783         {
1784                 cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]);
1785                 cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]);
1786                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1787         }
1788
1789         // interpolate the angles if playing a demo or spectating someone
1790         if (cls.demoplayback || cl.fixangle[0])
1791         {
1792                 for (i = 0;i < 3;i++)
1793                 {
1794                         float d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1795                         if (d > 180)
1796                                 d -= 360;
1797                         else if (d < -180)
1798                                 d += 360;
1799                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1800                 }
1801         }
1802 }
1803
1804 void CSQC_RelinkAllEntities (int drawmask)
1805 {
1806         // link stuff
1807         CL_RelinkWorld();
1808         CL_RelinkStaticEntities();
1809         CL_RelinkBeams();
1810         CL_RelinkEffects();
1811
1812         // link stuff
1813         if (drawmask & ENTMASK_ENGINE)
1814         {
1815                 CL_RelinkNetworkEntities();
1816                 if (drawmask & ENTMASK_ENGINEVIEWMODELS)
1817                         CL_LinkNetworkEntity(&cl.viewent); // link gun model
1818                 CL_RelinkQWNails();
1819         }
1820
1821         // update view blend
1822         V_CalcViewBlend();
1823 }
1824
1825 /*
1826 ===============
1827 CL_UpdateWorld
1828
1829 Update client game world for a new frame
1830 ===============
1831 */
1832 void CL_UpdateWorld(void)
1833 {
1834         r_refdef.scene.extraupdate = !r_speeds.integer;
1835         r_refdef.scene.numentities = 0;
1836         r_refdef.scene.numlights = 0;
1837         r_refdef.view.matrix = identitymatrix;
1838         r_refdef.view.quality = 1;
1839
1840         cl.num_brushmodel_entities = 0;
1841
1842         if (cls.state == ca_connected && cls.signon == SIGNONS)
1843         {
1844                 // prepare for a new frame
1845                 CL_LerpPlayer(CL_LerpPoint());
1846                 CL_DecayLightFlashes();
1847                 CL_ClearTempEntities();
1848                 V_DriftPitch();
1849                 V_FadeViewFlashs();
1850
1851                 // if prediction is enabled we have to update all the collidable
1852                 // network entities before the prediction code can be run
1853                 CL_UpdateNetworkCollisionEntities();
1854
1855                 // now update the player prediction
1856                 CL_ClientMovement_Replay();
1857
1858                 // update the player entity (which may be predicted)
1859                 CL_UpdateNetworkEntity(cl.entities + cl.viewentity, 32, true);
1860
1861                 // now update the view (which depends on that player entity)
1862                 V_CalcRefdef();
1863
1864                 // now update all the network entities and create particle trails
1865                 // (some entities may depend on the view)
1866                 CL_UpdateNetworkEntities();
1867
1868                 // update the engine-based viewmodel
1869                 CL_UpdateViewModel();
1870
1871                 CL_RelinkLightFlashes();
1872                 CSQC_RelinkAllEntities(ENTMASK_ENGINE | ENTMASK_ENGINEVIEWMODELS);
1873
1874                 // decals, particles, and explosions will be updated during rneder
1875         }
1876
1877         r_refdef.scene.time = cl.time;
1878 }
1879
1880 // LordHavoc: pausedemo command
1881 static void CL_PauseDemo_f (void)
1882 {
1883         cls.demopaused = !cls.demopaused;
1884         if (cls.demopaused)
1885                 Con_Print("Demo paused\n");
1886         else
1887                 Con_Print("Demo unpaused\n");
1888 }
1889
1890 /*
1891 ======================
1892 CL_Fog_f
1893 ======================
1894 */
1895 static void CL_Fog_f (void)
1896 {
1897         if (Cmd_Argc () == 1)
1898         {
1899                 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);
1900                 return;
1901         }
1902         FOG_clear(); // so missing values get good defaults
1903         if(Cmd_Argc() > 1)
1904                 r_refdef.fog_density = atof(Cmd_Argv(1));
1905         if(Cmd_Argc() > 2)
1906                 r_refdef.fog_red = atof(Cmd_Argv(2));
1907         if(Cmd_Argc() > 3)
1908                 r_refdef.fog_green = atof(Cmd_Argv(3));
1909         if(Cmd_Argc() > 4)
1910                 r_refdef.fog_blue = atof(Cmd_Argv(4));
1911         if(Cmd_Argc() > 5)
1912                 r_refdef.fog_alpha = atof(Cmd_Argv(5));
1913         if(Cmd_Argc() > 6)
1914                 r_refdef.fog_start = atof(Cmd_Argv(6));
1915         if(Cmd_Argc() > 7)
1916                 r_refdef.fog_end = atof(Cmd_Argv(7));
1917         if(Cmd_Argc() > 8)
1918                 r_refdef.fog_height = atof(Cmd_Argv(8));
1919         if(Cmd_Argc() > 9)
1920                 r_refdef.fog_fadedepth = atof(Cmd_Argv(9));
1921 }
1922
1923 /*
1924 ====================
1925 CL_TimeRefresh_f
1926
1927 For program optimization
1928 ====================
1929 */
1930 static void CL_TimeRefresh_f (void)
1931 {
1932         int i;
1933         float timestart, timedelta;
1934
1935         r_refdef.scene.extraupdate = false;
1936
1937         timestart = Sys_DoubleTime();
1938         for (i = 0;i < 128;i++)
1939         {
1940                 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);
1941                 r_refdef.view.quality = 1;
1942                 CL_UpdateScreen();
1943         }
1944         timedelta = Sys_DoubleTime() - timestart;
1945
1946         Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta);
1947 }
1948
1949 void CL_AreaStats_f(void)
1950 {
1951         World_PrintAreaStats(&cl.world, "client");
1952 }
1953
1954 cl_locnode_t *CL_Locs_FindNearest(const vec3_t point)
1955 {
1956         int i;
1957         cl_locnode_t *loc;
1958         cl_locnode_t *best;
1959         vec3_t nearestpoint;
1960         vec_t dist, bestdist;
1961         best = NULL;
1962         bestdist = 0;
1963         for (loc = cl.locnodes;loc;loc = loc->next)
1964         {
1965                 for (i = 0;i < 3;i++)
1966                         nearestpoint[i] = bound(loc->mins[i], point[i], loc->maxs[i]);
1967                 dist = VectorDistance2(nearestpoint, point);
1968                 if (bestdist > dist || !best)
1969                 {
1970                         bestdist = dist;
1971                         best = loc;
1972                         if (bestdist < 1)
1973                                 break;
1974                 }
1975         }
1976         return best;
1977 }
1978
1979 void CL_Locs_FindLocationName(char *buffer, size_t buffersize, vec3_t point)
1980 {
1981         cl_locnode_t *loc;
1982         loc = CL_Locs_FindNearest(point);
1983         if (loc)
1984                 strlcpy(buffer, loc->name, buffersize);
1985         else
1986                 dpsnprintf(buffer, buffersize, "LOC=%.0f:%.0f:%.0f", point[0], point[1], point[2]);
1987 }
1988
1989 void CL_Locs_FreeNode(cl_locnode_t *node)
1990 {
1991         cl_locnode_t **pointer, **next;
1992         for (pointer = &cl.locnodes;*pointer;pointer = next)
1993         {
1994                 next = &(*pointer)->next;
1995                 if (*pointer == node)
1996                 {
1997                         *pointer = node->next;
1998                         Mem_Free(node);
1999                         return;
2000                 }
2001         }
2002         Con_Printf("CL_Locs_FreeNode: no such node! (%p)\n", (void *)node);
2003 }
2004
2005 void CL_Locs_AddNode(vec3_t mins, vec3_t maxs, const char *name)
2006 {
2007         cl_locnode_t *node, **pointer;
2008         int namelen;
2009         if (!name)
2010                 name = "";
2011         namelen = strlen(name);
2012         node = (cl_locnode_t *) Mem_Alloc(cls.levelmempool, sizeof(cl_locnode_t) + namelen + 1);
2013         VectorSet(node->mins, min(mins[0], maxs[0]), min(mins[1], maxs[1]), min(mins[2], maxs[2]));
2014         VectorSet(node->maxs, max(mins[0], maxs[0]), max(mins[1], maxs[1]), max(mins[2], maxs[2]));
2015         node->name = (char *)(node + 1);
2016         memcpy(node->name, name, namelen);
2017         node->name[namelen] = 0;
2018         // link it into the tail of the list to preserve the order
2019         for (pointer = &cl.locnodes;*pointer;pointer = &(*pointer)->next)
2020                 ;
2021         *pointer = node;
2022 }
2023
2024 void CL_Locs_Add_f(void)
2025 {
2026         vec3_t mins, maxs;
2027         if (Cmd_Argc() != 5 && Cmd_Argc() != 8)
2028         {
2029                 Con_Printf("usage: %s x y z[ x y z] name\n", Cmd_Argv(0));
2030                 return;
2031         }
2032         mins[0] = atof(Cmd_Argv(1));
2033         mins[1] = atof(Cmd_Argv(2));
2034         mins[2] = atof(Cmd_Argv(3));
2035         if (Cmd_Argc() == 8)
2036         {
2037                 maxs[0] = atof(Cmd_Argv(4));
2038                 maxs[1] = atof(Cmd_Argv(5));
2039                 maxs[2] = atof(Cmd_Argv(6));
2040                 CL_Locs_AddNode(mins, maxs, Cmd_Argv(7));
2041         }
2042         else
2043                 CL_Locs_AddNode(mins, mins, Cmd_Argv(4));
2044 }
2045
2046 void CL_Locs_RemoveNearest_f(void)
2047 {
2048         cl_locnode_t *loc;
2049         loc = CL_Locs_FindNearest(r_refdef.view.origin);
2050         if (loc)
2051                 CL_Locs_FreeNode(loc);
2052         else
2053                 Con_Printf("no loc point or box found for your location\n");
2054 }
2055
2056 void CL_Locs_Clear_f(void)
2057 {
2058         while (cl.locnodes)
2059                 CL_Locs_FreeNode(cl.locnodes);
2060 }
2061
2062 void CL_Locs_Save_f(void)
2063 {
2064         cl_locnode_t *loc;
2065         qfile_t *outfile;
2066         char locfilename[MAX_QPATH];
2067         if (!cl.locnodes)
2068         {
2069                 Con_Printf("No loc points/boxes exist!\n");
2070                 return;
2071         }
2072         if (cls.state != ca_connected || !cl.worldmodel)
2073         {
2074                 Con_Printf("No level loaded!\n");
2075                 return;
2076         }
2077         FS_StripExtension(cl.worldmodel->name, locfilename, sizeof(locfilename));
2078         strlcat(locfilename, ".loc", sizeof(locfilename));
2079
2080         outfile = FS_OpenRealFile(locfilename, "w", false);
2081         if (!outfile)
2082                 return;
2083         // if any boxes are used then this is a proquake-format loc file, which
2084         // allows comments, so add some relevant information at the start
2085         for (loc = cl.locnodes;loc;loc = loc->next)
2086                 if (!VectorCompare(loc->mins, loc->maxs))
2087                         break;
2088         if (loc)
2089         {
2090                 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);
2091                 for (loc = cl.locnodes;loc;loc = loc->next)
2092                         if (VectorCompare(loc->mins, loc->maxs))
2093                                 break;
2094                 if (loc)
2095                         Con_Printf("Warning: writing loc file containing a mixture of qizmo-style points and proquake-style boxes may not work in qizmo or proquake!\n");
2096         }
2097         for (loc = cl.locnodes;loc;loc = loc->next)
2098         {
2099                 if (VectorCompare(loc->mins, loc->maxs))
2100                 {
2101                         int len;
2102                         const char *s;
2103                         const char *in = loc->name;
2104                         char name[MAX_INPUTLINE];
2105                         for (len = 0;len < (int)sizeof(name) - 1 && *in;)
2106                         {
2107                                 if (*in == ' ') {s = "$loc_name_separator";in++;}
2108                                 else if (!strncmp(in, "SSG", 3)) {s = "$loc_name_ssg";in += 3;}
2109                                 else if (!strncmp(in, "NG", 2)) {s = "$loc_name_ng";in += 2;}
2110                                 else if (!strncmp(in, "SNG", 3)) {s = "$loc_name_sng";in += 3;}
2111                                 else if (!strncmp(in, "GL", 2)) {s = "$loc_name_gl";in += 2;}
2112                                 else if (!strncmp(in, "RL", 2)) {s = "$loc_name_rl";in += 2;}
2113                                 else if (!strncmp(in, "LG", 2)) {s = "$loc_name_lg";in += 2;}
2114                                 else if (!strncmp(in, "GA", 2)) {s = "$loc_name_ga";in += 2;}
2115                                 else if (!strncmp(in, "YA", 2)) {s = "$loc_name_ya";in += 2;}
2116                                 else if (!strncmp(in, "RA", 2)) {s = "$loc_name_ra";in += 2;}
2117                                 else if (!strncmp(in, "MEGA", 4)) {s = "$loc_name_mh";in += 4;}
2118                                 else s = NULL;
2119                                 if (s)
2120                                 {
2121                                         while (len < (int)sizeof(name) - 1 && *s)
2122                                                 name[len++] = *s++;
2123                                         continue;
2124                                 }
2125                                 name[len++] = *in++;
2126                         }
2127                         name[len] = 0;
2128                         FS_Printf(outfile, "%.0f %.0f %.0f %s\n", loc->mins[0]*8, loc->mins[1]*8, loc->mins[2]*8, name);
2129                 }
2130                 else
2131                         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);
2132         }
2133         FS_Close(outfile);
2134 }
2135
2136 void CL_Locs_Reload_f(void)
2137 {
2138         int i, linenumber, limit, len;
2139         const char *s;
2140         char *filedata, *text, *textend, *linestart, *linetext, *lineend;
2141         fs_offset_t filesize;
2142         vec3_t mins, maxs;
2143         char locfilename[MAX_QPATH];
2144         char name[MAX_INPUTLINE];
2145
2146         if (cls.state != ca_connected || !cl.worldmodel)
2147         {
2148                 Con_Printf("No level loaded!\n");
2149                 return;
2150         }
2151
2152         CL_Locs_Clear_f();
2153
2154         // try maps/something.loc first (LordHavoc: where I think they should be)
2155         FS_StripExtension(cl.worldmodel->name, locfilename, sizeof(locfilename));
2156         strlcat(locfilename, ".loc", sizeof(locfilename));
2157         filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize);
2158         if (!filedata)
2159         {
2160                 // try proquake name as well (LordHavoc: I hate path mangling)
2161                 FS_StripExtension(va("locs/%s", FS_FileWithoutPath(cl.worldmodel->name)), locfilename, sizeof(locfilename));
2162                 strlcat(locfilename, ".loc", sizeof(locfilename));
2163                 filedata = (char *)FS_LoadFile(locfilename, cls.levelmempool, false, &filesize);
2164                 if (!filedata)
2165                         return;
2166         }
2167         text = filedata;
2168         textend = filedata + filesize;
2169         for (linenumber = 1;text < textend;linenumber++)
2170         {
2171                 linestart = text;
2172                 for (;text < textend && *text != '\r' && *text != '\n';text++)
2173                         ;
2174                 lineend = text;
2175                 if (text + 1 < textend && *text == '\r' && text[1] == '\n')
2176                         text++;
2177                 if (text < textend)
2178                         text++;
2179                 // trim trailing whitespace
2180                 while (lineend > linestart && ISWHITESPACE(lineend[-1]))
2181                         lineend--;
2182                 // trim leading whitespace
2183                 while (linestart < lineend && ISWHITESPACE(*linestart))
2184                         linestart++;
2185                 // check if this is a comment
2186                 if (linestart + 2 <= lineend && !strncmp(linestart, "//", 2))
2187                         continue;
2188                 linetext = linestart;
2189                 limit = 3;
2190                 for (i = 0;i < limit;i++)
2191                 {
2192                         if (linetext >= lineend)
2193                                 break;
2194                         // note: a missing number is interpreted as 0
2195                         if (i < 3)
2196                                 mins[i] = atof(linetext);
2197                         else
2198                                 maxs[i - 3] = atof(linetext);
2199                         // now advance past the number
2200                         while (linetext < lineend && !ISWHITESPACE(*linetext) && *linetext != ',')
2201                                 linetext++;
2202                         // advance through whitespace
2203                         if (linetext < lineend)
2204                         {
2205                                 if (*linetext == ',')
2206                                 {
2207                                         linetext++;
2208                                         limit = 6;
2209                                         // note: comma can be followed by whitespace
2210                                 }
2211                                 if (ISWHITESPACE(*linetext))
2212                                 {
2213                                         // skip whitespace
2214                                         while (linetext < lineend && ISWHITESPACE(*linetext))
2215                                                 linetext++;
2216                                 }
2217                         }
2218                 }
2219                 // if this is a quoted name, remove the quotes
2220                 if (i == 6)
2221                 {
2222                         if (linetext >= lineend || *linetext != '"')
2223                                 continue; // proquake location names are always quoted
2224                         lineend--;
2225                         linetext++;
2226                         len = min(lineend - linetext, (int)sizeof(name) - 1);
2227                         memcpy(name, linetext, len);
2228                         name[len] = 0;
2229                         // add the box to the list
2230                         CL_Locs_AddNode(mins, maxs, name);
2231                 }
2232                 // if a point was parsed, it needs to be scaled down by 8 (since
2233                 // point-based loc files were invented by a proxy which dealt
2234                 // directly with quake protocol coordinates, which are *8), turn
2235                 // it into a box
2236                 else if (i == 3)
2237                 {
2238                         // interpret silly fuhquake macros
2239                         for (len = 0;len < (int)sizeof(name) - 1 && linetext < lineend;)
2240                         {
2241                                 if (*linetext == '$')
2242                                 {
2243                                         if (linetext + 18 <= lineend && !strncmp(linetext, "$loc_name_separator", 19)) {s = " ";linetext += 19;}
2244                                         else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_ssg", 13)) {s = "SSG";linetext += 13;}
2245                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ng", 12)) {s = "NG";linetext += 12;}
2246                                         else if (linetext + 13 <= lineend && !strncmp(linetext, "$loc_name_sng", 13)) {s = "SNG";linetext += 13;}
2247                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_gl", 12)) {s = "GL";linetext += 12;}
2248                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_rl", 12)) {s = "RL";linetext += 12;}
2249                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_lg", 12)) {s = "LG";linetext += 12;}
2250                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ga", 12)) {s = "GA";linetext += 12;}
2251                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ya", 12)) {s = "YA";linetext += 12;}
2252                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_ra", 12)) {s = "RA";linetext += 12;}
2253                                         else if (linetext + 12 <= lineend && !strncmp(linetext, "$loc_name_mh", 12)) {s = "MEGA";linetext += 12;}
2254                                         else s = NULL;
2255                                         if (s)
2256                                         {
2257                                                 while (len < (int)sizeof(name) - 1 && *s)
2258                                                         name[len++] = *s++;
2259                                                 continue;
2260                                         }
2261                                 }
2262                                 name[len++] = *linetext++;
2263                         }
2264                         name[len] = 0;
2265                         // add the point to the list
2266                         VectorScale(mins, (1.0 / 8.0), mins);
2267                         CL_Locs_AddNode(mins, mins, name);
2268                 }
2269                 else
2270                         continue;
2271         }
2272 }
2273
2274 /*
2275 ===========
2276 CL_Shutdown
2277 ===========
2278 */
2279 void CL_Shutdown (void)
2280 {
2281         CL_Screen_Shutdown();
2282         CL_Particles_Shutdown();
2283         CL_Parse_Shutdown();
2284
2285         Mem_FreePool (&cls.permanentmempool);
2286         Mem_FreePool (&cls.levelmempool);
2287 }
2288
2289 /*
2290 =================
2291 CL_Init
2292 =================
2293 */
2294 void CL_Init (void)
2295 {
2296         cls.levelmempool = Mem_AllocPool("client (per-level memory)", 0, NULL);
2297         cls.permanentmempool = Mem_AllocPool("client (long term memory)", 0, NULL);
2298
2299         memset(&r_refdef, 0, sizeof(r_refdef));
2300         // max entities sent to renderer per frame
2301         r_refdef.scene.maxentities = MAX_EDICTS + 256 + 512;
2302         r_refdef.scene.entities = (entity_render_t **)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t *) * r_refdef.scene.maxentities);
2303
2304         r_refdef.scene.maxtempentities = 4096; // FIXME: make this grow
2305         r_refdef.scene.tempentities = (entity_render_t *)Mem_Alloc(cls.permanentmempool, sizeof(entity_render_t) * r_refdef.scene.maxtempentities);
2306
2307         CL_InitInput ();
2308
2309 //
2310 // register our commands
2311 //
2312         Cvar_RegisterVariable (&cl_upspeed);
2313         Cvar_RegisterVariable (&cl_forwardspeed);
2314         Cvar_RegisterVariable (&cl_backspeed);
2315         Cvar_RegisterVariable (&cl_sidespeed);
2316         Cvar_RegisterVariable (&cl_movespeedkey);
2317         Cvar_RegisterVariable (&cl_yawspeed);
2318         Cvar_RegisterVariable (&cl_pitchspeed);
2319         Cvar_RegisterVariable (&cl_anglespeedkey);
2320         Cvar_RegisterVariable (&cl_shownet);
2321         Cvar_RegisterVariable (&cl_nolerp);
2322         Cvar_RegisterVariable (&cl_deathfade);
2323         Cvar_RegisterVariable (&lookspring);
2324         Cvar_RegisterVariable (&lookstrafe);
2325         Cvar_RegisterVariable (&sensitivity);
2326         Cvar_RegisterVariable (&freelook);
2327
2328         Cvar_RegisterVariable (&m_pitch);
2329         Cvar_RegisterVariable (&m_yaw);
2330         Cvar_RegisterVariable (&m_forward);
2331         Cvar_RegisterVariable (&m_side);
2332
2333         Cvar_RegisterVariable (&cl_itembobspeed);
2334         Cvar_RegisterVariable (&cl_itembobheight);
2335
2336         Cmd_AddCommand ("entities", CL_PrintEntities_f, "print information on network entities known to client");
2337         Cmd_AddCommand ("disconnect", CL_Disconnect_f, "disconnect from server (or disconnect all clients if running a server)");
2338         Cmd_AddCommand ("record", CL_Record_f, "record a demo");
2339         Cmd_AddCommand ("stop", CL_Stop_f, "stop recording or playing a demo");
2340         Cmd_AddCommand ("playdemo", CL_PlayDemo_f, "watch a demo file");
2341         Cmd_AddCommand ("timedemo", CL_TimeDemo_f, "play back a demo as fast as possible and save statistics to benchmark.log");
2342
2343         // Support Client-side Model Index List
2344         Cmd_AddCommand ("cl_modelindexlist", CL_ModelIndexList_f, "list information on all models in the client modelindex");
2345         // Support Client-side Sound Index List
2346         Cmd_AddCommand ("cl_soundindexlist", CL_SoundIndexList_f, "list all sounds in the client soundindex");
2347
2348         Cvar_RegisterVariable (&cl_autodemo);
2349         Cvar_RegisterVariable (&cl_autodemo_nameformat);
2350
2351         Cmd_AddCommand ("fog", CL_Fog_f, "set global fog parameters (density red green blue [alpha [mindist maxdist]])");
2352
2353         // LordHavoc: added pausedemo
2354         Cmd_AddCommand ("pausedemo", CL_PauseDemo_f, "pause demo playback (can also safely pause demo recording if using QUAKE, QUAKEDP or NEHAHRAMOVIE protocol, useful for making movies)");
2355
2356         Cmd_AddCommand ("cl_areastats", CL_AreaStats_f, "prints statistics on entity culling during collision traces");
2357
2358         Cvar_RegisterVariable(&r_draweffects);
2359         Cvar_RegisterVariable(&cl_explosions_alpha_start);
2360         Cvar_RegisterVariable(&cl_explosions_alpha_end);
2361         Cvar_RegisterVariable(&cl_explosions_size_start);
2362         Cvar_RegisterVariable(&cl_explosions_size_end);
2363         Cvar_RegisterVariable(&cl_explosions_lifetime);
2364         Cvar_RegisterVariable(&cl_stainmaps);
2365         Cvar_RegisterVariable(&cl_stainmaps_clearonload);
2366         Cvar_RegisterVariable(&cl_beams_polygons);
2367         Cvar_RegisterVariable(&cl_beams_quakepositionhack);
2368         Cvar_RegisterVariable(&cl_beams_instantaimhack);
2369         Cvar_RegisterVariable(&cl_beams_lightatend);
2370         Cvar_RegisterVariable(&cl_noplayershadow);
2371         Cvar_RegisterVariable(&cl_dlights_decayradius);
2372         Cvar_RegisterVariable(&cl_dlights_decaybrightness);
2373
2374         Cvar_RegisterVariable(&cl_prydoncursor);
2375
2376         Cvar_RegisterVariable(&cl_deathnoviewmodel);
2377
2378         // for QW connections
2379         Cvar_RegisterVariable(&qport);
2380         Cvar_SetValueQuick(&qport, (rand() * RAND_MAX + rand()) & 0xffff);
2381
2382         Cmd_AddCommand("timerefresh", CL_TimeRefresh_f, "turn quickly and print rendering statistcs");
2383
2384         Cvar_RegisterVariable(&cl_locs_enable);
2385         Cvar_RegisterVariable(&cl_locs_show);
2386         Cmd_AddCommand("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)");
2387         Cmd_AddCommand("locs_removenearest", CL_Locs_RemoveNearest_f, "remove the nearest point or box (note: you need to be very near a box to remove it)");
2388         Cmd_AddCommand("locs_clear", CL_Locs_Clear_f, "remove all loc points/boxes");
2389         Cmd_AddCommand("locs_reload", CL_Locs_Reload_f, "reload .loc file for this map");
2390         Cmd_AddCommand("locs_save", CL_Locs_Save_f, "save .loc file for this map containing currently defined points and boxes");
2391
2392         CL_Parse_Init();
2393         CL_Particles_Init();
2394         CL_Screen_Init();
2395
2396         CL_Video_Init();
2397         CL_Gecko_Init();
2398 }
2399
2400
2401