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