made darkplaces compile successfully with g++ to test for errors C doesn't care about...
[xonotic/darkplaces.git] / cl_main.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // cl_main.c  -- client main loop
21
22 #include "quakedef.h"
23 #include "cl_collision.h"
24 #include "cl_video.h"
25 #include "image.h"
26
27 // we need to declare some mouse variables here, because the menu system
28 // references them even when on a unix system.
29
30 cvar_t cl_shownet = {0, "cl_shownet","0"};
31 cvar_t cl_nolerp = {0, "cl_nolerp", "0"};
32
33 cvar_t cl_itembobheight = {0, "cl_itembobheight", "0"}; // try 8
34 cvar_t cl_itembobspeed = {0, "cl_itembobspeed", "0.5"};
35
36 cvar_t lookspring = {CVAR_SAVE, "lookspring","0"};
37 cvar_t lookstrafe = {CVAR_SAVE, "lookstrafe","0"};
38 cvar_t sensitivity = {CVAR_SAVE, "sensitivity","3", 1, 30};
39
40 cvar_t m_pitch = {CVAR_SAVE, "m_pitch","0.022"};
41 cvar_t m_yaw = {CVAR_SAVE, "m_yaw","0.022"};
42 cvar_t m_forward = {CVAR_SAVE, "m_forward","1"};
43 cvar_t m_side = {CVAR_SAVE, "m_side","0.8"};
44
45 cvar_t freelook = {CVAR_SAVE, "freelook", "1"};
46
47 cvar_t r_draweffects = {0, "r_draweffects", "1"};
48
49 cvar_t cl_explosions_alpha_start = {CVAR_SAVE, "cl_explosions_alpha_start", "1.5"};
50 cvar_t cl_explosions_alpha_end = {CVAR_SAVE, "cl_explosions_alpha_end", "0"};
51 cvar_t cl_explosions_size_start = {CVAR_SAVE, "cl_explosions_size_start", "16"};
52 cvar_t cl_explosions_size_end = {CVAR_SAVE, "cl_explosions_size_end", "128"};
53 cvar_t cl_explosions_lifetime = {CVAR_SAVE, "cl_explosions_lifetime", "0.5"};
54
55 cvar_t cl_stainmaps = {CVAR_SAVE, "cl_stainmaps", "1"};
56 cvar_t cl_stainmaps_clearonload = {CVAR_SAVE, "cl_stainmaps_clearonload", "1"};
57
58 cvar_t cl_beams_polygons = {CVAR_SAVE, "cl_beams_polygons", "1"};
59 cvar_t cl_beams_relative = {CVAR_SAVE, "cl_beams_relative", "1"};
60 cvar_t cl_beams_lightatend = {CVAR_SAVE, "cl_beams_lightatend", "0"};
61
62 cvar_t cl_noplayershadow = {CVAR_SAVE, "cl_noplayershadow", "0"};
63
64 cvar_t cl_prydoncursor = {0, "cl_prydoncursor", "0"};
65
66 cvar_t cl_deathnoviewmodel = {0, "cl_deathnoviewmodel", "1"};
67
68 vec3_t cl_playerstandmins;
69 vec3_t cl_playerstandmaxs;
70 vec3_t cl_playercrouchmins;
71 vec3_t cl_playercrouchmaxs;
72
73 mempool_t *cl_mempool;
74
75 client_static_t cls;
76 client_state_t  cl;
77
78 int cl_max_entities;
79 int cl_max_static_entities;
80 int cl_max_temp_entities;
81 int cl_max_effects;
82 int cl_max_beams;
83 int cl_max_dlights;
84 int cl_max_lightstyle;
85 int cl_max_brushmodel_entities;
86
87 entity_t *cl_entities;
88 qbyte *cl_entities_active;
89 entity_t *cl_static_entities;
90 entity_t *cl_temp_entities;
91 cl_effect_t *cl_effects;
92 beam_t *cl_beams;
93 dlight_t *cl_dlights;
94 lightstyle_t *cl_lightstyle;
95 int *cl_brushmodel_entities;
96
97 int cl_num_entities;
98 int cl_num_static_entities;
99 int cl_num_temp_entities;
100 int cl_num_brushmodel_entities;
101
102 // keep track of quake entities because they need to be killed if they get stale
103 extern int cl_lastquakeentity;
104 extern qbyte cl_isquakeentity[MAX_EDICTS];
105
106 /*
107 =====================
108 CL_ClearState
109
110 =====================
111 */
112 void CL_ClearState(void)
113 {
114         int i;
115
116         if (cl_entities) Mem_Free(cl_entities);cl_entities = NULL;
117         if (cl_entities_active) Mem_Free(cl_entities_active);cl_entities_active = NULL;
118         if (cl_static_entities) Mem_Free(cl_static_entities);cl_static_entities = NULL;
119         if (cl_temp_entities) Mem_Free(cl_temp_entities);cl_temp_entities = NULL;
120         if (cl_effects) Mem_Free(cl_effects);cl_effects = NULL;
121         if (cl_beams) Mem_Free(cl_beams);cl_beams = NULL;
122         if (cl_dlights) Mem_Free(cl_dlights);cl_dlights = NULL;
123         if (cl_lightstyle) Mem_Free(cl_lightstyle);cl_lightstyle = NULL;
124         if (cl_brushmodel_entities) Mem_Free(cl_brushmodel_entities);cl_brushmodel_entities = NULL;
125         if (cl.entitydatabase) EntityFrame_FreeDatabase(cl.entitydatabase);cl.entitydatabase = NULL;
126         if (cl.entitydatabase4) EntityFrame4_FreeDatabase(cl.entitydatabase4);cl.entitydatabase4 = NULL;
127         if (cl.scores) Mem_Free(cl.scores);cl.scores = NULL;
128
129         if (!sv.active)
130                 Host_ClearMemory ();
131
132 // wipe the entire cl structure
133         memset (&cl, 0, sizeof(cl));
134         // reset the view zoom interpolation
135         cl.mviewzoom[0] = cl.mviewzoom[1] = 1;
136
137         SZ_Clear (&cls.message);
138
139         cl_num_entities = 0;
140         cl_num_static_entities = 0;
141         cl_num_temp_entities = 0;
142         cl_num_brushmodel_entities = 0;
143
144         // tweak these if the game runs out
145         cl_max_entities = 256;
146         cl_max_static_entities = 256;
147         cl_max_temp_entities = 512;
148         cl_max_effects = 256;
149         cl_max_beams = 256;
150         cl_max_dlights = MAX_DLIGHTS;
151         cl_max_lightstyle = MAX_LIGHTSTYLES;
152         cl_max_brushmodel_entities = MAX_EDICTS;
153
154         cl_entities = (entity_t *)Mem_Alloc(cl_mempool, cl_max_entities * sizeof(entity_t));
155         cl_entities_active = (qbyte *)Mem_Alloc(cl_mempool, cl_max_brushmodel_entities * sizeof(qbyte));
156         cl_static_entities = (entity_t *)Mem_Alloc(cl_mempool, cl_max_static_entities * sizeof(entity_t));
157         cl_temp_entities = (entity_t *)Mem_Alloc(cl_mempool, cl_max_temp_entities * sizeof(entity_t));
158         cl_effects = (cl_effect_t *)Mem_Alloc(cl_mempool, cl_max_effects * sizeof(cl_effect_t));
159         cl_beams = (beam_t *)Mem_Alloc(cl_mempool, cl_max_beams * sizeof(beam_t));
160         cl_dlights = (dlight_t *)Mem_Alloc(cl_mempool, cl_max_dlights * sizeof(dlight_t));
161         cl_lightstyle = (lightstyle_t *)Mem_Alloc(cl_mempool, cl_max_lightstyle * sizeof(lightstyle_t));
162         cl_brushmodel_entities = (int *)Mem_Alloc(cl_mempool, cl_max_brushmodel_entities * sizeof(int));
163
164         cl_lastquakeentity = 0;
165         memset(cl_isquakeentity, 0, sizeof(cl_isquakeentity));
166
167         // LordHavoc: have to set up the baseline info for alpha and other stuff
168         for (i = 0;i < cl_max_entities;i++)
169         {
170                 cl_entities[i].state_baseline = defaultstate;
171                 cl_entities[i].state_previous = defaultstate;
172                 cl_entities[i].state_current = defaultstate;
173         }
174
175         if (gamemode == GAME_NEXUIZ)
176         {
177                 VectorSet(cl_playerstandmins, -16, -16, -24);
178                 VectorSet(cl_playerstandmaxs, 16, 16, 45);
179                 VectorSet(cl_playercrouchmins, -16, -16, -24);
180                 VectorSet(cl_playercrouchmaxs, 16, 16, 25);
181         }
182         else
183         {
184                 VectorSet(cl_playerstandmins, -16, -16, -24);
185                 VectorSet(cl_playerstandmaxs, 16, 16, 24);
186                 VectorSet(cl_playercrouchmins, -16, -16, -24);
187                 VectorSet(cl_playercrouchmaxs, 16, 16, 24);
188         }
189
190         CL_Screen_NewMap();
191         CL_Particles_Clear();
192         CL_CGVM_Clear();
193 }
194
195 void CL_ExpandEntities(int num)
196 {
197         int i, oldmaxentities;
198         entity_t *oldentities;
199         if (num >= cl_max_entities)
200         {
201                 if (!cl_entities)
202                         Sys_Error("CL_ExpandEntities: cl_entities not initialized\n");
203                 if (num >= MAX_EDICTS)
204                         Host_Error("CL_ExpandEntities: num %i >= %i\n", num, MAX_EDICTS);
205                 oldmaxentities = cl_max_entities;
206                 oldentities = cl_entities;
207                 cl_max_entities = (num & ~255) + 256;
208                 cl_entities = (entity_t *)Mem_Alloc(cl_mempool, cl_max_entities * sizeof(entity_t));
209                 memcpy(cl_entities, oldentities, oldmaxentities * sizeof(entity_t));
210                 Mem_Free(oldentities);
211                 for (i = oldmaxentities;i < cl_max_entities;i++)
212                 {
213                         cl_entities[i].state_baseline = defaultstate;
214                         cl_entities[i].state_previous = defaultstate;
215                         cl_entities[i].state_current = defaultstate;
216                 }
217         }
218 }
219
220 /*
221 =====================
222 CL_Disconnect
223
224 Sends a disconnect message to the server
225 This is also called on Host_Error, so it shouldn't cause any errors
226 =====================
227 */
228 void CL_Disconnect(void)
229 {
230         if (cls.state == ca_dedicated)
231                 return;
232
233         Con_DPrintf("CL_Disconnect\n");
234
235 // stop sounds (especially looping!)
236         S_StopAllSounds ();
237
238         // clear contents blends
239         cl.cshifts[0].percent = 0;
240         cl.cshifts[1].percent = 0;
241         cl.cshifts[2].percent = 0;
242         cl.cshifts[3].percent = 0;
243
244         cl.worldmodel = NULL;
245
246         if (cls.demoplayback)
247                 CL_StopPlayback();
248         else if (cls.netcon)
249         {
250                 if (cls.demorecording)
251                         CL_Stop_f();
252
253                 Con_DPrint("Sending clc_disconnect\n");
254                 SZ_Clear(&cls.message);
255                 MSG_WriteByte(&cls.message, clc_disconnect);
256                 NetConn_SendUnreliableMessage(cls.netcon, &cls.message);
257                 SZ_Clear(&cls.message);
258                 NetConn_Close(cls.netcon);
259                 cls.netcon = NULL;
260         }
261         cls.state = ca_disconnected;
262
263         cls.demoplayback = cls.timedemo = false;
264         cls.signon = 0;
265 }
266
267 void CL_Disconnect_f(void)
268 {
269         CL_Disconnect ();
270         if (sv.active)
271                 Host_ShutdownServer (false);
272 }
273
274
275
276
277 /*
278 =====================
279 CL_EstablishConnection
280
281 Host should be either "local" or a net address
282 =====================
283 */
284 void CL_EstablishConnection(const char *host)
285 {
286         if (cls.state == ca_dedicated)
287                 return;
288
289         // clear menu's connect error message
290         M_Update_Return_Reason("");
291         cls.demonum = -1;
292
293         // stop demo loop in case this fails
294         CL_Disconnect();
295         NetConn_ClientFrame();
296         NetConn_ServerFrame();
297
298         if (LHNETADDRESS_FromString(&cls.connect_address, host, 26000) && (cls.connect_mysocket = NetConn_ChooseClientSocketForAddress(&cls.connect_address)))
299         {
300                 cls.connect_trying = true;
301                 cls.connect_remainingtries = 3;
302                 cls.connect_nextsendtime = 0;
303                 M_Update_Return_Reason("Trying to connect...");
304                 if (sv.active)
305                 {
306                         NetConn_ClientFrame();
307                         NetConn_ServerFrame();
308                         NetConn_ClientFrame();
309                         NetConn_ServerFrame();
310                         NetConn_ClientFrame();
311                         NetConn_ServerFrame();
312                         NetConn_ClientFrame();
313                         NetConn_ServerFrame();
314                 }
315         }
316         else
317         {
318                 Con_Print("Unable to find a suitable network socket to connect to server.\n");
319                 M_Update_Return_Reason("No network");
320         }
321 }
322
323 /*
324 ==============
325 CL_PrintEntities_f
326 ==============
327 */
328 static void CL_PrintEntities_f(void)
329 {
330         entity_t *ent;
331         int i, j;
332         char name[32];
333
334         for (i = 0, ent = cl_entities;i < cl_num_entities;i++, ent++)
335         {
336                 if (!ent->state_current.active)
337                         continue;
338
339                 if (ent->render.model)
340                         strlcpy (name, ent->render.model->name, 25);
341                 else
342                         strcpy(name, "--no model--");
343                 for (j = (int)strlen(name);j < 25;j++)
344                         name[j] = ' ';
345                 Con_Printf("%3i: %s:%4i (%5i %5i %5i) [%3i %3i %3i] %4.2f %5.3f\n", i, name, ent->render.frame, (int) ent->render.origin[0], (int) ent->render.origin[1], (int) ent->render.origin[2], (int) ent->render.angles[0] % 360, (int) ent->render.angles[1] % 360, (int) ent->render.angles[2] % 360, ent->render.scale, ent->render.alpha);
346         }
347 }
348
349 //static const vec3_t nomodelmins = {-16, -16, -16};
350 //static const vec3_t nomodelmaxs = {16, 16, 16};
351 void CL_BoundingBoxForEntity(entity_render_t *ent)
352 {
353         if (ent->model)
354         {
355                 //if (ent->angles[0] || ent->angles[2])
356                 if (ent->matrix.m[2][0] != 0 || ent->matrix.m[2][1] != 0)
357                 {
358                         // pitch or roll
359                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->rotatedmins[0];
360                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->rotatedmins[1];
361                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->rotatedmins[2];
362                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->rotatedmaxs[0];
363                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->rotatedmaxs[1];
364                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->rotatedmaxs[2];
365                         //VectorAdd(ent->origin, ent->model->rotatedmins, ent->mins);
366                         //VectorAdd(ent->origin, ent->model->rotatedmaxs, ent->maxs);
367                 }
368                 //else if (ent->angles[1])
369                 else if (ent->matrix.m[0][1] != 0 || ent->matrix.m[1][0] != 0)
370                 {
371                         // yaw
372                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->yawmins[0];
373                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->yawmins[1];
374                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->yawmins[2];
375                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->yawmaxs[0];
376                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->yawmaxs[1];
377                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->yawmaxs[2];
378                         //VectorAdd(ent->origin, ent->model->yawmins, ent->mins);
379                         //VectorAdd(ent->origin, ent->model->yawmaxs, ent->maxs);
380                 }
381                 else
382                 {
383                         ent->mins[0] = ent->matrix.m[0][3] + ent->model->normalmins[0];
384                         ent->mins[1] = ent->matrix.m[1][3] + ent->model->normalmins[1];
385                         ent->mins[2] = ent->matrix.m[2][3] + ent->model->normalmins[2];
386                         ent->maxs[0] = ent->matrix.m[0][3] + ent->model->normalmaxs[0];
387                         ent->maxs[1] = ent->matrix.m[1][3] + ent->model->normalmaxs[1];
388                         ent->maxs[2] = ent->matrix.m[2][3] + ent->model->normalmaxs[2];
389                         //VectorAdd(ent->origin, ent->model->normalmins, ent->mins);
390                         //VectorAdd(ent->origin, ent->model->normalmaxs, ent->maxs);
391                 }
392         }
393         else
394         {
395                 ent->mins[0] = ent->matrix.m[0][3] - 16;
396                 ent->mins[1] = ent->matrix.m[1][3] - 16;
397                 ent->mins[2] = ent->matrix.m[2][3] - 16;
398                 ent->maxs[0] = ent->matrix.m[0][3] + 16;
399                 ent->maxs[1] = ent->matrix.m[1][3] + 16;
400                 ent->maxs[2] = ent->matrix.m[2][3] + 16;
401                 //VectorAdd(ent->origin, nomodelmins, ent->mins);
402                 //VectorAdd(ent->origin, nomodelmaxs, ent->maxs);
403         }
404 }
405
406 /*
407 ===============
408 CL_LerpPoint
409
410 Determines the fraction between the last two messages that the objects
411 should be put at.
412 ===============
413 */
414 static float CL_LerpPoint(void)
415 {
416         float f;
417
418         // dropped packet, or start of demo
419         if (cl.mtime[1] < cl.mtime[0] - 0.1)
420                 cl.mtime[1] = cl.mtime[0] - 0.1;
421
422         cl.time = bound(cl.mtime[1], cl.time, cl.mtime[0]);
423
424         // LordHavoc: lerp in listen games as the server is being capped below the client (usually)
425         f = cl.mtime[0] - cl.mtime[1];
426         if (!f || cl_nolerp.integer || cls.timedemo || cl.islocalgame)
427         {
428                 cl.time = cl.mtime[0];
429                 return 1;
430         }
431
432         f = (cl.time - cl.mtime[1]) / f;
433         return bound(0, f, 1);
434 }
435
436 void CL_ClearTempEntities (void)
437 {
438         cl_num_temp_entities = 0;
439 }
440
441 entity_t *CL_NewTempEntity(void)
442 {
443         entity_t *ent;
444
445         if (r_refdef.numentities >= r_refdef.maxentities)
446                 return NULL;
447         if (cl_num_temp_entities >= cl_max_temp_entities)
448                 return NULL;
449         ent = &cl_temp_entities[cl_num_temp_entities++];
450         memset (ent, 0, sizeof(*ent));
451         r_refdef.entities[r_refdef.numentities++] = &ent->render;
452
453         ent->render.colormap = -1; // no special coloring
454         ent->render.scale = 1;
455         ent->render.alpha = 1;
456         VectorSet(ent->render.colormod, 1, 1, 1);
457         return ent;
458 }
459
460 void CL_Effect(vec3_t org, int modelindex, int startframe, int framecount, float framerate)
461 {
462         int i;
463         cl_effect_t *e;
464         if (!modelindex) // sanity check
465                 return;
466         for (i = 0, e = cl_effects;i < cl_max_effects;i++, e++)
467         {
468                 if (e->active)
469                         continue;
470                 e->active = true;
471                 VectorCopy(org, e->origin);
472                 e->modelindex = modelindex;
473                 e->starttime = cl.time;
474                 e->startframe = startframe;
475                 e->endframe = startframe + framecount;
476                 e->framerate = framerate;
477
478                 e->frame = 0;
479                 e->frame1time = cl.time;
480                 e->frame2time = cl.time;
481                 break;
482         }
483 }
484
485 void CL_AllocDlight(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)
486 {
487         int i;
488         dlight_t *dl;
489
490         /*
491 // first look for an exact key match
492         if (ent)
493         {
494                 dl = cl_dlights;
495                 for (i = 0;i < MAX_DLIGHTS;i++, dl++)
496                         if (dl->ent == ent)
497                                 goto dlightsetup;
498         }
499         */
500
501 // then look for anything else
502         dl = cl_dlights;
503         for (i = 0;i < MAX_DLIGHTS;i++, dl++)
504                 if (!dl->radius)
505                         goto dlightsetup;
506
507         // unable to find one
508         return;
509
510 dlightsetup:
511         //Con_Printf("dlight %i : %f %f %f : %f %f %f\n", i, org[0], org[1], org[2], red * radius, green * radius, blue * radius);
512         memset (dl, 0, sizeof(*dl));
513         dl->matrix = *matrix;
514         dl->ent = ent;
515         dl->origin[0] = dl->matrix.m[0][3];
516         dl->origin[1] = dl->matrix.m[1][3];
517         dl->origin[2] = dl->matrix.m[2][3];
518         CL_FindNonSolidLocation(dl->origin, dl->origin, 6);
519         dl->matrix.m[0][3] = dl->origin[0];
520         dl->matrix.m[1][3] = dl->origin[1];
521         dl->matrix.m[2][3] = dl->origin[2];
522         dl->radius = radius;
523         dl->color[0] = red;
524         dl->color[1] = green;
525         dl->color[2] = blue;
526         dl->decay = decay;
527         if (lifetime)
528                 dl->die = cl.time + lifetime;
529         else
530                 dl->die = 0;
531         dl->cubemapnum = cubemapnum;
532         dl->style = style;
533         dl->shadow = shadowenable;
534         dl->corona = corona;
535         dl->flags = flags;
536         dl->coronasizescale = coronasizescale;
537         dl->ambientscale = ambientscale;
538         dl->diffusescale = diffusescale;
539         dl->specularscale = specularscale;
540 }
541
542 void CL_DecayLights(void)
543 {
544         int i;
545         dlight_t *dl;
546         float time;
547
548         time = cl.time - cl.oldtime;
549         for (i = 0, dl = cl_dlights;i < MAX_DLIGHTS;i++, dl++)
550                 if (dl->radius)
551                         dl->radius = (cl.time < dl->die) ? max(0, dl->radius - time * dl->decay) : 0;
552 }
553
554 #define MAXVIEWMODELS 32
555 entity_t *viewmodels[MAXVIEWMODELS];
556 int numviewmodels;
557
558 matrix4x4_t viewmodelmatrix;
559
560 static int entitylinkframenumber;
561
562 static const vec3_t muzzleflashorigin = {18, 0, 0};
563
564 extern void V_DriftPitch(void);
565 extern void V_FadeViewFlashs(void);
566 extern void V_CalcViewBlend(void);
567
568 extern void V_CalcRefdef(void);
569 // note this is a recursive function, but it can never get in a runaway loop (because of the delayedlink flags)
570 void CL_LinkNetworkEntity(entity_t *e)
571 {
572         matrix4x4_t *matrix, blendmatrix, tempmatrix, matrix2;
573         //matrix4x4_t dlightmatrix;
574         int j, k, l, trailtype, temp;
575         float origin[3], angles[3], delta[3], lerp, dlightcolor[3], dlightradius, mins[3], maxs[3], v2[3], d;
576         entity_t *t;
577         model_t *model;
578         trace_t trace;
579         //entity_persistent_t *p = &e->persistent;
580         //entity_render_t *r = &e->render;
581         if (e->persistent.linkframe != entitylinkframenumber)
582         {
583                 e->persistent.linkframe = entitylinkframenumber;
584                 // skip inactive entities and world
585                 if (!e->state_current.active || e == cl_entities)
586                         return;
587                 e->render.alpha = e->state_current.alpha * (1.0f / 255.0f); // FIXME: interpolate?
588                 e->render.scale = e->state_current.scale * (1.0f / 16.0f); // FIXME: interpolate?
589                 e->render.flags = e->state_current.flags;
590                 e->render.effects = e->state_current.effects;
591                 VectorScale(e->state_current.colormod, (1.0f / 32.0f), e->render.colormod);
592                 if (e->state_current.flags & RENDER_COLORMAPPED)
593                 {
594                         int cb;
595                         qbyte *cbcolor;
596                         e->render.colormap = e->state_current.colormap;
597                         cb = (e->render.colormap & 0xF) << 4;cb += (cb >= 128 && cb < 224) ? 4 : 12;
598                         cbcolor = (qbyte *) (&palette_complete[cb]);
599                         e->render.colormap_pantscolor[0] = cbcolor[0] * (1.0f / 255.0f) * e->render.colormod[0];
600                         e->render.colormap_pantscolor[1] = cbcolor[1] * (1.0f / 255.0f) * e->render.colormod[1];
601                         e->render.colormap_pantscolor[2] = cbcolor[2] * (1.0f / 255.0f) * e->render.colormod[2];
602                         cb = (e->render.colormap & 0xF0);cb += (cb >= 128 && cb < 224) ? 4 : 12;
603                         cbcolor = (qbyte *) (&palette_complete[cb]);
604                         e->render.colormap_shirtcolor[0] = cbcolor[0] * (1.0f / 255.0f) * e->render.colormod[0];
605                         e->render.colormap_shirtcolor[1] = cbcolor[1] * (1.0f / 255.0f) * e->render.colormod[1];
606                         e->render.colormap_shirtcolor[2] = cbcolor[2] * (1.0f / 255.0f) * e->render.colormod[2];
607                 }
608                 else if (e->state_current.colormap && cl.scores != NULL)
609                 {
610                         int cb;
611                         qbyte *cbcolor;
612                         e->render.colormap = cl.scores[e->state_current.colormap - 1].colors; // color it
613                         cb = (e->render.colormap & 0xF) << 4;cb += (cb >= 128 && cb < 224) ? 4 : 12;
614                         cbcolor = (qbyte *) (&palette_complete[cb]);
615                         e->render.colormap_pantscolor[0] = cbcolor[0] * (1.0f / 255.0f) * e->render.colormod[0];
616                         e->render.colormap_pantscolor[1] = cbcolor[1] * (1.0f / 255.0f) * e->render.colormod[1];
617                         e->render.colormap_pantscolor[2] = cbcolor[2] * (1.0f / 255.0f) * e->render.colormod[2];
618                         cb = (e->render.colormap & 0xF0);cb += (cb >= 128 && cb < 224) ? 4 : 12;
619                         cbcolor = (qbyte *) (&palette_complete[cb]);
620                         e->render.colormap_shirtcolor[0] = cbcolor[0] * (1.0f / 255.0f) * e->render.colormod[0];
621                         e->render.colormap_shirtcolor[1] = cbcolor[1] * (1.0f / 255.0f) * e->render.colormod[1];
622                         e->render.colormap_shirtcolor[2] = cbcolor[2] * (1.0f / 255.0f) * e->render.colormod[2];
623                 }
624                 else
625                 {
626                         e->render.colormap = -1; // no special coloring
627                         VectorClear(e->render.colormap_pantscolor);
628                         VectorClear(e->render.colormap_shirtcolor);
629                 }
630                 e->render.skinnum = e->state_current.skin;
631                 if (e->render.flags & RENDER_VIEWMODEL && !e->state_current.tagentity)
632                 {
633                         if (!r_drawviewmodel.integer || chase_active.integer || envmap)
634                                 return;
635                         if (cl.viewentity)
636                                 CL_LinkNetworkEntity(cl_entities + cl.viewentity);
637                         matrix = &viewmodelmatrix;
638                         if (e == &cl.viewent && cl_entities[cl.viewentity].state_current.active)
639                         {
640                                 e->state_current.alpha = cl_entities[cl.viewentity].state_current.alpha;
641                                 e->state_current.effects = EF_NOSHADOW | (cl_entities[cl.viewentity].state_current.effects & (EF_ADDITIVE | EF_REFLECTIVE | EF_FULLBRIGHT | EF_NODEPTHTEST));
642                         }
643                 }
644                 else
645                 {
646                         // if the tag entity is currently impossible, skip it
647                         if (e->state_current.tagentity >= cl_num_entities)
648                                 return;
649                         t = cl_entities + e->state_current.tagentity;
650                         // if the tag entity is inactive, skip it
651                         if (!t->state_current.active)
652                                 return;
653                         // note: this can link to world
654                         CL_LinkNetworkEntity(t);
655                         // make relative to the entity
656                         matrix = &t->render.matrix;
657                         // some properties of the tag entity carry over
658                         e->render.flags |= t->render.flags & (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL);
659                         // if a valid tagindex is used, make it relative to that tag instead
660                         // FIXME: use a model function to get tag info (need to handle skeletal)
661                         if (e->state_current.tagentity && e->state_current.tagindex >= 1 && (model = t->render.model))
662                         {
663                                 // blend the matrices
664                                 memset(&blendmatrix, 0, sizeof(blendmatrix));
665                                 for (j = 0;j < 4 && t->render.frameblend[j].lerp > 0;j++)
666                                 {
667                                         matrix4x4_t tagmatrix;
668                                         Mod_Alias_GetTagMatrix(model, t->render.frameblend[j].frame, e->state_current.tagindex - 1, &tagmatrix);
669                                         d = t->render.frameblend[j].lerp;
670                                         for (l = 0;l < 4;l++)
671                                                 for (k = 0;k < 4;k++)
672                                                         blendmatrix.m[l][k] += d * tagmatrix.m[l][k];
673                                 }
674                                 // concat the tag matrices onto the entity matrix
675                                 Matrix4x4_Concat(&tempmatrix, &t->render.matrix, &blendmatrix);
676                                 // use the constructed tag matrix
677                                 matrix = &tempmatrix;
678                         }
679                 }
680
681                 // movement lerp
682                 // if it's the player entity, update according to client movement
683                 if (e == cl_entities + cl.playerentity && cl.movement)
684                 {
685                         lerp = (cl.time - cl.mtime[1]) / (cl.mtime[0] - cl.mtime[1]);
686                         lerp = bound(0, lerp, 1);
687                         VectorLerp(cl.movement_oldorigin, lerp, cl.movement_origin, origin);
688                         VectorSet(angles, 0, cl.viewangles[1], 0);
689                 }
690                 else if (e->persistent.lerpdeltatime > 0 && (lerp = (cl.time - e->persistent.lerpstarttime) / e->persistent.lerpdeltatime) < 1)
691                 {
692                         // interpolate the origin and angles
693                         VectorLerp(e->persistent.oldorigin, lerp, e->persistent.neworigin, origin);
694                         VectorSubtract(e->persistent.newangles, e->persistent.oldangles, delta);
695                         if (delta[0] < -180) delta[0] += 360;else if (delta[0] >= 180) delta[0] -= 360;
696                         if (delta[1] < -180) delta[1] += 360;else if (delta[1] >= 180) delta[1] -= 360;
697                         if (delta[2] < -180) delta[2] += 360;else if (delta[2] >= 180) delta[2] -= 360;
698                         VectorMA(e->persistent.oldangles, lerp, delta, angles);
699                 }
700                 else
701                 {
702                         // no interpolation
703                         VectorCopy(e->persistent.neworigin, origin);
704                         VectorCopy(e->persistent.newangles, angles);
705                 }
706
707                 // model setup and some modelflags
708                 e->render.model = cl.model_precache[e->state_current.modelindex];
709                 if (e->render.model)
710                 {
711                         Mod_CheckLoaded(e->render.model);
712                         // if model is alias or this is a tenebrae-like dlight, reverse pitch direction
713                         if (e->render.model->type == mod_alias || (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC))
714                                 angles[0] = -angles[0];
715                         if ((e->render.model->flags & EF_ROTATE) && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
716                         {
717                                 angles[1] = ANGLEMOD(100*cl.time);
718                                 if (cl_itembobheight.value)
719                                         origin[2] += (cos(cl.time * cl_itembobspeed.value * (2.0 * M_PI)) + 1.0) * 0.5 * cl_itembobheight.value;
720                         }
721                         // transfer certain model flags to effects
722                         e->render.effects |= e->render.model->flags2 & (EF_FULLBRIGHT | EF_ADDITIVE);
723                         if (cl_prydoncursor.integer && (e->render.effects & EF_SELECTABLE) && cl.cmd.cursor_entitynumber == e->state_current.number)
724                                 VectorScale(e->render.colormod, 2, e->render.colormod);
725                 }
726
727                 // animation lerp
728                 if (e->render.frame2 == e->state_current.frame)
729                 {
730                         // update frame lerp fraction
731                         e->render.framelerp = 1;
732                         if (e->render.frame2time > e->render.frame1time)
733                         {
734                                 // make sure frame lerp won't last longer than 100ms
735                                 // (this mainly helps with models that use framegroups and
736                                 // switch between them infrequently)
737                                 e->render.framelerp = (cl.time - e->render.frame2time) / min(e->render.frame2time - e->render.frame1time, 0.1);
738                                 e->render.framelerp = bound(0, e->render.framelerp, 1);
739                         }
740                 }
741                 else
742                 {
743                         // begin a new frame lerp
744                         e->render.frame1 = e->render.frame2;
745                         e->render.frame1time = e->render.frame2time;
746                         e->render.frame = e->render.frame2 = e->state_current.frame;
747                         e->render.frame2time = cl.time;
748                         e->render.framelerp = 0;
749                 }
750                 R_LerpAnimation(&e->render);
751
752                 // set up the render matrix
753                 // FIXME: e->render.scale should go away
754                 Matrix4x4_CreateFromQuakeEntity(&matrix2, origin[0], origin[1], origin[2], angles[0], angles[1], angles[2], e->render.scale);
755                 // concat the matrices to make the entity relative to its tag
756                 Matrix4x4_Concat(&e->render.matrix, matrix, &matrix2);
757                 // make the other useful stuff
758                 Matrix4x4_Invert_Simple(&e->render.inversematrix, &e->render.matrix);
759                 CL_BoundingBoxForEntity(&e->render);
760
761                 // handle effects now that we know where this entity is in the world...
762                 if (e->render.model && e->render.model->soundfromcenter)
763                 {
764                         // bmodels are treated specially since their origin is usually '0 0 0'
765                         vec3_t o;
766                         VectorMAM(0.5f, e->render.model->normalmins, 0.5f, e->render.model->normalmaxs, o);
767                         Matrix4x4_Transform(&e->render.matrix, o, origin);
768                 }
769                 else
770                 {
771                         origin[0] = e->render.matrix.m[0][3];
772                         origin[1] = e->render.matrix.m[1][3];
773                         origin[2] = e->render.matrix.m[2][3];
774                 }
775                 trailtype = -1;
776                 dlightradius = 0;
777                 dlightcolor[0] = 0;
778                 dlightcolor[1] = 0;
779                 dlightcolor[2] = 0;
780                 // LordHavoc: if the entity has no effects, don't check each
781                 if (e->render.effects)
782                 {
783                         if (e->render.effects & EF_BRIGHTFIELD)
784                         {
785                                 if (gamemode == GAME_NEXUIZ)
786                                 {
787                                         dlightradius = max(dlightradius, 200);
788                                         dlightcolor[0] += 0.75f;
789                                         dlightcolor[1] += 1.50f;
790                                         dlightcolor[2] += 3.00f;
791                                         trailtype = 8;
792                                 }
793                                 else
794                                         CL_EntityParticles(e);
795                         }
796                         if (e->render.effects & EF_MUZZLEFLASH)
797                                 e->persistent.muzzleflash = 1.0f;
798                         if (e->render.effects & EF_DIMLIGHT)
799                         {
800                                 dlightradius = max(dlightradius, 200);
801                                 dlightcolor[0] += 1.50f;
802                                 dlightcolor[1] += 1.50f;
803                                 dlightcolor[2] += 1.50f;
804                         }
805                         if (e->render.effects & EF_BRIGHTLIGHT)
806                         {
807                                 dlightradius = max(dlightradius, 400);
808                                 dlightcolor[0] += 3.00f;
809                                 dlightcolor[1] += 3.00f;
810                                 dlightcolor[2] += 3.00f;
811                         }
812                         // LordHavoc: more effects
813                         if (e->render.effects & EF_RED) // red
814                         {
815                                 dlightradius = max(dlightradius, 200);
816                                 dlightcolor[0] += 1.50f;
817                                 dlightcolor[1] += 0.15f;
818                                 dlightcolor[2] += 0.15f;
819                         }
820                         if (e->render.effects & EF_BLUE) // blue
821                         {
822                                 dlightradius = max(dlightradius, 200);
823                                 dlightcolor[0] += 0.15f;
824                                 dlightcolor[1] += 0.15f;
825                                 dlightcolor[2] += 1.50f;
826                         }
827                         if (e->render.effects & EF_FLAME)
828                         {
829                                 mins[0] = origin[0] - 16.0f;
830                                 mins[1] = origin[1] - 16.0f;
831                                 mins[2] = origin[2] - 16.0f;
832                                 maxs[0] = origin[0] + 16.0f;
833                                 maxs[1] = origin[1] + 16.0f;
834                                 maxs[2] = origin[2] + 16.0f;
835                                 // how many flames to make
836                                 temp = (int) (cl.time * 300) - (int) (cl.oldtime * 300);
837                                 CL_FlameCube(mins, maxs, temp);
838                                 d = lhrandom(0.75f, 1);
839                                 dlightradius = max(dlightradius, 200);
840                                 dlightcolor[0] += d * 2.0f;
841                                 dlightcolor[1] += d * 1.5f;
842                                 dlightcolor[2] += d * 0.5f;
843                         }
844                         if (e->render.effects & EF_STARDUST)
845                         {
846                                 mins[0] = origin[0] - 16.0f;
847                                 mins[1] = origin[1] - 16.0f;
848                                 mins[2] = origin[2] - 16.0f;
849                                 maxs[0] = origin[0] + 16.0f;
850                                 maxs[1] = origin[1] + 16.0f;
851                                 maxs[2] = origin[2] + 16.0f;
852                                 // how many particles to make
853                                 temp = (int) (cl.time * 200) - (int) (cl.oldtime * 200);
854                                 CL_Stardust(mins, maxs, temp);
855                                 dlightradius = max(dlightradius, 200);
856                                 dlightcolor[0] += 1.0f;
857                                 dlightcolor[1] += 0.7f;
858                                 dlightcolor[2] += 0.3f;
859                         }
860                 }
861                 // muzzleflash fades over time, and is offset a bit
862                 if (e->persistent.muzzleflash > 0)
863                 {
864                         Matrix4x4_Transform(&e->render.matrix, muzzleflashorigin, v2);
865                         trace = CL_TraceBox(origin, vec3_origin, vec3_origin, v2, true, NULL, SUPERCONTENTS_SOLID | SUPERCONTENTS_SKY, false);
866                         tempmatrix = e->render.matrix;
867                         tempmatrix.m[0][3] = trace.endpos[0];
868                         tempmatrix.m[1][3] = trace.endpos[1];
869                         tempmatrix.m[2][3] = trace.endpos[2];
870                         CL_AllocDlight(NULL, &tempmatrix, 100, e->persistent.muzzleflash, e->persistent.muzzleflash, e->persistent.muzzleflash, 0, 0, 0, -1, true, 0, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
871                         e->persistent.muzzleflash -= cl.frametime * 10;
872                 }
873                 // LordHavoc: if the model has no flags, don't check each
874                 if (e->render.model && e->render.model->flags && (!e->state_current.tagentity && !(e->render.flags & RENDER_VIEWMODEL)))
875                 {
876                         if (e->render.model->flags & EF_GIB)
877                                 trailtype = 2;
878                         else if (e->render.model->flags & EF_ZOMGIB)
879                                 trailtype = 4;
880                         else if (e->render.model->flags & EF_TRACER)
881                         {
882                                 trailtype = 3;
883                                 dlightradius = max(dlightradius, 100);
884                                 dlightcolor[0] += 0.25f;
885                                 dlightcolor[1] += 1.00f;
886                                 dlightcolor[2] += 0.25f;
887                         }
888                         else if (e->render.model->flags & EF_TRACER2)
889                         {
890                                 trailtype = 5;
891                                 dlightradius = max(dlightradius, 100);
892                                 dlightcolor[0] += 1.00f;
893                                 dlightcolor[1] += 0.60f;
894                                 dlightcolor[2] += 0.20f;
895                         }
896                         else if (e->render.model->flags & EF_ROCKET)
897                         {
898                                 trailtype = 0;
899                                 dlightradius = max(dlightradius, 200);
900                                 dlightcolor[0] += 3.00f;
901                                 dlightcolor[1] += 1.50f;
902                                 dlightcolor[2] += 0.50f;
903                         }
904                         else if (e->render.model->flags & EF_GRENADE)
905                         {
906                                 // LordHavoc: e->render.alpha == -1 is for Nehahra dem compatibility (cigar smoke)
907                                 trailtype = e->render.alpha == -1 ? 7 : 1;
908                         }
909                         else if (e->render.model->flags & EF_TRACER3)
910                         {
911                                 trailtype = 6;
912                                 if (gamemode == GAME_PRYDON)
913                                 {
914                                         dlightradius = max(dlightradius, 100);
915                                         dlightcolor[0] += 0.30f;
916                                         dlightcolor[1] += 0.60f;
917                                         dlightcolor[2] += 1.20f;
918                                 }
919                                 else
920                                 {
921                                         dlightradius = max(dlightradius, 200);
922                                         dlightcolor[0] += 1.20f;
923                                         dlightcolor[1] += 0.50f;
924                                         dlightcolor[2] += 1.00f;
925                                 }
926                         }
927                 }
928                 // LordHavoc: customizable glow
929                 if (e->state_current.glowsize)
930                 {
931                         // * 4 for the expansion from 0-255 to 0-1023 range,
932                         // / 255 to scale down byte colors
933                         dlightradius = max(dlightradius, e->state_current.glowsize * 4);
934                         VectorMA(dlightcolor, (1.0f / 255.0f), (qbyte *)&palette_complete[e->state_current.glowcolor], dlightcolor);
935                 }
936                 // make the glow dlight
937                 if (dlightradius > 0 && (dlightcolor[0] || dlightcolor[1] || dlightcolor[2]) && !(e->render.flags & RENDER_VIEWMODEL))
938                 {
939                         //dlightmatrix = e->render.matrix;
940                         // hack to make glowing player light shine on their gun
941                         //if (e->state_current.number == cl.viewentity/* && !chase_active.integer*/)
942                         //      dlightmatrix.m[2][3] += 30;
943                         CL_AllocDlight(&e->render, &e->render.matrix, dlightradius, dlightcolor[0], dlightcolor[1], dlightcolor[2], 0, 0, 0, -1, true, 1, 0.25, 0.25, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
944                 }
945                 // custom rtlight
946                 if (e->state_current.lightpflags & PFLAGS_FULLDYNAMIC)
947                 {
948                         float light[4];
949                         VectorScale(e->state_current.light, (1.0f / 256.0f), light);
950                         light[3] = e->state_current.light[3];
951                         if (light[0] == 0 && light[1] == 0 && light[2] == 0)
952                                 VectorSet(light, 1, 1, 1);
953                         if (light[3] == 0)
954                                 light[3] = 350;
955                         // FIXME: add ambient/diffuse/specular scales as an extension ontop of TENEBRAE_GFX_DLIGHTS?
956                         CL_AllocDlight(&e->render, &e->render.matrix, light[3], light[0], light[1], light[2], 0, 0, e->state_current.skin, e->state_current.lightstyle, !(e->state_current.lightpflags & PFLAGS_NOSHADOW), (e->state_current.lightpflags & PFLAGS_CORONA) != 0, 0.25, 0, 1, 1, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
957                 }
958                 // do trails
959                 if (e->render.flags & RENDER_GLOWTRAIL)
960                         trailtype = 9;
961                 if (trailtype >= 0)
962                         CL_RocketTrail(e->persistent.trail_origin, origin, trailtype, e->state_current.glowcolor, e);
963                 VectorCopy(origin, e->persistent.trail_origin);
964                 // tenebrae's sprites are all additive mode (weird)
965                 if (gamemode == GAME_TENEBRAE && e->render.model && e->render.model->type == mod_sprite)
966                         e->render.effects |= EF_ADDITIVE;
967                 // player model is only shown with chase_active on
968                 if (e->state_current.number == cl.viewentity)
969                         e->render.flags |= RENDER_EXTERIORMODEL;
970                 // transparent stuff can't be lit during the opaque stage
971                 if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
972                         e->render.flags |= RENDER_TRANSPARENT;
973                 // either fullbright or lit
974                 if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
975                         e->render.flags |= RENDER_LIGHT;
976                 // hide player shadow during intermission or nehahra movie
977                 if (!(e->render.effects & EF_NOSHADOW)
978                  && !(e->render.flags & (RENDER_VIEWMODEL | RENDER_TRANSPARENT))
979                  && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cl.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
980                         e->render.flags |= RENDER_SHADOW;
981                 // as soon as player is known we can call V_CalcRefDef
982                 if (e->state_current.number == cl.viewentity)
983                         V_CalcRefdef();
984                 if (e->render.model && e->render.model->name[0] == '*' && e->render.model->TraceBox)
985                         cl_brushmodel_entities[cl_num_brushmodel_entities++] = e->state_current.number;
986                 // don't show entities with no modelindex (note: this still shows
987                 // entities which have a modelindex that resolved to a NULL model)
988                 if (e->render.model && !(e->render.effects & EF_NODRAW) && r_refdef.numentities < r_refdef.maxentities)
989                         r_refdef.entities[r_refdef.numentities++] = &e->render;
990                 //if (cl.viewentity && e->state_current.number == cl.viewentity)
991                 //      Matrix4x4_Print(&e->render.matrix);
992         }
993 }
994
995 void CL_RelinkWorld(void)
996 {
997         entity_t *ent = &cl_entities[0];
998         cl_brushmodel_entities[cl_num_brushmodel_entities++] = 0;
999         // FIXME: this should be done at load
1000         Matrix4x4_CreateIdentity(&ent->render.matrix);
1001         Matrix4x4_CreateIdentity(&ent->render.inversematrix);
1002         R_LerpAnimation(&ent->render);
1003         CL_BoundingBoxForEntity(&ent->render);
1004         ent->render.flags = RENDER_SHADOW;
1005         if (!r_fullbright.integer)
1006                 ent->render.flags |= RENDER_LIGHT;
1007         VectorSet(ent->render.colormod, 1, 1, 1);
1008         r_refdef.worldentity = &ent->render;
1009         r_refdef.worldmodel = cl.worldmodel;
1010 }
1011
1012 static void CL_RelinkStaticEntities(void)
1013 {
1014         int i;
1015         entity_t *e;
1016         for (i = 0, e = cl_static_entities;i < cl_num_static_entities && r_refdef.numentities < r_refdef.maxentities;i++, e++)
1017         {
1018                 Mod_CheckLoaded(e->render.model);
1019                 e->render.flags = 0;
1020                 // transparent stuff can't be lit during the opaque stage
1021                 if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
1022                         e->render.flags |= RENDER_TRANSPARENT;
1023                 // either fullbright or lit
1024                 if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
1025                         e->render.flags |= RENDER_LIGHT;
1026                 // hide player shadow during intermission or nehahra movie
1027                 if (!(e->render.effects & EF_NOSHADOW) && !(e->render.flags & RENDER_TRANSPARENT))
1028                         e->render.flags |= RENDER_SHADOW;
1029                 VectorSet(e->render.colormod, 1, 1, 1);
1030                 R_LerpAnimation(&e->render);
1031                 r_refdef.entities[r_refdef.numentities++] = &e->render;
1032         }
1033 }
1034
1035 /*
1036 ===============
1037 CL_RelinkEntities
1038 ===============
1039 */
1040 static void CL_RelinkNetworkEntities(void)
1041 {
1042         entity_t *ent;
1043         int i;
1044
1045         ent = &cl.viewent;
1046         ent->state_previous = ent->state_current;
1047         ent->state_current = defaultstate;
1048         ent->state_current.time = cl.time;
1049         ent->state_current.number = -1;
1050         ent->state_current.active = true;
1051         ent->state_current.modelindex = cl.stats[STAT_WEAPON];
1052         ent->state_current.frame = cl.stats[STAT_WEAPONFRAME];
1053         ent->state_current.flags = RENDER_VIEWMODEL;
1054         if ((cl.stats[STAT_HEALTH] <= 0 && cl_deathnoviewmodel.integer) || cl.intermission)
1055                 ent->state_current.modelindex = 0;
1056         else if (cl.stats[STAT_ITEMS] & IT_INVISIBILITY)
1057         {
1058                 if (gamemode == GAME_TRANSFUSION)
1059                         ent->state_current.alpha = 128;
1060                 else
1061                         ent->state_current.modelindex = 0;
1062         }
1063
1064         // reset animation interpolation on weaponmodel if model changed
1065         if (ent->state_previous.modelindex != ent->state_current.modelindex)
1066         {
1067                 ent->render.frame = ent->render.frame1 = ent->render.frame2 = ent->state_current.frame;
1068                 ent->render.frame1time = ent->render.frame2time = cl.time;
1069                 ent->render.framelerp = 1;
1070         }
1071
1072         // start on the entity after the world
1073         entitylinkframenumber++;
1074         for (i = 1;i < cl_num_entities;i++)
1075         {
1076                 if (cl_entities_active[i])
1077                 {
1078                         ent = cl_entities + i;
1079                         if (ent->state_current.active)
1080                                 CL_LinkNetworkEntity(ent);
1081                         else
1082                                 cl_entities_active[i] = false;
1083                 }
1084         }
1085         CL_LinkNetworkEntity(&cl.viewent);
1086 }
1087
1088 static void CL_RelinkEffects(void)
1089 {
1090         int i, intframe;
1091         cl_effect_t *e;
1092         entity_t *ent;
1093         float frame;
1094
1095         for (i = 0, e = cl_effects;i < cl_max_effects;i++, e++)
1096         {
1097                 if (e->active)
1098                 {
1099                         frame = (cl.time - e->starttime) * e->framerate + e->startframe;
1100                         intframe = frame;
1101                         if (intframe < 0 || intframe >= e->endframe)
1102                         {
1103                                 memset(e, 0, sizeof(*e));
1104                                 continue;
1105                         }
1106
1107                         if (intframe != e->frame)
1108                         {
1109                                 e->frame = intframe;
1110                                 e->frame1time = e->frame2time;
1111                                 e->frame2time = cl.time;
1112                         }
1113
1114                         // if we're drawing effects, get a new temp entity
1115                         // (NewTempEntity adds it to the render entities list for us)
1116                         if (r_draweffects.integer && (ent = CL_NewTempEntity()))
1117                         {
1118                                 // interpolation stuff
1119                                 ent->render.frame1 = intframe;
1120                                 ent->render.frame2 = intframe + 1;
1121                                 if (ent->render.frame2 >= e->endframe)
1122                                         ent->render.frame2 = -1; // disappear
1123                                 ent->render.framelerp = frame - intframe;
1124                                 ent->render.frame1time = e->frame1time;
1125                                 ent->render.frame2time = e->frame2time;
1126
1127                                 // normal stuff
1128                                 ent->render.model = cl.model_precache[e->modelindex];
1129                                 ent->render.frame = ent->render.frame2;
1130                                 ent->render.colormap = -1; // no special coloring
1131                                 ent->render.alpha = 1;
1132                                 VectorSet(ent->render.colormod, 1, 1, 1);
1133
1134                                 Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, e->origin[0], e->origin[1], e->origin[2], 0, 0, 0, 1);
1135                                 Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
1136                                 R_LerpAnimation(&ent->render);
1137                                 CL_BoundingBoxForEntity(&ent->render);
1138                         }
1139                 }
1140         }
1141 }
1142
1143 void CL_RelinkBeams(void)
1144 {
1145         int i;
1146         beam_t *b;
1147         vec3_t dist, org;
1148         float d;
1149         entity_t *ent;
1150         float yaw, pitch;
1151         float forward;
1152         matrix4x4_t tempmatrix;
1153
1154         for (i = 0, b = cl_beams;i < cl_max_beams;i++, b++)
1155         {
1156                 if (!b->model || b->endtime < cl.time)
1157                         continue;
1158
1159                 // if coming from the player, update the start position
1160                 //if (b->entity == cl.viewentity)
1161                 //      VectorCopy (cl_entities[cl.viewentity].render.origin, b->start);
1162                 if (cl_beams_relative.integer && b->entity == cl.viewentity && b->entity && cl_entities[b->entity].state_current.active && b->relativestartvalid)
1163                 {
1164                         entity_state_t *p = &cl_entities[b->entity].state_previous;
1165                         //entity_state_t *c = &cl_entities[b->entity].state_current;
1166                         entity_render_t *r = &cl_entities[b->entity].render;
1167                         matrix4x4_t matrix, imatrix;
1168                         if (b->relativestartvalid == 2)
1169                         {
1170                                 // not really valid yet, we need to get the orientation now
1171                                 // (ParseBeam flagged this because it is received before
1172                                 //  entities are received, by now they have been received)
1173                                 // note: because players create lightning in their think
1174                                 // function (which occurs before movement), they actually
1175                                 // have some lag in it's location, so compare to the
1176                                 // previous player state, not the latest
1177                                 if (b->entity == cl.viewentity)
1178                                         Matrix4x4_CreateFromQuakeEntity(&matrix, p->origin[0], p->origin[1], p->origin[2] + 16, cl.viewangles[0], cl.viewangles[1], cl.viewangles[2], 1);
1179                                 else
1180                                         Matrix4x4_CreateFromQuakeEntity(&matrix, p->origin[0], p->origin[1], p->origin[2] + 16, p->angles[0], p->angles[1], p->angles[2], 1);
1181                                 Matrix4x4_Invert_Simple(&imatrix, &matrix);
1182                                 Matrix4x4_Transform(&imatrix, b->start, b->relativestart);
1183                                 Matrix4x4_Transform(&imatrix, b->end, b->relativeend);
1184                                 b->relativestartvalid = 1;
1185                         }
1186                         else
1187                         {
1188                                 if (b->entity == cl.viewentity)
1189                                         Matrix4x4_CreateFromQuakeEntity(&matrix, r->origin[0], r->origin[1], r->origin[2] + 16, cl.viewangles[0], cl.viewangles[1], cl.viewangles[2], 1);
1190                                 else
1191                                         Matrix4x4_CreateFromQuakeEntity(&matrix, r->origin[0], r->origin[1], r->origin[2] + 16, r->angles[0], r->angles[1], r->angles[2], 1);
1192                                 Matrix4x4_Transform(&matrix, b->relativestart, b->start);
1193                                 Matrix4x4_Transform(&matrix, b->relativeend, b->end);
1194                         }
1195                 }
1196
1197                 if (b->lightning)
1198                 {
1199                         if (cl_beams_lightatend.integer)
1200                         {
1201                                 // FIXME: create a matrix from the beam start/end orientation
1202                                 Matrix4x4_CreateTranslate(&tempmatrix, b->end[0], b->end[1], b->end[2]);
1203                                 CL_AllocDlight (NULL, &tempmatrix, 200, 0.3, 0.7, 1, 0, 0, 0, -1, true, 1, 0.25, 1, 0, 0, LIGHTFLAG_NORMALMODE | LIGHTFLAG_REALTIMEMODE);
1204                         }
1205                         if (cl_beams_polygons.integer)
1206                                 continue;
1207                 }
1208
1209                 // calculate pitch and yaw
1210                 VectorSubtract (b->end, b->start, dist);
1211
1212                 if (dist[1] == 0 && dist[0] == 0)
1213                 {
1214                         yaw = 0;
1215                         if (dist[2] > 0)
1216                                 pitch = 90;
1217                         else
1218                                 pitch = 270;
1219                 }
1220                 else
1221                 {
1222                         yaw = (int) (atan2(dist[1], dist[0]) * 180 / M_PI);
1223                         if (yaw < 0)
1224                                 yaw += 360;
1225
1226                         forward = sqrt (dist[0]*dist[0] + dist[1]*dist[1]);
1227                         pitch = (int) (atan2(dist[2], forward) * 180 / M_PI);
1228                         if (pitch < 0)
1229                                 pitch += 360;
1230                 }
1231
1232                 // add new entities for the lightning
1233                 VectorCopy (b->start, org);
1234                 d = VectorNormalizeLength(dist);
1235                 while (d > 0)
1236                 {
1237                         ent = CL_NewTempEntity ();
1238                         if (!ent)
1239                                 return;
1240                         //VectorCopy (org, ent->render.origin);
1241                         ent->render.model = b->model;
1242                         //ent->render.effects = EF_FULLBRIGHT;
1243                         //ent->render.angles[0] = pitch;
1244                         //ent->render.angles[1] = yaw;
1245                         //ent->render.angles[2] = rand()%360;
1246                         Matrix4x4_CreateFromQuakeEntity(&ent->render.matrix, org[0], org[1], org[2], -pitch, yaw, lhrandom(0, 360), 1);
1247                         Matrix4x4_Invert_Simple(&ent->render.inversematrix, &ent->render.matrix);
1248                         R_LerpAnimation(&ent->render);
1249                         CL_BoundingBoxForEntity(&ent->render);
1250                         VectorMA(org, 30, dist, org);
1251                         d -= 30;
1252                 }
1253         }
1254 }
1255
1256 void CL_LerpPlayer(float frac)
1257 {
1258         int i;
1259         float d;
1260
1261         cl.viewzoom = cl.mviewzoom[1] + frac * (cl.mviewzoom[0] - cl.mviewzoom[1]);
1262         for (i = 0;i < 3;i++)
1263         {
1264                 cl.punchangle[i] = cl.mpunchangle[1][i] + frac * (cl.mpunchangle[0][i] - cl.mpunchangle[1][i]);
1265                 cl.punchvector[i] = cl.mpunchvector[1][i] + frac * (cl.mpunchvector[0][i] - cl.mpunchvector[1][i]);
1266                 cl.velocity[i] = cl.mvelocity[1][i] + frac * (cl.mvelocity[0][i] - cl.mvelocity[1][i]);
1267         }
1268
1269         if (cls.demoplayback)
1270         {
1271                 // interpolate the angles
1272                 for (i = 0;i < 3;i++)
1273                 {
1274                         d = cl.mviewangles[0][i] - cl.mviewangles[1][i];
1275                         if (d > 180)
1276                                 d -= 360;
1277                         else if (d < -180)
1278                                 d += 360;
1279                         cl.viewangles[i] = cl.mviewangles[1][i] + frac * d;
1280                 }
1281         }
1282 }
1283
1284 /*
1285 ===============
1286 CL_ReadFromServer
1287
1288 Read all incoming data from the server
1289 ===============
1290 */
1291 extern void CL_ClientMovement_Replay();
1292 int CL_ReadFromServer(void)
1293 {
1294         CL_ReadDemoMessage();
1295
1296         r_refdef.time = cl.time;
1297         r_refdef.extraupdate = !r_speeds.integer;
1298         r_refdef.numentities = 0;
1299         Matrix4x4_CreateIdentity(&r_refdef.viewentitymatrix);
1300         cl_num_brushmodel_entities = 0;
1301
1302         if (cls.state == ca_connected && cls.signon == SIGNONS)
1303         {
1304                 // prepare for a new frame
1305                 CL_LerpPlayer(CL_LerpPoint());
1306                 CL_DecayLights();
1307                 CL_ClearTempEntities();
1308                 V_DriftPitch();
1309                 V_FadeViewFlashs();
1310
1311                 // relink network entities (note: this sets up the view!)
1312                 CL_ClientMovement_Replay();
1313                 CL_RelinkNetworkEntities();
1314
1315                 // move particles
1316                 CL_MoveParticles();
1317                 R_MoveExplosions();
1318
1319                 // link stuff
1320                 CL_RelinkWorld();
1321                 CL_RelinkStaticEntities();
1322                 CL_RelinkBeams();
1323                 CL_RelinkEffects();
1324
1325                 // run cgame code (which can add more entities)
1326                 CL_CGVM_Frame();
1327
1328                 // update view blend
1329                 V_CalcViewBlend();
1330         }
1331
1332         return 0;
1333 }
1334
1335 /*
1336 =================
1337 CL_SendCmd
1338 =================
1339 */
1340 void CL_UpdatePrydonCursor(void);
1341 void CL_SendCmd(void)
1342 {
1343         if (cls.demoplayback)
1344         {
1345                 SZ_Clear(&cls.message);
1346                 return;
1347         }
1348
1349         // send the reliable message (forwarded commands) if there is one
1350         if (cls.message.cursize && NetConn_CanSendMessage(cls.netcon))
1351         {
1352                 if (developer.integer)
1353                 {
1354                         Con_Print("CL_SendCmd: sending reliable message:\n");
1355                         SZ_HexDumpToConsole(&cls.message);
1356                 }
1357                 if (NetConn_SendReliableMessage(cls.netcon, &cls.message) == -1)
1358                         Host_Error("CL_WriteToServer: lost server connection");
1359                 SZ_Clear(&cls.message);
1360         }
1361 }
1362
1363 // LordHavoc: pausedemo command
1364 static void CL_PauseDemo_f (void)
1365 {
1366         cls.demopaused = !cls.demopaused;
1367         if (cls.demopaused)
1368                 Con_Print("Demo paused\n");
1369         else
1370                 Con_Print("Demo unpaused\n");
1371 }
1372
1373 /*
1374 ======================
1375 CL_Fog_f
1376 ======================
1377 */
1378 static void CL_Fog_f (void)
1379 {
1380         if (Cmd_Argc () == 1)
1381         {
1382                 Con_Printf("\"fog\" is \"%f %f %f %f\"\n", fog_density, fog_red, fog_green, fog_blue);
1383                 return;
1384         }
1385         fog_density = atof(Cmd_Argv(1));
1386         fog_red = atof(Cmd_Argv(2));
1387         fog_green = atof(Cmd_Argv(3));
1388         fog_blue = atof(Cmd_Argv(4));
1389 }
1390
1391 /*
1392 ====================
1393 CL_TimeRefresh_f
1394
1395 For program optimization
1396 ====================
1397 */
1398 static void CL_TimeRefresh_f (void)
1399 {
1400         int i;
1401         float timestart, timedelta, oldangles[3];
1402
1403         r_refdef.extraupdate = false;
1404         VectorCopy(cl.viewangles, oldangles);
1405         VectorClear(cl.viewangles);
1406
1407         timestart = Sys_DoubleTime();
1408         for (i = 0;i < 128;i++)
1409         {
1410                 Matrix4x4_CreateFromQuakeEntity(&r_refdef.viewentitymatrix, r_vieworigin[0], r_vieworigin[1], r_vieworigin[2], 0, i / 128.0 * 360.0, 0, 1);
1411                 CL_UpdateScreen();
1412         }
1413         timedelta = Sys_DoubleTime() - timestart;
1414
1415         VectorCopy(oldangles, cl.viewangles);
1416         Con_Printf("%f seconds (%f fps)\n", timedelta, 128/timedelta);
1417 }
1418
1419 /*
1420 ===========
1421 CL_Shutdown
1422 ===========
1423 */
1424 void CL_Shutdown (void)
1425 {
1426         CL_CGVM_Shutdown();
1427         CL_Particles_Shutdown();
1428         CL_Parse_Shutdown();
1429
1430         Mem_FreePool (&cl_mempool);
1431 }
1432
1433 /*
1434 =================
1435 CL_Init
1436 =================
1437 */
1438 void CL_Init (void)
1439 {
1440         cl_mempool = Mem_AllocPool("client", 0, NULL);
1441
1442         memset(&r_refdef, 0, sizeof(r_refdef));
1443         // max entities sent to renderer per frame
1444         r_refdef.maxentities = MAX_EDICTS + 256 + 512;
1445         r_refdef.entities = (entity_render_t **)Mem_Alloc(cl_mempool, sizeof(entity_render_t *) * r_refdef.maxentities);
1446         // 256k drawqueue buffer
1447         r_refdef.maxdrawqueuesize = 256 * 1024;
1448         r_refdef.drawqueue = (qbyte *)Mem_Alloc(cl_mempool, r_refdef.maxdrawqueuesize);
1449
1450         cls.message.data = cls.message_buf;
1451         cls.message.maxsize = sizeof(cls.message_buf);
1452         cls.message.cursize = 0;
1453
1454         CL_InitInput ();
1455
1456 //
1457 // register our commands
1458 //
1459         Cvar_RegisterVariable (&cl_upspeed);
1460         Cvar_RegisterVariable (&cl_forwardspeed);
1461         Cvar_RegisterVariable (&cl_backspeed);
1462         Cvar_RegisterVariable (&cl_sidespeed);
1463         Cvar_RegisterVariable (&cl_movespeedkey);
1464         Cvar_RegisterVariable (&cl_yawspeed);
1465         Cvar_RegisterVariable (&cl_pitchspeed);
1466         Cvar_RegisterVariable (&cl_anglespeedkey);
1467         Cvar_RegisterVariable (&cl_shownet);
1468         Cvar_RegisterVariable (&cl_nolerp);
1469         Cvar_RegisterVariable (&lookspring);
1470         Cvar_RegisterVariable (&lookstrafe);
1471         Cvar_RegisterVariable (&sensitivity);
1472         Cvar_RegisterVariable (&freelook);
1473
1474         Cvar_RegisterVariable (&m_pitch);
1475         Cvar_RegisterVariable (&m_yaw);
1476         Cvar_RegisterVariable (&m_forward);
1477         Cvar_RegisterVariable (&m_side);
1478
1479         Cvar_RegisterVariable (&cl_itembobspeed);
1480         Cvar_RegisterVariable (&cl_itembobheight);
1481
1482         Cmd_AddCommand ("entities", CL_PrintEntities_f);
1483         Cmd_AddCommand ("disconnect", CL_Disconnect_f);
1484         Cmd_AddCommand ("record", CL_Record_f);
1485         Cmd_AddCommand ("stop", CL_Stop_f);
1486         Cmd_AddCommand ("playdemo", CL_PlayDemo_f);
1487         Cmd_AddCommand ("timedemo", CL_TimeDemo_f);
1488
1489         Cmd_AddCommand ("fog", CL_Fog_f);
1490
1491         // LordHavoc: added pausedemo
1492         Cmd_AddCommand ("pausedemo", CL_PauseDemo_f);
1493
1494         Cvar_RegisterVariable(&r_draweffects);
1495         Cvar_RegisterVariable(&cl_explosions_alpha_start);
1496         Cvar_RegisterVariable(&cl_explosions_alpha_end);
1497         Cvar_RegisterVariable(&cl_explosions_size_start);
1498         Cvar_RegisterVariable(&cl_explosions_size_end);
1499         Cvar_RegisterVariable(&cl_explosions_lifetime);
1500         Cvar_RegisterVariable(&cl_stainmaps);
1501         Cvar_RegisterVariable(&cl_stainmaps_clearonload);
1502         Cvar_RegisterVariable(&cl_beams_polygons);
1503         Cvar_RegisterVariable(&cl_beams_relative);
1504         Cvar_RegisterVariable(&cl_beams_lightatend);
1505         Cvar_RegisterVariable(&cl_noplayershadow);
1506
1507         Cvar_RegisterVariable(&cl_prydoncursor);
1508
1509         Cvar_RegisterVariable(&cl_deathnoviewmodel);
1510
1511         Cmd_AddCommand("timerefresh", CL_TimeRefresh_f);
1512
1513         CL_Parse_Init();
1514         CL_Particles_Init();
1515         CL_Screen_Init();
1516         CL_CGVM_Init();
1517
1518         CL_Video_Init();
1519 }
1520
1521
1522