made the Sorted Edge Rasterizer (hidden surface removal) optional as the r_ser cvar...
[xonotic/darkplaces.git] / gl_rmain.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 // r_main.c
21
22 #include "quakedef.h"
23
24 qboolean        r_cache_thrash;         // compatability
25
26 vec3_t          modelorg, r_entorigin;
27 entity_t        *currententity;
28
29 int                     r_framecount;           // used for dlight push checking
30
31 mplane_t        frustum[4];
32
33 int                     c_brush_polys, c_alias_polys, c_light_polys, c_faces, c_nodes, c_leafs, c_models, c_bmodels, c_sprites, c_particles, c_dlights;
34
35 qboolean        envmap;                         // true during envmap command capture
36
37 // LordHavoc: moved all code related to particles into r_part.c
38 //int                   particletexture;        // little dot for particles
39 //int                   playertextures;         // up to 16 color translated skins
40
41 //
42 // view origin
43 //
44 vec3_t  vup;
45 vec3_t  vpn;
46 vec3_t  vright;
47 vec3_t  r_origin;
48
49 float   r_world_matrix[16];
50 float   r_base_world_matrix[16];
51
52 //
53 // screen size info
54 //
55 refdef_t        r_refdef;
56
57 mleaf_t         *r_viewleaf, *r_oldviewleaf;
58
59 unsigned short  d_lightstylevalue[256]; // 8.8 fraction of base light value
60
61 float ixtable[4096];
62
63 void R_MarkLeaves (void);
64
65 //cvar_t        r_norefresh = {0, "r_norefresh","0"};
66 cvar_t  r_drawentities = {0, "r_drawentities","1"};
67 cvar_t  r_drawviewmodel = {0, "r_drawviewmodel","1"};
68 cvar_t  r_speeds = {0, "r_speeds","0"};
69 cvar_t  r_speeds2 = {0, "r_speeds2","0"};
70 cvar_t  r_fullbright = {0, "r_fullbright","0"};
71 //cvar_t        r_lightmap = {0, "r_lightmap","0"};
72 cvar_t  r_wateralpha = {CVAR_SAVE, "r_wateralpha","1"};
73 cvar_t  r_dynamic = {CVAR_SAVE, "r_dynamic","1"};
74 cvar_t  r_waterripple = {CVAR_SAVE, "r_waterripple","0"};
75 cvar_t  r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1"};
76
77 cvar_t  gl_lightmode = {CVAR_SAVE, "gl_lightmode", "1"}; // LordHavoc: overbright lighting
78 //cvar_t        r_dynamicbothsides = {CVAR_SAVE, "r_dynamicbothsides", "1"}; // LordHavoc: can disable dynamic lighting of backfaces, but quake maps are weird so it doesn't always work right...
79 cvar_t  r_farclip = {0, "r_farclip", "6144"}; // FIXME: make this go away (calculate based on farthest visible object/polygon)
80
81 cvar_t  gl_fogenable = {0, "gl_fogenable", "0"};
82 cvar_t  gl_fogdensity = {0, "gl_fogdensity", "0.25"};
83 cvar_t  gl_fogred = {0, "gl_fogred","0.3"};
84 cvar_t  gl_foggreen = {0, "gl_foggreen","0.3"};
85 cvar_t  gl_fogblue = {0, "gl_fogblue","0.3"};
86 cvar_t  gl_fogstart = {0, "gl_fogstart", "0"};
87 cvar_t  gl_fogend = {0, "gl_fogend","0"};
88 cvar_t  glfog = {0, "glfog", "0"};
89
90 cvar_t  r_ser = {CVAR_SAVE, "r_ser", "1"};
91
92 /*
93 int R_VisibleCullBox (vec3_t mins, vec3_t maxs)
94 {
95         int sides;
96         mnode_t *nodestack[8192], *node;
97         int stack = 0;
98
99         node = cl.worldmodel->nodes;
100 loc0:
101         if (node->contents < 0)
102         {
103                 if (((mleaf_t *)node)->visframe == r_framecount)
104                 {
105                         if (R_CullBox(mins, maxs))
106                                 return true;
107                         return false;
108                 }
109                 if (!stack)
110                         return true;
111                 node = nodestack[--stack];
112                 goto loc0;
113         }
114
115         sides = BOX_ON_PLANE_SIDE(mins, maxs, node->plane);
116
117 // recurse down the contacted sides
118         if (sides & 1)
119         {
120                 if (sides & 2) // 3
121                 {
122                         // put second child on the stack for later examination
123                         nodestack[stack++] = node->children[1];
124                         node = node->children[0];
125                         goto loc0;
126                 }
127                 else // 1
128                 {
129                         node = node->children[0];
130                         goto loc0;
131                 }
132         }
133         // 2
134         node = node->children[1];
135         goto loc0;
136 }
137 */
138
139 qboolean lighthalf;
140
141 vec3_t fogcolor;
142 vec_t fogdensity;
143 float fog_density, fog_red, fog_green, fog_blue;
144 qboolean fogenabled;
145 qboolean oldgl_fogenable;
146 void FOG_framebegin(void)
147 {
148         if (nehahra)
149         {
150 //              if (!Nehahrademcompatibility)
151 //                      gl_fogenable.value = 0;
152                 if (gl_fogenable.value)
153                 {
154                         oldgl_fogenable = true;
155                         fog_density = gl_fogdensity.value;
156                         fog_red = gl_fogred.value;
157                         fog_green = gl_foggreen.value;
158                         fog_blue = gl_fogblue.value;
159                 }
160                 else if (oldgl_fogenable)
161                 {
162                         oldgl_fogenable = false;
163                         fog_density = 0;
164                         fog_red = 0;
165                         fog_green = 0;
166                         fog_blue = 0;
167                 }
168         }
169         if (fog_density)
170         {
171                         fogcolor[0] = fog_red   = bound(0.0f, fog_red  , 1.0f);
172                         fogcolor[1] = fog_green = bound(0.0f, fog_green, 1.0f);
173                         fogcolor[2] = fog_blue  = bound(0.0f, fog_blue , 1.0f);
174                         if (lighthalf)
175                         {
176                                 fogcolor[0] *= 0.5f;
177                                 fogcolor[1] *= 0.5f;
178                                 fogcolor[2] *= 0.5f;
179                         }
180         }
181         if (glfog.value)
182         {
183                 if (!r_render.value)
184                         return;
185                 if(fog_density)
186                 {
187                         // LordHavoc: Borland C++ 5.0 was choking on this line, stupid compiler...
188                         //GLfloat colors[4] = {(GLfloat) gl_fogred.value, (GLfloat) gl_foggreen.value, (GLfloat) gl_fogblue.value, (GLfloat) 1};
189                         GLfloat colors[4];
190                         colors[0] = fog_red;
191                         colors[1] = fog_green;
192                         colors[2] = fog_blue;
193                         colors[3] = 1;
194                         if (lighthalf)
195                         {
196                                 colors[0] *= 0.5f;
197                                 colors[1] *= 0.5f;
198                                 colors[2] *= 0.5f;
199                         }
200
201                         glFogi (GL_FOG_MODE, GL_EXP2);
202                         glFogf (GL_FOG_DENSITY, (GLfloat) fog_density / 100); 
203                         glFogfv (GL_FOG_COLOR, colors);
204                         glEnable (GL_FOG);
205                 }
206                 else
207                         glDisable(GL_FOG);
208         }
209         else
210         {
211                 if (fog_density)
212                 {
213                         fogenabled = true;
214                         fogdensity = -4000.0f / (fog_density * fog_density);
215                         // fog color was already set
216                 }
217                 else
218                         fogenabled = false;
219         }
220 }
221
222 void FOG_frameend(void)
223 {
224         if (glfog.value)
225                 glDisable(GL_FOG);
226 }
227
228 void FOG_clear(void)
229 {
230         if (nehahra)
231         {
232                 Cvar_Set("gl_fogenable", "0");
233                 Cvar_Set("gl_fogdensity", "0.2");
234                 Cvar_Set("gl_fogred", "0.3");
235                 Cvar_Set("gl_foggreen", "0.3");
236                 Cvar_Set("gl_fogblue", "0.3");
237         }
238         fog_density = fog_red = fog_green = fog_blue = 0.0f;
239 }
240
241 void FOG_registercvars(void)
242 {
243         Cvar_RegisterVariable (&glfog);
244         if (nehahra)
245         {
246                 Cvar_RegisterVariable (&gl_fogenable);
247                 Cvar_RegisterVariable (&gl_fogdensity);
248                 Cvar_RegisterVariable (&gl_fogred);
249                 Cvar_RegisterVariable (&gl_foggreen);
250                 Cvar_RegisterVariable (&gl_fogblue);
251                 Cvar_RegisterVariable (&gl_fogstart);
252                 Cvar_RegisterVariable (&gl_fogend);
253         }
254 }
255
256 void gl_main_start(void)
257 {
258 }
259
260 void gl_main_shutdown(void)
261 {
262 }
263
264 void gl_main_newmap(void)
265 {
266 }
267
268 void GL_Main_Init(void)
269 {
270         int a;
271         FOG_registercvars();
272         // LordHavoc: setup 1.0f / N table for quick recipricols of integers
273         ixtable[0] = 0;
274         for (a = 1;a < 4096;a++)
275                 ixtable[a] = 1.0f / a;
276         Cvar_RegisterVariable (&r_drawentities);
277         Cvar_RegisterVariable (&r_drawviewmodel);
278         Cvar_RegisterVariable (&r_speeds);
279         Cvar_RegisterVariable (&r_speeds2);
280         Cvar_RegisterVariable (&gl_lightmode);
281 //      Cvar_RegisterVariable (&r_dynamicwater);
282 //      Cvar_RegisterVariable (&r_dynamicbothsides);
283         Cvar_RegisterVariable (&r_fullbrights);
284         Cvar_RegisterVariable (&r_wateralpha);
285         Cvar_RegisterVariable (&r_dynamic);
286         Cvar_RegisterVariable (&r_waterripple);
287         Cvar_RegisterVariable (&r_farclip);
288         if (nehahra)
289                 Cvar_SetValue("r_fullbrights", 0);
290 //      if (gl_vendor && strstr(gl_vendor, "3Dfx"))
291 //              gl_lightmode.value = 0;
292         Cvar_RegisterVariable (&r_fullbright);
293         Cvar_RegisterVariable (&r_ser);
294         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
295 }
296
297 extern void GL_Draw_Init(void);
298 extern void GL_Main_Init(void);
299 extern void GL_Models_Init(void);
300 extern void GL_Poly_Init(void);
301 extern void GL_Surf_Init(void);
302 extern void GL_Screen_Init(void);
303 extern void GL_Misc_Init(void);
304 extern void R_Crosshairs_Init(void);
305 extern void R_Light_Init(void);
306 extern void R_Particles_Init(void);
307 extern void R_Explosion_Init(void);
308 extern void CL_Effects_Init(void);
309 extern void R_Clip_Init(void);
310 extern void ui_init(void);
311
312 void Render_Init(void)
313 {
314         R_Modules_Shutdown();
315         R_Clip_Init();
316         GL_Draw_Init();
317         GL_Main_Init();
318         GL_Models_Init();
319         GL_Poly_Init();
320         GL_Surf_Init();
321         GL_Screen_Init();
322         GL_Misc_Init();
323         R_Crosshairs_Init();
324         R_Light_Init();
325         R_Particles_Init();
326         R_Explosion_Init();
327         CL_Effects_Init();
328         R_Decals_Init();
329         ui_init();
330         R_Modules_Start();
331 }
332
333 /*
334 ===============
335 GL_Init
336 ===============
337 */
338 extern char *ENGINE_EXTENSIONS;
339 void GL_Init (void)
340 {
341         gl_vendor = glGetString (GL_VENDOR);
342         Con_Printf ("GL_VENDOR: %s\n", gl_vendor);
343         gl_renderer = glGetString (GL_RENDERER);
344         Con_Printf ("GL_RENDERER: %s\n", gl_renderer);
345
346         gl_version = glGetString (GL_VERSION);
347         Con_Printf ("GL_VERSION: %s\n", gl_version);
348         gl_extensions = glGetString (GL_EXTENSIONS);
349         Con_Printf ("GL_EXTENSIONS: %s\n", gl_extensions);
350
351 //      Con_Printf ("%s %s\n", gl_renderer, gl_version);
352
353         VID_CheckMultitexture();
354         VID_CheckCVA();
355
356         // LordHavoc: report supported extensions
357         Con_Printf ("\nengine extensions: %s\n", ENGINE_EXTENSIONS);
358
359         glCullFace(GL_FRONT);
360         glEnable(GL_TEXTURE_2D);
361 //      glDisable(GL_ALPHA_TEST);
362         glAlphaFunc(GL_GREATER, 0.5);
363
364 //      glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
365 }
366
367
368 /*
369 void R_RotateForEntity (entity_t *e)
370 {
371         glTranslatef (e->origin[0],  e->origin[1],  e->origin[2]);
372
373         glRotatef (e->angles[1],  0, 0, 1);
374         glRotatef (-e->angles[0],  0, 1, 0);
375         glRotatef (e->angles[2],  1, 0, 0);
376
377         glScalef (e->scale, e->scale, e->scale); // LordHavoc: model scale
378 }
379 */
380
381 // LordHavoc: shading stuff
382 vec3_t  shadevector;
383 vec3_t  shadecolor;
384
385 float   modelalpha;
386
387 //==================================================================================
388
389 void R_LerpUpdate(entity_t *ent)
390 {
391         int frame;
392         frame = ent->render.frame;
393         if (ent->render.model && ent->render.frame >= ent->render.model->numframes)
394         {
395                 Con_Printf("R_LerpUpdate: no such frame%6i in \"%s\"\n", ent->render.frame, ent->render.model->name);
396                 frame = 0;
397         }
398
399         if (ent->render.lerp_model != ent->render.model)
400         {
401                 // reset all interpolation information
402                 ent->render.lerp_model = ent->render.model;
403                 ent->render.frame1 = ent->render.frame2 = frame;
404                 ent->render.frame1start = ent->render.frame2start = cl.time;
405                 ent->render.framelerp = 1;
406                 ent->render.lerp_starttime = 0;
407         }
408         else if (ent->render.frame2 != frame)
409         {
410                 // transition to new frame
411                 ent->render.frame1 = ent->render.frame2;
412                 ent->render.frame1start = ent->render.frame2start;
413                 ent->render.frame2 = frame;
414                 ent->render.frame2start = cl.time;
415                 ent->render.framelerp = 0;
416                 ent->render.lerp_starttime = cl.time;
417         }
418         else
419         {
420                 // lerp_starttime < 0 is used to prevent changing of framelerp
421                 if (ent->render.lerp_starttime >= 0)
422                 {
423                         // update transition
424                         ent->render.framelerp = (cl.time - ent->render.lerp_starttime) * 10;
425                         ent->render.framelerp = bound(0, ent->render.framelerp, 1);
426                 }
427         }
428 }
429
430
431 void R_PrepareEntities (void)
432 {
433         int i;
434         entity_t *ent;
435         vec3_t v;
436         // this updates entities that are supposed to be view relative
437         for (i = 0;i < cl_numvisedicts;i++)
438         {
439                 ent = cl_visedicts[i];
440
441                 if (ent->render.flags & RENDER_VIEWMODEL)
442                 {
443                         // remove flag so it will not be repeated incase RelinkEntities is not called again for a while
444                         ent->render.flags -= RENDER_VIEWMODEL;
445                         // transform origin
446                         VectorCopy(ent->render.origin, v);
447                         ent->render.origin[0] = v[0] * vpn[0] + v[1] * vright[0] + v[2] * vup[0] + r_origin[0];
448                         ent->render.origin[1] = v[0] * vpn[1] + v[1] * vright[1] + v[2] * vup[1] + r_origin[1];
449                         ent->render.origin[2] = v[0] * vpn[2] + v[1] * vright[2] + v[2] * vup[2] + r_origin[2];
450                         // adjust angles
451                         VectorAdd(ent->render.angles, r_refdef.viewangles, ent->render.angles);
452                 }
453         }
454 }
455
456 void R_Entity_Callback(void *data, void *junk)
457 {
458         ((entity_t *)data)->render.visframe = r_framecount;
459 }
460
461 void R_AddModelEntities (void)
462 {
463         int             i;
464         vec3_t  mins, maxs;
465         frameblend_t blend[4];
466
467         if (!r_drawentities.value)
468                 return;
469
470         for (i = 0;i < cl_numvisedicts;i++)
471         {
472                 currententity = cl_visedicts[i];
473                 if (currententity->render.model->type == mod_brush)
474                 {
475                         modelalpha = currententity->render.alpha;
476                         R_DrawBrushModel (currententity);
477                 }
478                 else if (currententity->render.model->type == mod_alias)
479                 {
480                         VectorAdd(currententity->render.origin, currententity->render.model->mins, mins);
481                         VectorAdd(currententity->render.origin, currententity->render.model->maxs, maxs);
482                         if (r_ser.value)
483                                 R_Clip_AddBox(mins, maxs, R_Entity_Callback, currententity, NULL);
484                         else if (R_NotCulledBox(mins, maxs))
485                                 currententity->render.visframe = r_framecount;
486                 }
487                 else if (currententity->render.model->type == mod_sprite)
488                 {
489                         R_LerpUpdate(currententity);
490                         if (r_ser.value)
491                         {
492                                 R_LerpAnimation(currententity->render.model, currententity->render.frame1, currententity->render.frame2, currententity->render.frame1start, currententity->render.frame2start, currententity->render.framelerp, blend);
493                                 R_ClipSprite(currententity, blend);
494                         }
495                         else
496                         {
497                                 VectorAdd(currententity->render.origin, currententity->render.model->mins, mins);
498                                 VectorAdd(currententity->render.origin, currententity->render.model->maxs, maxs);
499                                 if (R_NotCulledBox(mins, maxs))
500                                         currententity->render.visframe = r_framecount;
501                         }
502                 }
503         }
504 }
505
506 /*
507 =============
508 R_DrawEntitiesOnList
509 =============
510 */
511 /*
512 void R_DrawEntitiesOnList1 (void)
513 {
514         int             i;
515
516         if (!r_drawentities.value)
517                 return;
518
519         for (i = 0;i < cl_numvisedicts;i++)
520         {
521                 if (cl_visedicts[i]->render.visframe != r_framecount)
522                         continue;
523                 if (cl_visedicts[i]->render.model->type != mod_brush)
524                         continue;
525                 currententity = cl_visedicts[i];
526                 modelalpha = currententity->render.alpha;
527
528                 R_DrawBrushModel (currententity);
529         }
530 }
531 */
532
533 void R_DrawModels (void)
534 {
535         int             i;
536         frameblend_t blend[4];
537 //      vec3_t  mins, maxs;
538
539         if (!r_drawentities.value)
540                 return;
541
542         for (i = 0;i < cl_numvisedicts;i++)
543         {
544                 if (cl_visedicts[i]->render.visframe != r_framecount)
545                         continue;
546                 currententity = cl_visedicts[i];
547                 if (currententity->render.model->type != mod_alias && currententity->render.model->type != mod_sprite)
548                         continue;
549
550                 modelalpha = currententity->render.alpha;
551
552                 if (currententity->render.model->type == mod_alias)
553                 {
554                         // only lerp models here because sprites were already lerped for their clip polygon
555                         R_LerpUpdate(currententity);
556                         R_LerpAnimation(currententity->render.model, currententity->render.frame1, currententity->render.frame2, currententity->render.frame1start, currententity->render.frame2start, currententity->render.framelerp, blend);
557                         R_DrawAliasModel (currententity, true, modelalpha, currententity->render.model, blend, currententity->render.skinnum, currententity->render.origin, currententity->render.angles, currententity->render.scale, currententity->render.effects, currententity->render.model->flags, currententity->render.colormap);
558                 }
559                 else //if (currententity->render.model->type == mod_sprite)
560                 {
561                         // build blend array
562                         R_LerpAnimation(currententity->render.model, currententity->render.frame1, currententity->render.frame2, currententity->render.frame1start, currententity->render.frame2start, currententity->render.framelerp, blend);
563                         R_DrawSpriteModel (currententity, blend);
564                 }
565
566                 /*
567                 VectorAdd(cl_visedicts[i]->render.origin, cl_visedicts[i]->render.model->mins, mins);
568                 VectorAdd(cl_visedicts[i]->render.origin, cl_visedicts[i]->render.model->maxs, maxs);
569
570                 switch (cl_visedicts[i]->render.model->type)
571                 {
572                 case mod_alias:
573                         R_Clip_AddBox(mins, maxs, R_DrawModelCallback, cl_visedicts[i], NULL);
574                         break;
575                 case mod_sprite:
576                         R_Clip_AddBox(mins, maxs, R_DrawSpriteCallback, cl_visedicts[i], NULL);
577                         break;
578                 }
579                 */
580         }
581 }
582
583 /*
584 =============
585 R_DrawViewModel
586 =============
587 */
588 void R_DrawViewModel (void)
589 {
590         frameblend_t blend[4];
591
592         if (!r_drawviewmodel.value || chase_active.value || envmap || !r_drawentities.value || cl.items & IT_INVISIBILITY || cl.stats[STAT_HEALTH] <= 0 || !cl.viewent.render.model)
593                 return;
594
595         currententity = &cl.viewent;
596         currententity->render.alpha = modelalpha = cl_entities[cl.viewentity].render.alpha; // LordHavoc: if the player is transparent, so is the gun
597         currententity->render.effects = cl_entities[cl.viewentity].render.effects;
598         currententity->render.scale = 1;
599         VectorCopy(cl_entities[cl.viewentity].render.colormod, currententity->render.colormod);
600
601         R_LerpUpdate(currententity);
602         R_LerpAnimation(currententity->render.model, currententity->render.frame1, currententity->render.frame2, currententity->render.frame1start, currententity->render.frame2start, currententity->render.framelerp, blend);
603
604         // hack the depth range to prevent view model from poking into walls
605         glDepthRange (gldepthmin, gldepthmin + 0.3*(gldepthmax-gldepthmin));
606         R_DrawAliasModel (currententity, false, modelalpha, currententity->render.model, blend, currententity->render.skinnum, currententity->render.origin, currententity->render.angles, currententity->render.scale, currententity->render.effects, currententity->render.model->flags, currententity->render.colormap);
607         glDepthRange (gldepthmin, gldepthmax);
608 }
609
610 void R_DrawBrushModel (entity_t *e);
611
612 void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees );
613
614 void R_SetFrustum (void)
615 {
616         int             i;
617
618         // LordHavoc: note to all quake engine coders, this code was making the
619         // view frustum taller than it should have been (it assumed the view is
620         // square; it is not square), so I disabled it
621         /*
622         if (r_refdef.fov_x == 90)
623         {
624                 // front side is visible
625
626                 VectorAdd (vpn, vright, frustum[0].normal);
627                 VectorSubtract (vpn, vright, frustum[1].normal);
628
629                 VectorAdd (vpn, vup, frustum[2].normal);
630                 VectorSubtract (vpn, vup, frustum[3].normal);
631         }
632         else
633         {
634         */
635                 // rotate VPN right by FOV_X/2 degrees
636                 RotatePointAroundVector( frustum[0].normal, vup, vpn, -(90-r_refdef.fov_x / 2 ) );
637                 // rotate VPN left by FOV_X/2 degrees
638                 RotatePointAroundVector( frustum[1].normal, vup, vpn, 90-r_refdef.fov_x / 2 );
639                 // rotate VPN up by FOV_X/2 degrees
640                 RotatePointAroundVector( frustum[2].normal, vright, vpn, 90-r_refdef.fov_y / 2 );
641                 // rotate VPN down by FOV_X/2 degrees
642                 RotatePointAroundVector( frustum[3].normal, vright, vpn, -( 90 - r_refdef.fov_y / 2 ) );
643         //}
644
645         for (i=0 ; i<4 ; i++)
646         {
647                 frustum[i].type = PLANE_ANYZ;
648                 frustum[i].dist = DotProduct (r_origin, frustum[i].normal);
649 //              frustum[i].signbits = SignbitsForPlane (&frustum[i]);
650                 PlaneClassify(&frustum[i]);
651         }
652 }
653
654 void R_AnimateLight (void);
655 void V_CalcBlend (void);
656
657 /*
658 ===============
659 R_SetupFrame
660 ===============
661 */
662 void R_SetupFrame (void)
663 {
664 // don't allow cheats in multiplayer
665         if (cl.maxclients > 1)
666         {
667                 Cvar_Set ("r_fullbright", "0");
668                 Cvar_Set ("r_ambient", "0");
669         }
670
671         r_framecount++;
672
673 // build the transformation matrix for the given view angles
674         VectorCopy (r_refdef.vieworg, r_origin);
675
676         AngleVectors (r_refdef.viewangles, vpn, vright, vup);
677
678 // current viewleaf
679         r_oldviewleaf = r_viewleaf;
680         r_viewleaf = Mod_PointInLeaf (r_origin, cl.worldmodel);
681
682         V_SetContentsColor (r_viewleaf->contents);
683         V_CalcBlend ();
684
685         r_cache_thrash = false;
686
687         c_brush_polys = 0;
688         c_alias_polys = 0;
689         c_light_polys = 0;
690         c_faces = 0;
691         c_nodes = 0;
692         c_leafs = 0;
693         c_models = 0;
694         c_bmodels = 0;
695         c_sprites = 0;
696         c_particles = 0;
697 //      c_dlights = 0;
698
699         R_AnimateLight ();
700 }
701
702
703 void MYgluPerspective( GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar )
704 {
705    GLdouble xmin, xmax, ymin, ymax;
706
707    ymax = zNear * tan( fovy * M_PI / 360.0 );
708    ymin = -ymax;
709
710    xmin = ymin * aspect;
711    xmax = ymax * aspect;
712
713    glFrustum( xmin, xmax, ymin, ymax, zNear, zFar );
714 }
715
716
717 /*
718 =============
719 R_SetupGL
720 =============
721 */
722 void R_SetupGL (void)
723 {
724         float   screenaspect;
725         int             x, x2, y2, y, w, h;
726
727         if (!r_render.value)
728                 return;
729         //
730         // set up viewpoint
731         //
732         glMatrixMode(GL_PROJECTION);
733     glLoadIdentity ();
734         x = r_refdef.vrect.x * glwidth/vid.width;
735         x2 = (r_refdef.vrect.x + r_refdef.vrect.width) * glwidth/vid.width;
736         y = (vid.height-r_refdef.vrect.y) * glheight/vid.height;
737         y2 = (vid.height - (r_refdef.vrect.y + r_refdef.vrect.height)) * glheight/vid.height;
738
739         // fudge around because of frac screen scale
740         if (x > 0)
741                 x--;
742         if (x2 < glwidth)
743                 x2++;
744         if (y2 < 0)
745                 y2--;
746         if (y < glheight)
747                 y++;
748
749         w = x2 - x;
750         h = y - y2;
751
752         if (envmap)
753         {
754                 x = y2 = 0;
755                 w = h = 256;
756         }
757
758         glViewport (glx + x, gly + y2, w, h);
759     screenaspect = (float)r_refdef.vrect.width/r_refdef.vrect.height;
760 //      yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*180/M_PI;
761         MYgluPerspective (r_refdef.fov_y,  screenaspect,  4,  r_farclip.value);
762
763         glCullFace(GL_FRONT);
764
765         glMatrixMode(GL_MODELVIEW);
766     glLoadIdentity ();
767
768     glRotatef (-90,  1, 0, 0);      // put Z going up
769     glRotatef (90,  0, 0, 1);       // put Z going up
770     glRotatef (-r_refdef.viewangles[2],  1, 0, 0);
771     glRotatef (-r_refdef.viewangles[0],  0, 1, 0);
772     glRotatef (-r_refdef.viewangles[1],  0, 0, 1);
773     glTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);
774
775         glGetFloatv (GL_MODELVIEW_MATRIX, r_world_matrix);
776
777         //
778         // set drawing parms
779         //
780 //      if (gl_cull.value)
781                 glEnable(GL_CULL_FACE);
782 //      else
783 //              glDisable(GL_CULL_FACE);
784
785         glEnable(GL_BLEND); // was Disable
786         glDisable(GL_ALPHA_TEST);
787         glAlphaFunc(GL_GREATER, 0.5);
788         glEnable(GL_DEPTH_TEST);
789         glDepthMask(1);
790         glShadeModel(GL_SMOOTH);
791 }
792
793 /*
794 =============
795 R_Clear
796 =============
797 */
798 void R_Clear (void)
799 {
800         if (!r_render.value)
801                 return;
802 //      glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // LordHavoc: moved to SCR_UpdateScreen
803         gldepthmin = 0;
804         gldepthmax = 1;
805         glDepthFunc (GL_LEQUAL);
806
807         glDepthRange (gldepthmin, gldepthmax);
808 }
809
810 // LordHavoc: my trick to *FIX* GLQuake lighting once and for all :)
811 void GL_Brighten(void)
812 {
813         if (!r_render.value)
814                 return;
815         glMatrixMode(GL_PROJECTION);
816     glLoadIdentity ();
817         glOrtho  (0, vid.width, vid.height, 0, -99999, 99999);
818         glMatrixMode(GL_MODELVIEW);
819     glLoadIdentity ();
820         glDisable (GL_DEPTH_TEST);
821         glDisable (GL_CULL_FACE);
822         glDisable(GL_TEXTURE_2D);
823         glEnable(GL_BLEND);
824         glBlendFunc (GL_DST_COLOR, GL_ONE);
825         glBegin (GL_TRIANGLES);
826         glColor3f (1, 1, 1);
827         glVertex2f (-5000, -5000);
828         glVertex2f (10000, -5000);
829         glVertex2f (-5000, 10000);
830         glEnd ();
831         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
832         glDisable(GL_BLEND);
833         glEnable(GL_TEXTURE_2D);
834         glEnable (GL_DEPTH_TEST);
835         glEnable (GL_CULL_FACE);
836 }
837
838 void GL_BlendView(void)
839 {
840         if (!r_render.value)
841                 return;
842
843         if (v_blend[3] < 0.01f)
844                 return;
845
846         glMatrixMode(GL_PROJECTION);
847     glLoadIdentity ();
848         glOrtho  (0, vid.width, vid.height, 0, -99999, 99999);
849         glMatrixMode(GL_MODELVIEW);
850     glLoadIdentity ();
851         glDisable (GL_DEPTH_TEST);
852         glDisable (GL_CULL_FACE);
853         glDisable(GL_TEXTURE_2D);
854         glEnable(GL_BLEND);
855         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
856         glBegin (GL_TRIANGLES);
857         if (lighthalf)
858                 glColor4f (v_blend[0] * 0.5f, v_blend[1] * 0.5f, v_blend[2] * 0.5f, v_blend[3]);
859         else
860                 glColor4fv (v_blend);
861         glVertex2f (-5000, -5000);
862         glVertex2f (10000, -5000);
863         glVertex2f (-5000, 10000);
864         glEnd ();
865
866         glEnable (GL_CULL_FACE);
867         glEnable (GL_DEPTH_TEST);
868         glDisable(GL_BLEND);
869         glEnable(GL_TEXTURE_2D);
870 }
871
872 /*
873 ================
874 R_RenderView
875
876 r_refdef must be set before the first call
877 ================
878 */
879 extern void R_Sky(void);
880 extern void UploadLightmaps(void);
881 extern void R_DrawSurfaces(void);
882 extern void R_DrawPortals(void);
883 char r_speeds2_string[1024];
884 int speedstringcount;
885
886 void timestring(int t, char *desc)
887 {
888         char tempbuf[256];
889         int length;
890         if (t < 1000000)
891                 sprintf(tempbuf, " %6ius %s", t, desc);
892         else
893                 sprintf(tempbuf, " %6ims %s", t / 1000, desc);
894         length = strlen(tempbuf);
895 //      while (length < 20)
896 //              tempbuf[length++] = ' ';
897 //      tempbuf[length] = 0;
898         if (speedstringcount + length > 80)
899         {
900                 strcat(r_speeds2_string, "\n");
901                 speedstringcount = 0;
902         }
903         // skip the space at the beginning if it's the first on the line
904         if (speedstringcount == 0)
905         {
906                 strcat(r_speeds2_string, tempbuf + 1);
907                 speedstringcount = length - 1;
908         }
909         else
910         {
911                 strcat(r_speeds2_string, tempbuf);
912                 speedstringcount += length;
913         }
914 }
915
916 #define TIMEREPORT(NAME) \
917         if (r_speeds2.value)\
918         {\
919                 temptime = currtime;\
920                 currtime = Sys_DoubleTime();\
921                 timestring((int) ((currtime - temptime) * 1000000.0), NAME);\
922         }
923
924 void R_RenderView (void)
925 {
926         double starttime, currtime, temptime;
927 //      if (r_norefresh.value)
928 //              return;
929
930         if (!cl.worldmodel)
931                 Host_Error ("R_RenderView: NULL worldmodel");
932
933         if (r_speeds2.value)
934         {
935                 starttime = currtime = Sys_DoubleTime();
936
937                 speedstringcount = 0;
938                 sprintf(r_speeds2_string, "org:'%c%6.2f %c%6.2f %c%6.2f' ang:'%c%3.0f %c%3.0f %c%3.0f' dir:'%c%2.3f %c%2.3f %c%2.3f'\n%6i walls %6i dlitwalls %7i modeltris %7i transpoly\nBSP: %6i faces %6i nodes %6i leafs\n%4i models %4i bmodels %4i sprites %5i particles %3i dlights\n",
939                         r_origin[0] < 0 ? '-' : ' ', fabs(r_origin[0]), r_origin[1] < 0 ? '-' : ' ', fabs(r_origin[1]), r_origin[2] < 0 ? '-' : ' ', fabs(r_origin[2]), r_refdef.viewangles[0] < 0 ? '-' : ' ', fabs(r_refdef.viewangles[0]), r_refdef.viewangles[1] < 0 ? '-' : ' ', fabs(r_refdef.viewangles[1]), r_refdef.viewangles[2] < 0 ? '-' : ' ', fabs(r_refdef.viewangles[2]), vpn[0] < 0 ? '-' : ' ', fabs(vpn[0]), vpn[1] < 0 ? '-' : ' ', fabs(vpn[1]), vpn[2] < 0 ? '-' : ' ', fabs(vpn[2]),
940                         c_brush_polys, c_light_polys, c_alias_polys, currenttranspoly,
941                         c_faces, c_nodes, c_leafs,
942                         c_models, c_bmodels, c_sprites, c_particles, c_dlights);
943         }
944         else
945                 starttime = currtime = 0;
946
947         R_MoveParticles ();
948         R_MoveExplosions();
949
950         lighthalf = gl_lightmode.value;
951
952         FOG_framebegin();
953
954         R_Clear();
955         TIMEREPORT("clear     ")
956
957         // render normal view
958
959         R_SetupFrame ();
960         R_SetFrustum ();
961         R_SetupGL ();
962         R_Clip_StartFrame();
963
964         R_PrepareEntities();
965
966         skypolyclear();
967         wallpolyclear();
968         transpolyclear();
969
970         TIMEREPORT("setup     ")
971
972         R_DrawWorld ();
973         TIMEREPORT("world     ")
974
975         R_AddModelEntities();
976         TIMEREPORT("addmodels")
977
978         R_Clip_EndFrame();
979         TIMEREPORT("scanedge  ")
980
981         // now mark the lit surfaces
982         R_PushDlights ();
983         // yes this does add the world surfaces after the brush models
984         R_DrawSurfaces ();
985         R_DrawPortals ();
986         TIMEREPORT("surfaces  ");
987
988         UploadLightmaps();
989         TIMEREPORT("uploadlmap")
990
991         // fogged sky polys, affects depth
992         skypolyrender();
993
994         // does not affect depth, draws over the sky polys
995         if (currentskypoly)
996                 R_Sky();
997         TIMEREPORT("skypoly   ")
998
999         wallpolyrender();
1000         TIMEREPORT("wallpoly  ")
1001
1002         GL_DrawDecals();
1003         TIMEREPORT("ddecal    ")
1004
1005         // don't let sound skip if going slow
1006         if (!intimerefresh && !r_speeds2.value)
1007                 S_ExtraUpdate ();
1008
1009         R_DrawViewModel ();
1010         R_DrawModels ();
1011         TIMEREPORT("models    ")
1012
1013         R_DrawParticles ();
1014         TIMEREPORT("dparticles")
1015         R_DrawExplosions();
1016         TIMEREPORT("dexplosion")
1017
1018         transpolyrender();
1019         TIMEREPORT("transpoly ")
1020
1021         FOG_frameend();
1022
1023         GL_BlendView();
1024         TIMEREPORT("blend     ")
1025
1026         if (r_speeds2.value)
1027                 timestring((int) ((Sys_DoubleTime() - starttime) * 1000000.0), "total    ");
1028 }