lighthalf related transpoly cleanup
[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 entity_t        r_worldentity;
25
26 qboolean        r_cache_thrash;         // compatability
27
28 vec3_t          modelorg, r_entorigin;
29 entity_t        *currententity;
30
31 int                     r_visframecount;        // bumped when going to a new PVS
32 int                     r_framecount;           // used for dlight push checking
33
34 mplane_t        frustum[4];
35
36 int                     c_brush_polys, c_alias_polys, c_light_polys, c_nodes, c_leafs;
37
38 qboolean        envmap;                         // true during envmap command capture 
39
40 // LordHavoc: moved all code related to particles into r_part.c
41 //int                   particletexture;        // little dot for particles
42 int                     playertextures;         // up to 16 color translated skins
43
44 extern qboolean isG200, isRagePro; // LordHavoc: special card hacks
45
46 //
47 // view origin
48 //
49 vec3_t  vup;
50 vec3_t  vpn;
51 vec3_t  vright;
52 vec3_t  r_origin;
53
54 float   r_world_matrix[16];
55 float   r_base_world_matrix[16];
56
57 //
58 // screen size info
59 //
60 refdef_t        r_refdef;
61
62 mleaf_t         *r_viewleaf, *r_oldviewleaf;
63
64 texture_t       *r_notexture_mip;
65
66 int             d_lightstylevalue[256]; // 8.8 fraction of base light value
67
68
69 void R_MarkLeaves (void);
70
71 //cvar_t        r_norefresh = {"r_norefresh","0"};
72 cvar_t  r_drawentities = {"r_drawentities","1"};
73 cvar_t  r_drawviewmodel = {"r_drawviewmodel","1"};
74 cvar_t  r_speeds = {"r_speeds","0"};
75 cvar_t  r_speeds2 = {"r_speeds2","0"};
76 cvar_t  r_fullbright = {"r_fullbright","0"};
77 //cvar_t        r_lightmap = {"r_lightmap","0"};
78 cvar_t  r_shadows = {"r_shadows","0"};
79 cvar_t  r_wateralpha = {"r_wateralpha","1"};
80 cvar_t  r_dynamic = {"r_dynamic","1"};
81 cvar_t  r_novis = {"r_novis","0"};
82 cvar_t  r_waterripple = {"r_waterripple","0"};
83 cvar_t  r_fullbrights = {"r_fullbrights", "1"};
84
85 //cvar_t        gl_cull = {"gl_cull","1"};
86 //cvar_t        gl_affinemodels = {"gl_affinemodels","0"};
87 //cvar_t        gl_polyblend = {"gl_polyblend","1"};
88 cvar_t  gl_playermip = {"gl_playermip","0"};
89 //cvar_t        gl_nocolors = {"gl_nocolors","0"};
90 //cvar_t        gl_keeptjunctions = {"gl_keeptjunctions","1"};
91 //cvar_t        gl_reporttjunctions = {"gl_reporttjunctions","0"};
92 cvar_t  contrast = {"contrast", "1.0", TRUE}; // LordHavoc: a method of operating system independent color correction
93 cvar_t  brightness = {"brightness", "1.0", TRUE}; // LordHavoc: a method of operating system independent color correction
94 cvar_t  gl_lightmode = {"gl_lightmode", "1", TRUE}; // LordHavoc: overbright lighting
95 //cvar_t        r_dynamicwater = {"r_dynamicwater", "1"};
96 //cvar_t        r_dynamicbothsides = {"r_dynamicbothsides", "1"}; // LordHavoc: can disable dynamic lighting of backfaces, but quake maps are weird so it doesn't always work right...
97 cvar_t  r_farclip = {"r_farclip", "6144"};
98
99 cvar_t  gl_fogenable = {"gl_fogenable", "0"};
100 cvar_t  gl_fogdensity = {"gl_fogdensity", "0.25"};
101 cvar_t  gl_fogred = {"gl_fogred","0.3"};
102 cvar_t  gl_foggreen = {"gl_foggreen","0.3"};
103 cvar_t  gl_fogblue = {"gl_fogblue","0.3"};
104 cvar_t  gl_fogstart = {"gl_fogstart", "0"};
105 cvar_t  gl_fogend = {"gl_fogend","0"};
106 cvar_t  glfog = {"glfog", "0"};
107
108 int chrometexture;
109
110 void makechrometextures()
111 {
112         int x, y, g, g2, amplitude, noise[64][64], min, max;
113         byte data[64][64][4];
114         //
115         // particle texture
116         //
117         chrometexture = texture_extension_number++;
118     glBindTexture(GL_TEXTURE_2D, chrometexture);
119
120 #define n(x,y) noise[(y)&63][(x)&63]
121
122         amplitude = 16777215;
123         g2 = 64;
124         noise[0][0] = 0;
125         for (;(g = g2 >> 1) >= 1;g2 >>= 1)
126         {
127                 // subdivide, diamond-square algorythm (really this has little to do with squares)
128                 // diamond
129                 for (y = 0;y < 64;y += g2)
130                         for (x = 0;x < 64;x += g2)
131                                 n(x+g,y+g) = (n(x,y) + n(x+g2,y) + n(x,y+g2) + n(x+g2,y+g2)) >> 2;
132                 // square
133                 for (y = 0;y < 64;y += g2)
134                         for (x = 0;x < 64;x += g2)
135                         {
136                                 n(x+g,y) = (n(x,y) + n(x+g2,y) + n(x+g,y-g) + n(x+g,y+g)) >> 2;
137                                 n(x,y+g) = (n(x,y) + n(x,y+g2) + n(x-g,y+g) + n(x+g,y+g)) >> 2;
138                         }
139                 // brownian motion theory
140                 amplitude >>= 1;
141                 for (y = 0;y < 64;y += g)
142                         for (x = 0;x < 64;x += g)
143                                 noise[y][x] += rand()&amplitude;
144         }
145         // normalize the noise range
146         min = max = 0;
147         for (y = 0;y < 64;y++)
148                 for (x = 0;x < 64;x++)
149                 {
150                         if (n(x,y) < min) min = n(x,y);
151                         if (n(x,y) > max) max = n(x,y);
152                 }
153         max -= min;
154         for (y = 0;y < 64;y++)
155                 for (x = 0;x < 64;x++)
156                         n(x,y) = (n(x,y) - min) * 255 / max;
157
158 #undef n
159
160         // convert to RGBA data
161         for (y = 0;y < 64;y++)
162                 for (x = 0;x < 64;x++)
163                 {
164                         data[y][x][0] = data[y][x][1] = data[y][x][2] = (byte) noise[y][x];
165                         data[y][x][3] = 255;
166                 }
167
168         glTexImage2D (GL_TEXTURE_2D, 0, 4, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
169
170         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
171
172         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
173         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
174 }
175
176 extern qboolean isRagePro;
177
178 qboolean lighthalf;
179
180 vec3_t fogcolor;
181 vec_t fogdensity;
182 float fog_density, fog_red, fog_green, fog_blue;
183 qboolean fogenabled;
184 qboolean oldgl_fogenable;
185 void FOG_framebegin()
186 {
187         if (nehahra)
188         {
189 //              if (!Nehahrademcompatibility)
190 //                      gl_fogenable.value = 0;
191                 if (gl_fogenable.value)
192                 {
193                         oldgl_fogenable = true;
194                         fog_density = gl_fogdensity.value;
195                         fog_red = gl_fogred.value;
196                         fog_green = gl_foggreen.value;
197                         fog_blue = gl_fogblue.value;
198                 }
199                 else if (oldgl_fogenable)
200                 {
201                         oldgl_fogenable = false;
202                         fog_density = 0;
203                         fog_red = 0;
204                         fog_green = 0;
205                         fog_blue = 0;
206                 }
207         }
208         if (glfog.value)
209         {
210                 if(fog_density)
211                 {
212                         // LordHavoc: Borland C++ 5.0 was choking on this line, stupid compiler...
213                         //GLfloat colors[4] = {(GLfloat) gl_fogred.value, (GLfloat) gl_foggreen.value, (GLfloat) gl_fogblue.value, (GLfloat) 1};
214                         GLfloat colors[4];
215                         colors[0] = fog_red;
216                         colors[1] = fog_green;
217                         colors[2] = fog_blue;
218                         colors[3] = 1;
219                         if (lighthalf)
220                         {
221                                 colors[0] *= 0.5f;
222                                 colors[1] *= 0.5f;
223                                 colors[2] *= 0.5f;
224                         }
225
226                         glFogi (GL_FOG_MODE, GL_EXP2);
227                         glFogf (GL_FOG_DENSITY, (GLfloat) fog_density / 100); 
228                         glFogfv (GL_FOG_COLOR, colors);
229                         glEnable (GL_FOG);
230                 }
231                 else
232                         glDisable(GL_FOG);
233         }
234         else
235         {
236                 if (fog_density)
237                 {
238                         fogenabled = true;
239                         fogdensity = -4000.0f / (fog_density * fog_density);
240                         fogcolor[0] = fog_red   = bound(0.0f, fog_red  , 1.0f);
241                         fogcolor[1] = fog_green = bound(0.0f, fog_green, 1.0f);
242                         fogcolor[2] = fog_blue  = bound(0.0f, fog_blue , 1.0f);
243                         if (lighthalf)
244                         {
245                                 fogcolor[0] *= 0.5f;
246                                 fogcolor[1] *= 0.5f;
247                                 fogcolor[2] *= 0.5f;
248                         }
249                 }
250                 else
251                         fogenabled = false;
252         }
253 }
254
255 void FOG_frameend()
256 {
257         if (glfog.value)
258                 glDisable(GL_FOG);
259 }
260
261 void FOG_clear()
262 {
263         if (nehahra)
264         {
265                 Cvar_Set("gl_fogenable", "0");
266                 Cvar_Set("gl_fogdensity", "0.2");
267                 Cvar_Set("gl_fogred", "0.3");
268                 Cvar_Set("gl_foggreen", "0.3");
269                 Cvar_Set("gl_fogblue", "0.3");
270         }
271         fog_density = fog_red = fog_green = fog_blue = 0.0f;
272 }
273
274 void FOG_registercvars()
275 {
276         Cvar_RegisterVariable (&glfog);
277         if (nehahra)
278         {
279                 Cvar_RegisterVariable (&gl_fogenable);
280                 Cvar_RegisterVariable (&gl_fogdensity);
281                 Cvar_RegisterVariable (&gl_fogred);
282                 Cvar_RegisterVariable (&gl_foggreen); 
283                 Cvar_RegisterVariable (&gl_fogblue);
284                 Cvar_RegisterVariable (&gl_fogstart);
285                 Cvar_RegisterVariable (&gl_fogend);
286         }
287 }
288
289 void glpoly_init();
290 void glrsurf_init();
291 void rlight_init();
292
293 // LordHavoc: vertex array
294 float *aliasvert;
295 float *aliasvertnorm;
296 byte *aliasvertcolor;
297
298 void rmain_registercvars()
299 {
300         // allocate vertex processing arrays
301         aliasvert = malloc(sizeof(float[MD2MAX_VERTS][3]));
302         aliasvertnorm = malloc(sizeof(float[MD2MAX_VERTS][3]));
303         aliasvertcolor = malloc(sizeof(byte[MD2MAX_VERTS][4]));
304
305         FOG_registercvars();
306         Cvar_RegisterVariable (&r_speeds2);
307         Cvar_RegisterVariable (&contrast);
308         Cvar_RegisterVariable (&brightness);
309         Cvar_RegisterVariable (&gl_lightmode);
310 //      Cvar_RegisterVariable (&r_dynamicwater);
311 //      Cvar_RegisterVariable (&r_dynamicbothsides);
312         Cvar_RegisterVariable (&r_fullbrights);
313         if (nehahra)
314                 Cvar_SetValue("r_fullbrights", 0);
315 //      if (gl_vendor && strstr(gl_vendor, "3Dfx"))
316 //              gl_lightmode.value = 0;
317         Cvar_RegisterVariable (&r_fullbright);
318         makechrometextures();
319         glpoly_init();
320         glrsurf_init();
321         rlight_init();
322 }
323
324 /*
325 void R_RotateForEntity (entity_t *e)
326 {
327         glTranslatef (e->origin[0],  e->origin[1],  e->origin[2]);
328
329         glRotatef (e->angles[1],  0, 0, 1);
330         glRotatef (-e->angles[0],  0, 1, 0);
331         glRotatef (e->angles[2],  1, 0, 0);
332
333         glScalef (e->scale, e->scale, e->scale); // LordHavoc: model scale
334 }
335 */
336
337 // LordHavoc: if not for the fact BRIGHTFIELD particles require this, it would be removed...
338 #define NUMVERTEXNORMALS        162
339
340 float   r_avertexnormals[NUMVERTEXNORMALS][3] = {
341 #include "anorms.h"
342 };
343
344 // LordHavoc: moved this shading stuff up because the sprites need shading stuff
345 vec3_t  shadevector;
346 vec3_t  shadecolor;
347
348 float   modelalpha;
349
350 void R_LightPoint (vec3_t color, vec3_t p);
351 void R_DynamicLightPoint(vec3_t color, vec3_t org, int *dlightbits);
352 void R_DynamicLightPointNoMask(vec3_t color, vec3_t org);
353
354 float R_CalcAnimLerp(int pose, float lerpscale)
355 {
356         if (currententity->draw_lastmodel == currententity->model && currententity->draw_lerpstart <= cl.time)
357         {
358                 if (pose != currententity->draw_pose)
359                 {
360                         currententity->draw_lastpose = currententity->draw_pose;
361                         currententity->draw_pose = pose;
362                         currententity->draw_lerpstart = cl.time;
363                         return 0;
364                 }
365                 else
366                         return ((cl.time - currententity->draw_lerpstart) * lerpscale);
367         }
368         else // uninitialized
369         {
370                 currententity->draw_lastmodel = currententity->model;
371                 currententity->draw_lastpose = currententity->draw_pose = pose;
372                 currententity->draw_lerpstart = cl.time;
373                 return 0;
374         }
375 }
376
377 /*
378 =============================================================
379
380   SPRITE MODELS
381
382 =============================================================
383 */
384
385 /*
386 ================
387 R_GetSpriteFrame
388 ================
389 */
390 void R_GetSpriteFrame (entity_t *currententity, mspriteframe_t **oldframe, mspriteframe_t **newframe, float *framelerp)
391 {
392         msprite_t               *psprite;
393         mspritegroup_t  *pspritegroup;
394         int                             i, j, numframes, frame;
395         float                   *pintervals, fullinterval, targettime, time, jtime, jinterval;
396
397         psprite = currententity->model->cache.data;
398         frame = currententity->frame;
399
400         if ((frame >= psprite->numframes) || (frame < 0))
401         {
402                 Con_Printf ("R_DrawSprite: no such frame %d\n", frame);
403                 frame = 0;
404         }
405
406         if (psprite->frames[frame].type == SPR_SINGLE)
407         {
408                 if (currententity->draw_lastmodel == currententity->model && currententity->draw_lerpstart < cl.time)
409                 {
410                         if (frame != currententity->draw_pose)
411                         {
412                                 currententity->draw_lastpose = currententity->draw_pose;
413                                 currententity->draw_pose = frame;
414                                 currententity->draw_lerpstart = cl.time;
415                                 *framelerp = 0;
416                         }
417                         else
418                                 *framelerp = (cl.time - currententity->draw_lerpstart) * 10.0;
419                 }
420                 else // uninitialized
421                 {
422                         currententity->draw_lastmodel = currententity->model;
423                         currententity->draw_lastpose = currententity->draw_pose = frame;
424                         currententity->draw_lerpstart = cl.time;
425                         *framelerp = 0;
426                 }
427                 *oldframe = psprite->frames[currententity->draw_lastpose].frameptr;
428                 *newframe = psprite->frames[frame].frameptr;
429         }
430         else
431         {
432                 pspritegroup = (mspritegroup_t *)psprite->frames[frame].frameptr;
433                 pintervals = pspritegroup->intervals;
434                 numframes = pspritegroup->numframes;
435                 fullinterval = pintervals[numframes-1];
436
437                 time = cl.time + currententity->syncbase;
438
439         // when loading in Mod_LoadSpriteGroup, we guaranteed all interval values
440         // are positive, so we don't have to worry about division by 0
441                 targettime = time - ((int)(time / fullinterval)) * fullinterval;
442
443                 // LordHavoc: since I can't measure the time properly when it loops from numframes-1 to 0,
444                 //            I instead measure the time of the first frame, hoping it is consistent
445                 j = numframes-1;jtime = 0;jinterval = pintervals[1] - pintervals[0];
446                 for (i=0 ; i<(numframes-1) ; i++)
447                 {
448                         if (pintervals[i] > targettime)
449                                 break;
450                         j = i;jinterval = pintervals[i] - jtime;jtime = pintervals[i];
451                 }
452                 *framelerp = (targettime - jtime) / jinterval;
453
454                 *oldframe = pspritegroup->frames[j];
455                 *newframe = pspritegroup->frames[i];
456         }
457 }
458
459 void GL_DrawSpriteImage (mspriteframe_t *frame, vec3_t origin, vec3_t up, vec3_t right, int red, int green, int blue, int alpha)
460 {
461         // LordHavoc: rewrote this to use the transparent poly system
462         transpolybegin(frame->gl_texturenum, 0, frame->gl_fogtexturenum, currententity->effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
463         transpolyvert(origin[0] + frame->down * up[0] + frame->left * right[0], origin[1] + frame->down * up[1] + frame->left * right[1], origin[2] + frame->down * up[2] + frame->left * right[2], 0, 1, red, green, blue, alpha);
464         transpolyvert(origin[0] + frame->up * up[0] + frame->left * right[0], origin[1] + frame->up * up[1] + frame->left * right[1], origin[2] + frame->up * up[2] + frame->left * right[2], 0, 0, red, green, blue, alpha);
465         transpolyvert(origin[0] + frame->up * up[0] + frame->right * right[0], origin[1] + frame->up * up[1] + frame->right * right[1], origin[2] + frame->up * up[2] + frame->right * right[2], 1, 0, red, green, blue, alpha);
466         transpolyvert(origin[0] + frame->down * up[0] + frame->right * right[0], origin[1] + frame->down * up[1] + frame->right * right[1], origin[2] + frame->down * up[2] + frame->right * right[2], 1, 1, red, green, blue, alpha);
467         transpolyend();
468 }
469
470 extern qboolean isG200, isRagePro, lighthalf;
471
472 /*
473 =================
474 R_DrawSpriteModel
475
476 =================
477 */
478 void R_DrawSpriteModel (entity_t *e)
479 {
480         mspriteframe_t  *oldframe, *newframe;
481         float           *up, *right, lerp, ilerp;
482         vec3_t          v_forward, v_right, v_up, org;
483         msprite_t               *psprite;
484
485         // don't even bother culling, because it's just a single
486         // polygon without a surface cache
487         R_GetSpriteFrame (e, &oldframe, &newframe, &lerp);
488         if (lerp < 0) lerp = 0;
489         if (lerp > 1) lerp = 1;
490         if (isRagePro) // LordHavoc: no alpha scaling supported on per pixel alpha images on ATI Rage Pro... ACK!
491                 lerp = 1;
492         ilerp = 1.0 - lerp;
493         psprite = e->model->cache.data;
494
495         if (psprite->type == SPR_ORIENTED)
496         {       // bullet marks on walls
497                 AngleVectors (e->angles, v_forward, v_right, v_up);
498                 up = v_up;
499                 right = v_right;
500                 VectorSubtract(e->origin, vpn, org);
501         }
502         else
503         {       // normal sprite
504                 up = vup;
505                 right = vright;
506                 VectorCopy(e->origin, org);
507         }
508         if (e->scale != 1)
509         {
510                 VectorScale(up, e->scale, up);
511                 VectorScale(right, e->scale, right);
512         }
513
514         if (e->model->flags & EF_FULLBRIGHT || e->effects & EF_FULLBRIGHT)
515         {
516                 shadecolor[0] = e->colormod[0] * 255;
517                 shadecolor[1] = e->colormod[1] * 255;
518                 shadecolor[2] = e->colormod[2] * 255;
519         }
520         else
521         {
522                 R_LightPoint (shadecolor, e->origin);
523                 R_DynamicLightPointNoMask(shadecolor, e->origin);
524         }
525
526         // LordHavoc: interpolated sprite rendering
527         if (ilerp != 0)
528                 GL_DrawSpriteImage(oldframe, org, up, right, shadecolor[0],shadecolor[1],shadecolor[2],e->alpha*255*ilerp);
529         if (lerp != 0)
530                 GL_DrawSpriteImage(newframe, org, up, right, shadecolor[0],shadecolor[1],shadecolor[2],e->alpha*255*lerp);
531 }
532
533 /*
534 =============================================================
535
536   ALIAS MODELS
537
538 =============================================================
539 */
540
541 extern vec3_t softwaretransform_x;
542 extern vec3_t softwaretransform_y;
543 extern vec3_t softwaretransform_z;
544 extern vec_t softwaretransform_scale;
545 extern vec3_t softwaretransform_offset;
546 void R_AliasLerpVerts(int vertcount, float lerp, trivert2 *verts1, vec3_t scale1, vec3_t translate1, trivert2 *verts2, vec3_t scale2, vec3_t translate2)
547 {
548         int i;
549         vec3_t point, matrix_x, matrix_y, matrix_z;
550         float *av, *avn;
551         av = aliasvert;
552         avn = aliasvertnorm;
553         if (lerp < 0) lerp = 0;
554         if (lerp > 1) lerp = 1;
555         if (lerp != 0)
556         {
557                 float ilerp, ilerp127, lerp127, scalex1, scalex2, translatex, scaley1, scaley2, translatey, scalez1, scalez2, translatez;
558                 if (lerp < 0) lerp = 0;
559                 if (lerp > 1) lerp = 1;
560                 ilerp = 1 - lerp;
561                 ilerp127 = ilerp * (1.0 / 127.0);
562                 lerp127 = lerp * (1.0 / 127.0);
563                 VectorScale(softwaretransform_x, softwaretransform_scale, matrix_x);
564                 VectorScale(softwaretransform_y, softwaretransform_scale, matrix_y);
565                 VectorScale(softwaretransform_z, softwaretransform_scale, matrix_z);
566                 // calculate combined interpolation variables
567                 scalex1 = scale1[0] * ilerp;scalex2 = scale2[0] *  lerp;translatex = translate1[0] * ilerp + translate2[0] *  lerp;
568                 scaley1 = scale1[1] * ilerp;scaley2 = scale2[1] *  lerp;translatey = translate1[1] * ilerp + translate2[1] *  lerp;
569                 scalez1 = scale1[2] * ilerp;scalez2 = scale2[2] *  lerp;translatez = translate1[2] * ilerp + translate2[2] *  lerp;
570                 // generate vertices
571                 for (i = 0;i < vertcount;i++)
572                 {
573                         // rotate, scale, and translate the vertex locations
574                         point[0] = verts1->v[0] * scalex1 + verts2->v[0] * scalex2 + translatex;
575                         point[1] = verts1->v[1] * scaley1 + verts2->v[1] * scaley2 + translatey;
576                         point[2] = verts1->v[2] * scalez1 + verts2->v[2] * scalez2 + translatez;
577                         *av++ = point[0] * matrix_x[0] + point[1] * matrix_y[0] + point[2] * matrix_z[0] + softwaretransform_offset[0];
578                         *av++ = point[0] * matrix_x[1] + point[1] * matrix_y[1] + point[2] * matrix_z[1] + softwaretransform_offset[1];
579                         *av++ = point[0] * matrix_x[2] + point[1] * matrix_y[2] + point[2] * matrix_z[2] + softwaretransform_offset[2];
580                         // rotate the normals
581                         point[0] = verts1->n[0] * ilerp127 + verts2->n[0] * lerp127;
582                         point[1] = verts1->n[1] * ilerp127 + verts2->n[1] * lerp127;
583                         point[2] = verts1->n[2] * ilerp127 + verts2->n[2] * lerp127;
584                         *avn++ = point[0] * softwaretransform_x[0] + point[1] * softwaretransform_y[0] + point[2] * softwaretransform_z[0];
585                         *avn++ = point[0] * softwaretransform_x[1] + point[1] * softwaretransform_y[1] + point[2] * softwaretransform_z[1];
586                         *avn++ = point[0] * softwaretransform_x[2] + point[1] * softwaretransform_y[2] + point[2] * softwaretransform_z[2];
587                         verts1++;verts2++;
588                 }
589         }
590         else
591         {
592                 float i127;
593                 i127 = 1.0f / 127.0f;
594                 VectorScale(softwaretransform_x, softwaretransform_scale, matrix_x);
595                 VectorScale(softwaretransform_y, softwaretransform_scale, matrix_y);
596                 VectorScale(softwaretransform_z, softwaretransform_scale, matrix_z);
597                 // generate vertices
598                 for (i = 0;i < vertcount;i++)
599                 {
600                         // rotate, scale, and translate the vertex locations
601                         point[0] = verts1->v[0] * scale1[0] + translate1[0];
602                         point[1] = verts1->v[1] * scale1[1] + translate1[1];
603                         point[2] = verts1->v[2] * scale1[2] + translate1[2];
604                         *av++ = point[0] * matrix_x[0] + point[1] * matrix_y[0] + point[2] * matrix_z[0] + softwaretransform_offset[0];
605                         *av++ = point[0] * matrix_x[1] + point[1] * matrix_y[1] + point[2] * matrix_z[1] + softwaretransform_offset[1];
606                         *av++ = point[0] * matrix_x[2] + point[1] * matrix_y[2] + point[2] * matrix_z[2] + softwaretransform_offset[2];
607                         // rotate the normals
608                         point[0] = verts1->n[0] * i127;
609                         point[1] = verts1->n[1] * i127;
610                         point[2] = verts1->n[2] * i127;
611                         *avn++ = point[0] * softwaretransform_x[0] + point[1] * softwaretransform_y[0] + point[2] * softwaretransform_z[0];
612                         *avn++ = point[0] * softwaretransform_x[1] + point[1] * softwaretransform_y[1] + point[2] * softwaretransform_z[1];
613                         *avn++ = point[0] * softwaretransform_x[2] + point[1] * softwaretransform_y[2] + point[2] * softwaretransform_z[2];
614                         verts1++;
615                 }
616         }
617 }
618
619 /*
620 =================
621 R_DrawAliasFrame
622
623 =================
624 */
625 extern vec3_t lightspot;
626 void R_LightModel(int numverts, vec3_t center);
627 extern cvar_t gl_vertexarrays;
628 void R_DrawAliasFrame (aliashdr_t *paliashdr)
629 {
630         int                             i, pose, frame = currententity->frame;
631         float                   lerpscale, lerp;
632
633         softwaretransformforentity(currententity);
634
635         if ((frame >= paliashdr->numframes) || (frame < 0))
636         {
637                 Con_DPrintf ("R_AliasSetupFrame: no such frame %d\n", frame);
638                 frame = 0;
639         }
640
641         pose = paliashdr->frames[frame].firstpose;
642
643         if (paliashdr->frames[frame].numposes > 1)
644         {
645                 lerpscale = 1.0 / paliashdr->frames[frame].interval;
646                 pose += (int)(cl.time * lerpscale) % paliashdr->frames[frame].numposes;
647         }
648         else
649                 lerpscale = 10.0;
650
651         lerp = R_CalcAnimLerp(pose, lerpscale);
652
653         R_AliasLerpVerts(paliashdr->numverts, lerp, (trivert2 *)((byte *)paliashdr + paliashdr->posedata) + currententity->draw_lastpose * paliashdr->numverts, paliashdr->scale, paliashdr->scale_origin, (trivert2 *)((byte *)paliashdr + paliashdr->posedata) + currententity->draw_pose * paliashdr->numverts, paliashdr->scale, paliashdr->scale_origin);
654
655         R_LightModel(paliashdr->numverts, currententity->origin);
656
657         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
658         glShadeModel(GL_SMOOTH);
659         if (currententity->effects & EF_ADDITIVE)
660         {
661                 glBlendFunc(GL_SRC_ALPHA, GL_ONE); // additive rendering
662                 glEnable(GL_BLEND);
663                 glDepthMask(0);
664         }
665         else if (modelalpha != 1.0)
666         {
667                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
668                 glEnable(GL_BLEND);
669                 glDepthMask(0);
670         }
671         else
672         {
673                 glDisable(GL_BLEND);
674                 glDepthMask(1);
675         }
676
677         if (gl_vertexarrays.value)
678         {
679                 // LordHavoc: I would use InterleavedArrays here,
680                 // but the texture coordinates are a seperate array,
681                 // and it would be wasteful to copy them into the main array...
682         //      glColor4f(shadecolor[0], shadecolor[1], shadecolor[2], modelalpha);
683                 qglVertexPointer(3, GL_FLOAT, 0, aliasvert);
684                 qglColorPointer(4, GL_UNSIGNED_BYTE, 0, aliasvertcolor);
685                 glEnableClientState(GL_VERTEX_ARRAY);
686                 glEnableClientState(GL_COLOR_ARRAY);
687
688                 // draw the front faces
689                 qglTexCoordPointer(2, GL_FLOAT, 0, (void *)((int) paliashdr->texcoords + (int) paliashdr));
690                 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
691                 qglDrawElements(GL_TRIANGLES, paliashdr->frontfaces * 3, GL_UNSIGNED_SHORT, (void *)((int) paliashdr->vertindices + (int) paliashdr));
692                 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
693
694                 // draw the back faces
695                 qglTexCoordPointer(2, GL_FLOAT, 0, (void *)((int) paliashdr->texcoords + sizeof(float[2]) * paliashdr->numverts + (int) paliashdr));
696                 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
697                 qglDrawElements(GL_TRIANGLES, paliashdr->backfaces * 3, GL_UNSIGNED_SHORT, (void *)((int) paliashdr->vertindices + sizeof(unsigned short[3]) * paliashdr->frontfaces + (int) paliashdr));
698                 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
699
700                 glDisableClientState(GL_COLOR_ARRAY);
701                 glDisableClientState(GL_VERTEX_ARRAY);
702         }
703         else
704         {
705                 unsigned short *in, index;
706                 float *tex;
707                 in = (void *)((int) paliashdr->vertindices + (int) paliashdr);
708                 glBegin(GL_TRIANGLES);
709                 // draw the front faces
710                 tex = (void *)((int) paliashdr->texcoords + (int) paliashdr);
711                 //if (isG200)
712                 //{
713                         for (i = 0;i < paliashdr->frontfaces * 3;i++)
714                         {
715                                 index = *in++;
716                                 glTexCoord2f(tex[index*2], tex[index*2+1]);
717                                 glColor4f(aliasvertcolor[index*4] * (1.0f / 255.0f), aliasvertcolor[index*4+1] * (1.0f / 255.0f), aliasvertcolor[index*4+2] * (1.0f / 255.0f), aliasvertcolor[index*4+3] * (1.0f / 255.0f));
718                                 glVertex3fv(&aliasvert[index*3]);
719                         }
720                 /*
721                 }
722                 else
723                 {
724                         for (i = 0;i < paliashdr->frontfaces * 3;i++)
725                         {
726                                 index = *in++;
727                                 glTexCoord2f(tex[index*2], tex[index*2+1]);
728                                 glColor4ub(aliasvertcolor[index*4], aliasvertcolor[index*4+1], aliasvertcolor[index*4+2], aliasvertcolor[index*4+3]);
729                                 glVertex3fv(&aliasvert[index*3]);
730                         }
731                 }
732                 */
733                 // draw the back faces
734                 tex += 2 * paliashdr->numverts;
735                 //if (isG200)
736                 //{
737                         for (i = 0;i < paliashdr->backfaces * 3;i++)
738                         {
739                                 index = *in++;
740                                 glTexCoord2f(tex[index*2], tex[index*2+1]);
741                                 glColor4f(aliasvertcolor[index*4] * (1.0f / 255.0f), aliasvertcolor[index*4+1] * (1.0f / 255.0f), aliasvertcolor[index*4+2] * (1.0f / 255.0f), aliasvertcolor[index*4+3] * (1.0f / 255.0f));
742                                 glVertex3fv(&aliasvert[index*3]);
743                         }
744                 /*
745                 }
746                 else
747                 {
748                         for (i = 0;i < paliashdr->backfaces * 3;i++)
749                         {
750                                 index = *in++;
751                                 glTexCoord2f(tex[index*2], tex[index*2+1]);
752                                 glColor4ub(aliasvertcolor[index*4], aliasvertcolor[index*4+1], aliasvertcolor[index*4+2], aliasvertcolor[index*4+3]);
753                                 glVertex3fv(&aliasvert[index*3]);
754                         }
755                 }
756                 */
757                 glEnd();
758         }
759
760         if (fogenabled)
761         {
762                 vec3_t diff;
763                 glDisable (GL_TEXTURE_2D);
764                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
765                 glEnable (GL_BLEND);
766                 glDepthMask(0); // disable zbuffer updates
767
768                 VectorSubtract(currententity->origin, r_refdef.vieworg, diff);
769                 glColor4f(fogcolor[0], fogcolor[1], fogcolor[2], exp(fogdensity/DotProduct(diff,diff)));
770
771                 if (gl_vertexarrays.value)
772                 {
773                         qglVertexPointer(3, GL_FLOAT, 0, aliasvert);
774                         glEnableClientState(GL_VERTEX_ARRAY);
775                         qglDrawElements(GL_TRIANGLES, paliashdr->numtris * 3, GL_UNSIGNED_SHORT, (void *)((int) paliashdr->vertindices + (int) paliashdr));
776                         glDisableClientState(GL_VERTEX_ARRAY);
777                 }
778                 else
779                 {
780                         unsigned short *in;
781                         in = (void *)((int) paliashdr->vertindices + (int) paliashdr);
782                         glBegin(GL_TRIANGLES);
783                         for (i = 0;i < paliashdr->numtris * 3;i++)
784                                 glVertex3fv(&aliasvert[*in++ * 3]);
785                         glEnd();
786                 }
787
788                 glEnable (GL_TEXTURE_2D);
789                 glColor3f (1,1,1);
790         }
791
792         if (!fogenabled && r_shadows.value && !(currententity->effects & EF_ADDITIVE) && currententity != &cl.viewent)
793         {
794                 // flatten it to make a shadow
795                 float *av = aliasvert + 2, l = lightspot[2] + 0.125;
796                 av = aliasvert + 2;
797                 for (i = 0;i < paliashdr->numverts;i++, av+=3)
798                         if (*av > l)
799                                 *av = l;
800                 glDisable (GL_TEXTURE_2D);
801                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
802                 glEnable (GL_BLEND);
803                 glDepthMask(0); // disable zbuffer updates
804                 glColor4f (0,0,0,0.5 * modelalpha);
805
806                 if (gl_vertexarrays.value)
807                 {
808                         qglVertexPointer(3, GL_FLOAT, 0, aliasvert);
809                         glEnableClientState(GL_VERTEX_ARRAY);
810                         qglDrawElements(GL_TRIANGLES, paliashdr->numtris * 3, GL_UNSIGNED_SHORT, (void *)((int) paliashdr->vertindices + (int) paliashdr));
811                         glDisableClientState(GL_VERTEX_ARRAY);
812                 }
813                 else
814                 {
815                         unsigned short *in;
816                         in = (void *)((int) paliashdr->vertindices + (int) paliashdr);
817                         glBegin(GL_TRIANGLES);
818                         for (i = 0;i < paliashdr->numtris * 3;i++)
819                                 glVertex3fv(&aliasvert[*in++ * 3]);
820                         glEnd();
821                 }
822
823                 glEnable (GL_TEXTURE_2D);
824                 glColor3f (1,1,1);
825         }
826
827         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
828         glEnable (GL_BLEND);
829         glDepthMask(1);
830 }
831
832 /*
833 =================
834 R_DrawQ2AliasFrame
835
836 =================
837 */
838 void R_DrawQ2AliasFrame (md2mem_t *pheader)
839 {
840         int *order, count, frame = currententity->frame;
841         float lerp;
842         md2memframe_t *frame1, *frame2;
843
844         softwaretransformforentity(currententity);
845
846         if ((frame >= pheader->num_frames) || (frame < 0))
847         {
848                 Con_DPrintf ("R_SetupQ2AliasFrame: no such frame %d\n", frame);
849                 frame = 0;
850         }
851
852         lerp = R_CalcAnimLerp(frame, 10);
853
854         frame1 = (void *)((int) pheader + pheader->ofs_frames + (pheader->framesize * currententity->draw_lastpose));
855         frame2 = (void *)((int) pheader + pheader->ofs_frames + (pheader->framesize * currententity->draw_pose));
856         R_AliasLerpVerts(pheader->num_xyz, lerp, frame1->verts, frame1->scale, frame1->translate, frame2->verts, frame2->scale, frame2->translate);
857
858         R_LightModel(pheader->num_xyz, currententity->origin);
859
860         if (gl_vertexarrays.value)
861         {
862                 // LordHavoc: big mess...
863                 // using arrays only slightly, although it is enough to prevent duplicates
864                 // (saving half the transforms)
865                 //glColor4f(shadecolor[0], shadecolor[1], shadecolor[2], modelalpha);
866                 qglVertexPointer(3, GL_FLOAT, 0, aliasvert);
867                 qglColorPointer(4, GL_UNSIGNED_BYTE, 0, aliasvertcolor);
868                 glEnableClientState(GL_VERTEX_ARRAY);
869                 glEnableClientState(GL_COLOR_ARRAY);
870
871                 order = (int *)((int)pheader + pheader->ofs_glcmds);
872                 while(1)
873                 {
874                         if (!(count = *order++))
875                                 break;
876                         if (count > 0)
877                                 glBegin(GL_TRIANGLE_STRIP);
878                         else
879                         {
880                                 glBegin(GL_TRIANGLE_FAN);
881                                 count = -count;
882                         }
883                         do
884                         {
885                                 glTexCoord2f(((float *)order)[0], ((float *)order)[1]);
886                                 qglArrayElement(order[2]);
887                                 order += 3;
888                         }
889                         while (count--);
890                 }
891
892                 glDisableClientState(GL_COLOR_ARRAY);
893                 glDisableClientState(GL_VERTEX_ARRAY);
894         }
895         else
896         {
897                 order = (int *)((int)pheader + pheader->ofs_glcmds);
898                 while(1)
899                 {
900                         if (!(count = *order++))
901                                 break;
902                         if (count > 0)
903                                 glBegin(GL_TRIANGLE_STRIP);
904                         else
905                         {
906                                 glBegin(GL_TRIANGLE_FAN);
907                                 count = -count;
908                         }
909                         //if (isG200)
910                         //{
911                                 do
912                                 {
913                                         glTexCoord2f(((float *)order)[0], ((float *)order)[1]);
914                                         glColor4f(aliasvertcolor[order[2] * 4] * (1.0f / 255.0f), aliasvertcolor[order[2] * 4 + 1] * (1.0f / 255.0f), aliasvertcolor[order[2] * 4 + 2] * (1.0f / 255.0f), aliasvertcolor[order[2] * 4 + 3] * (1.0f / 255.0f));
915                                         glVertex3fv(&aliasvert[order[2] * 3]);
916                                         order += 3;
917                                 }
918                                 while (count--);
919                         /*
920                         }
921                         else
922                         {
923                                 do
924                                 {
925                                         glTexCoord2f(((float *)order)[0], ((float *)order)[1]);
926                                         glColor4ub(aliasvertcolor[order[2] * 4], aliasvertcolor[order[2] * 4 + 1], aliasvertcolor[order[2] * 4 + 2], aliasvertcolor[order[2] * 4 + 3]);
927                                         glVertex3fv(&aliasvert[order[2] * 3]);
928                                         order += 3;
929                                 }
930                                 while (count--);
931                         }
932                         */
933                 }
934         }
935
936         if (fogenabled)
937         {
938                 glDisable (GL_TEXTURE_2D);
939                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
940                 glEnable (GL_BLEND);
941                 glDepthMask(0); // disable zbuffer updates
942                 {
943                         vec3_t diff;
944                         VectorSubtract(currententity->origin, r_refdef.vieworg, diff);
945                         glColor4f(fogcolor[0], fogcolor[1], fogcolor[2], exp(fogdensity/DotProduct(diff,diff)));
946                 }
947
948                 if (gl_vertexarrays.value)
949                 {
950                         // LordHavoc: big mess...
951                         // using arrays only slightly, although it is enough to prevent duplicates
952                         // (saving half the transforms)
953                         //glColor4f(shadecolor[0], shadecolor[1], shadecolor[2], modelalpha);
954                         qglVertexPointer(3, GL_FLOAT, 0, aliasvert);
955                         glEnableClientState(GL_VERTEX_ARRAY);
956
957                         order = (int *)((int)pheader + pheader->ofs_glcmds);
958                         while(1)
959                         {
960                                 if (!(count = *order++))
961                                         break;
962                                 if (count > 0)
963                                         glBegin(GL_TRIANGLE_STRIP);
964                                 else
965                                 {
966                                         glBegin(GL_TRIANGLE_FAN);
967                                         count = -count;
968                                 }
969                                 do
970                                 {
971                                         qglArrayElement(order[2]);
972                                         order += 3;
973                                 }
974                                 while (count--);
975                         }
976
977                         glDisableClientState(GL_VERTEX_ARRAY);
978                 }
979                 else
980                 {
981                         order = (int *)((int)pheader + pheader->ofs_glcmds);
982                         while(1)
983                         {
984                                 if (!(count = *order++))
985                                         break;
986                                 if (count > 0)
987                                         glBegin(GL_TRIANGLE_STRIP);
988                                 else
989                                 {
990                                         glBegin(GL_TRIANGLE_FAN);
991                                         count = -count;
992                                 }
993                                 do
994                                 {
995                                         glVertex3fv(&aliasvert[order[2] * 3]);
996                                         order += 3;
997                                 }
998                                 while (count--);
999                         }
1000                 }
1001
1002                 glEnable (GL_TEXTURE_2D);
1003                 glColor3f (1,1,1);
1004         }
1005
1006         if (!fogenabled && r_shadows.value && !(currententity->effects & EF_ADDITIVE) && currententity != &cl.viewent)
1007         {
1008                 int i;
1009                 float *av = aliasvert + 2, l = lightspot[2] + 0.125;
1010                 av = aliasvert + 2;
1011                 for (i = 0;i < pheader->num_xyz;i++, av+=3)
1012                         if (*av > l)
1013                                 *av = l;
1014                 glDisable (GL_TEXTURE_2D);
1015                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1016                 glEnable (GL_BLEND);
1017                 glDepthMask(0); // disable zbuffer updates
1018                 glColor4f (0,0,0,0.5 * modelalpha);
1019
1020                 if (gl_vertexarrays.value)
1021                 {
1022                         qglVertexPointer(3, GL_FLOAT, 0, aliasvert);
1023                         glEnableClientState(GL_VERTEX_ARRAY);
1024                                                 
1025                         while(1)
1026                         {
1027                                 if (!(count = *order++))
1028                                         break;
1029                                 if (count > 0)
1030                                         glBegin(GL_TRIANGLE_STRIP);
1031                                 else
1032                                 {
1033                                         glBegin(GL_TRIANGLE_FAN);
1034                                         count = -count;
1035                                 }
1036                                 do
1037                                 {
1038                                         qglArrayElement(order[2]);
1039                                         order += 3;
1040                                 }
1041                                 while (count--);
1042                         }
1043
1044                         glDisableClientState(GL_VERTEX_ARRAY);
1045                 }
1046                 else
1047                 {
1048                         while(1)
1049                         {
1050                                 if (!(count = *order++))
1051                                         break;
1052                                 if (count > 0)
1053                                         glBegin(GL_TRIANGLE_STRIP);
1054                                 else
1055                                 {
1056                                         glBegin(GL_TRIANGLE_FAN);
1057                                         count = -count;
1058                                 }
1059                                 do
1060                                 {
1061                                         glVertex3fv(&aliasvert[order[2] * 3]);
1062                                         order += 3;
1063                                 }
1064                                 while (count--);
1065                         }
1066                 }
1067
1068                 glEnable (GL_TEXTURE_2D);
1069                 glColor3f (1,1,1);
1070         }
1071
1072         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1073         glEnable (GL_BLEND);
1074         glDepthMask(1);
1075 }
1076
1077 int modeldlightbits[8];
1078 extern int r_dlightframecount;
1079
1080 /*
1081 =================
1082 R_DrawAliasModel
1083
1084 =================
1085 */
1086 void R_DrawAliasModel (entity_t *e, int cull)
1087 {
1088         int                     i;
1089         model_t         *clmodel;
1090         vec3_t          mins, maxs;
1091         aliashdr_t      *paliashdr = NULL;
1092         md2mem_t                *pheader = NULL;
1093         int                     anim;
1094
1095         if (modelalpha < (1.0 / 64.0))
1096                 return; // basically completely transparent
1097
1098         clmodel = currententity->model;
1099
1100         VectorAdd (currententity->origin, clmodel->mins, mins);
1101         VectorAdd (currententity->origin, clmodel->maxs, maxs);
1102
1103         if (cull && R_CullBox (mins, maxs))
1104                 return;
1105
1106         VectorCopy (currententity->origin, r_entorigin);
1107         VectorSubtract (r_origin, r_entorigin, modelorg);
1108
1109         {
1110                 mleaf_t *leaf = Mod_PointInLeaf (currententity->origin, cl.worldmodel);
1111                 if (leaf->dlightframe == r_dlightframecount)
1112                         for (i = 0;i < 8;i++)
1113                                 modeldlightbits[i] = leaf->dlightbits[i];
1114                 else
1115                         for (i = 0;i < 8;i++)
1116                                 modeldlightbits[i] = 0;
1117         }
1118
1119         // get lighting information
1120
1121         if (currententity->model->flags & EF_FULLBRIGHT || currententity->effects & EF_FULLBRIGHT)
1122         {
1123                 shadecolor[0] = currententity->colormod[0] * 256;
1124                 shadecolor[1] = currententity->colormod[1] * 256;
1125                 shadecolor[2] = currententity->colormod[2] * 256;
1126         }
1127         else
1128         {
1129                 R_LightPoint (shadecolor, currententity->origin);
1130
1131                 // HACK HACK HACK -- no fullbright colors, so make torches full light
1132                 if (!strcmp (currententity->model->name, "progs/flame2.mdl") || !strcmp (currententity->model->name, "progs/flame.mdl") )
1133                         shadecolor[0] = shadecolor[1] = shadecolor[2] = 128;
1134
1135                 shadecolor[0] *= currententity->colormod[0];
1136                 shadecolor[1] *= currententity->colormod[1];
1137                 shadecolor[2] *= currententity->colormod[2];
1138         }
1139
1140         // locate the proper data
1141         if (clmodel->aliastype == ALIASTYPE_MD2)
1142         {
1143                 pheader = (void *)Mod_Extradata (currententity->model);
1144                 c_alias_polys += pheader->num_tris;
1145         }
1146         else
1147         {
1148                 paliashdr = (void *)Mod_Extradata (currententity->model);
1149                 c_alias_polys += paliashdr->numtris;
1150         }
1151
1152         // draw all the triangles
1153
1154         if (clmodel->aliastype == ALIASTYPE_MD2)
1155         {
1156                 if (currententity->skinnum < 0 || currententity->skinnum >= pheader->num_skins)
1157                 {
1158                         currententity->skinnum = 0;
1159                         Con_DPrintf("invalid skin number %d for model %s\n", currententity->skinnum, clmodel->name);
1160                 }
1161                 glBindTexture(GL_TEXTURE_2D, pheader->gl_texturenum[currententity->skinnum]);
1162         }
1163         else
1164         {
1165                 if (currententity->skinnum < 0 || currententity->skinnum >= paliashdr->numskins)
1166                 {
1167                         currententity->skinnum = 0;
1168                         Con_DPrintf("invalid skin number %d for model %s\n", currententity->skinnum, clmodel->name);
1169                 }
1170                 anim = (int)(cl.time*10) & 3;
1171             glBindTexture(GL_TEXTURE_2D, paliashdr->gl_texturenum[currententity->skinnum][anim]);
1172         }
1173         glDisable(GL_ALPHA_TEST);
1174         glEnable (GL_TEXTURE_2D);
1175
1176         // we can't dynamically colormap textures, so they are cached
1177         // seperately for the players.  Heads are just uncolored.
1178         if (currententity->colormap != 0 /*vid.colormap*/ /* && !gl_nocolors.value*/)
1179         {
1180                 i = currententity - cl_entities;
1181                 if (i >= 1 && i<=cl.maxclients /* && !strcmp (currententity->model->name, "progs/player.mdl") */)
1182                         glBindTexture(GL_TEXTURE_2D, playertextures - 1 + i);
1183         }
1184
1185 //      if (gl_affinemodels.value)
1186 //              glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
1187         if (clmodel->aliastype == ALIASTYPE_MD2)
1188                 R_DrawQ2AliasFrame (pheader);
1189         else
1190                 R_DrawAliasFrame (paliashdr);
1191
1192         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1193 }
1194
1195 //==================================================================================
1196
1197 void R_DrawBrushModel (entity_t *e);
1198
1199 /*
1200 =============
1201 R_DrawEntitiesOnList
1202 =============
1203 */
1204 // LordHavoc: split so bmodels are rendered before any other objects
1205 void R_DrawEntitiesOnList1 (void)
1206 {
1207         int             i;
1208
1209         if (!r_drawentities.value)
1210                 return;
1211
1212         for (i=0 ; i<cl_numvisedicts ; i++)
1213         {
1214                 if (cl_visedicts[i]->model->type != mod_brush)
1215                         continue;
1216                 currententity = cl_visedicts[i];
1217                 modelalpha = currententity->alpha;
1218
1219                 R_DrawBrushModel (currententity);
1220         }
1221 }
1222
1223 void R_DrawEntitiesOnList2 (void)
1224 {
1225         int             i;
1226
1227         if (!r_drawentities.value)
1228                 return;
1229
1230         for (i=0 ; i<cl_numvisedicts ; i++)
1231         {
1232                 currententity = cl_visedicts[i];
1233                 modelalpha = currententity->alpha;
1234
1235                 switch (currententity->model->type)
1236                 {
1237                 case mod_alias:
1238                         R_DrawAliasModel (currententity, true);
1239                         break;
1240
1241                 case mod_sprite:
1242                         R_DrawSpriteModel (currententity);
1243                         break;
1244
1245                 default:
1246                         break;
1247                 }
1248         }
1249 }
1250
1251 /*
1252 =============
1253 R_DrawViewModel
1254 =============
1255 */
1256 void R_DrawViewModel (void)
1257 {
1258         if (!r_drawviewmodel.value || chase_active.value || envmap || !r_drawentities.value || cl.items & IT_INVISIBILITY || cl.stats[STAT_HEALTH] <= 0 || !cl.viewent.model)
1259                 return;
1260
1261         currententity = &cl.viewent;
1262         currententity->alpha = modelalpha = cl_entities[cl.viewentity].alpha; // LordHavoc: if the player is transparent, so is his gun
1263         currententity->effects = cl_entities[cl.viewentity].effects;
1264         currententity->scale = 1;
1265         VectorCopy(cl_entities[cl.viewentity].colormod, currententity->colormod);
1266
1267         // hack the depth range to prevent view model from poking into walls
1268         glDepthRange (gldepthmin, gldepthmin + 0.3*(gldepthmax-gldepthmin));
1269         R_DrawAliasModel (currententity, FALSE);
1270         glDepthRange (gldepthmin, gldepthmax);
1271 }
1272
1273 void R_DrawBrushModel (entity_t *e);
1274
1275 void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees );
1276
1277 void R_SetFrustum (void)
1278 {
1279         int             i;
1280
1281         if (r_refdef.fov_x == 90) 
1282         {
1283                 // front side is visible
1284
1285                 VectorAdd (vpn, vright, frustum[0].normal);
1286                 VectorSubtract (vpn, vright, frustum[1].normal);
1287
1288                 VectorAdd (vpn, vup, frustum[2].normal);
1289                 VectorSubtract (vpn, vup, frustum[3].normal);
1290         }
1291         else
1292         {
1293                 // rotate VPN right by FOV_X/2 degrees
1294                 RotatePointAroundVector( frustum[0].normal, vup, vpn, -(90-r_refdef.fov_x / 2 ) );
1295                 // rotate VPN left by FOV_X/2 degrees
1296                 RotatePointAroundVector( frustum[1].normal, vup, vpn, 90-r_refdef.fov_x / 2 );
1297                 // rotate VPN up by FOV_X/2 degrees
1298                 RotatePointAroundVector( frustum[2].normal, vright, vpn, 90-r_refdef.fov_y / 2 );
1299                 // rotate VPN down by FOV_X/2 degrees
1300                 RotatePointAroundVector( frustum[3].normal, vright, vpn, -( 90 - r_refdef.fov_y / 2 ) );
1301         }
1302
1303         for (i=0 ; i<4 ; i++)
1304         {
1305                 frustum[i].type = PLANE_ANYZ;
1306                 frustum[i].dist = DotProduct (r_origin, frustum[i].normal);
1307 //              frustum[i].signbits = SignbitsForPlane (&frustum[i]);
1308                 BoxOnPlaneSideClassify(&frustum[i]);
1309         }
1310 }
1311
1312 void R_AnimateLight (void);
1313 void V_CalcBlend (void);
1314
1315 /*
1316 ===============
1317 R_SetupFrame
1318 ===============
1319 */
1320 void R_SetupFrame (void)
1321 {
1322 // don't allow cheats in multiplayer
1323         if (cl.maxclients > 1)
1324         {
1325                 Cvar_Set ("r_fullbright", "0");
1326                 Cvar_Set ("r_ambient", "0");
1327         }
1328
1329         R_AnimateLight ();
1330
1331         r_framecount++;
1332
1333 // build the transformation matrix for the given view angles
1334         VectorCopy (r_refdef.vieworg, r_origin);
1335
1336         AngleVectors (r_refdef.viewangles, vpn, vright, vup);
1337
1338 // current viewleaf
1339         r_oldviewleaf = r_viewleaf;
1340         r_viewleaf = Mod_PointInLeaf (r_origin, cl.worldmodel);
1341
1342         V_SetContentsColor (r_viewleaf->contents);
1343         V_CalcBlend ();
1344
1345         r_cache_thrash = false;
1346
1347         c_brush_polys = 0;
1348         c_alias_polys = 0;
1349         c_light_polys = 0;
1350         c_nodes = 0;
1351         c_leafs = 0;
1352
1353 }
1354
1355
1356 void MYgluPerspective( GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar )
1357 {
1358    GLdouble xmin, xmax, ymin, ymax;
1359
1360    ymax = zNear * tan( fovy * M_PI / 360.0 );
1361    ymin = -ymax;
1362
1363    xmin = ymin * aspect;
1364    xmax = ymax * aspect;
1365
1366    glFrustum( xmin, xmax, ymin, ymax, zNear, zFar );
1367 }
1368
1369
1370 extern char skyname[];
1371
1372 /*
1373 =============
1374 R_SetupGL
1375 =============
1376 */
1377 void R_SetupGL (void)
1378 {
1379         float   screenaspect;
1380         extern  int glwidth, glheight;
1381         int             x, x2, y2, y, w, h;
1382
1383         //
1384         // set up viewpoint
1385         //
1386         glMatrixMode(GL_PROJECTION);
1387     glLoadIdentity ();
1388         x = r_refdef.vrect.x * glwidth/vid.width;
1389         x2 = (r_refdef.vrect.x + r_refdef.vrect.width) * glwidth/vid.width;
1390         y = (vid.height-r_refdef.vrect.y) * glheight/vid.height;
1391         y2 = (vid.height - (r_refdef.vrect.y + r_refdef.vrect.height)) * glheight/vid.height;
1392
1393         // fudge around because of frac screen scale
1394         if (x > 0)
1395                 x--;
1396         if (x2 < glwidth)
1397                 x2++;
1398         if (y2 < 0)
1399                 y2--;
1400         if (y < glheight)
1401                 y++;
1402
1403         w = x2 - x;
1404         h = y - y2;
1405
1406         if (envmap)
1407         {
1408                 x = y2 = 0;
1409                 w = h = 256;
1410         }
1411
1412         glViewport (glx + x, gly + y2, w, h);
1413     screenaspect = (float)r_refdef.vrect.width/r_refdef.vrect.height;
1414 //      yfov = 2*atan((float)r_refdef.vrect.height/r_refdef.vrect.width)*180/M_PI;
1415 //      if (skyname[0]) // skybox enabled?
1416 //              MYgluPerspective (r_refdef.fov_y,  screenaspect,  4,  r_skyboxsize.value*1.732050807569 + 256); // this is size*sqrt(3) + 256
1417 //      else
1418                 MYgluPerspective (r_refdef.fov_y,  screenaspect,  4,  r_farclip.value);
1419
1420         glCullFace(GL_FRONT);
1421
1422         glMatrixMode(GL_MODELVIEW);
1423     glLoadIdentity ();
1424
1425     glRotatef (-90,  1, 0, 0);      // put Z going up
1426     glRotatef (90,  0, 0, 1);       // put Z going up
1427     glRotatef (-r_refdef.viewangles[2],  1, 0, 0);
1428     glRotatef (-r_refdef.viewangles[0],  0, 1, 0);
1429     glRotatef (-r_refdef.viewangles[1],  0, 0, 1);
1430     glTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);
1431
1432         glGetFloatv (GL_MODELVIEW_MATRIX, r_world_matrix);
1433
1434         //
1435         // set drawing parms
1436         //
1437 //      if (gl_cull.value)
1438                 glEnable(GL_CULL_FACE);
1439 //      else
1440 //              glDisable(GL_CULL_FACE);
1441
1442         glEnable(GL_BLEND); // was Disable
1443         glDisable(GL_ALPHA_TEST);
1444         glAlphaFunc(GL_GREATER, 0.5);
1445         glEnable(GL_DEPTH_TEST);
1446         glDepthMask(1);
1447         glShadeModel(GL_SMOOTH);
1448 }
1449
1450 void R_DrawWorld (void);
1451 //void R_RenderDlights (void);
1452 void R_DrawParticles (void);
1453
1454 /*
1455 =============
1456 R_Clear
1457 =============
1458 */
1459 void R_Clear (void)
1460 {
1461 //      glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // LordHavoc: moved to SCR_UpdateScreen
1462         gldepthmin = 0;
1463         gldepthmax = 1;
1464         glDepthFunc (GL_LEQUAL);
1465
1466         glDepthRange (gldepthmin, gldepthmax);
1467 }
1468
1469 // LordHavoc: my trick to *FIX* GLQuake lighting once and for all :)
1470 void GL_Brighten()
1471 {
1472         glMatrixMode(GL_PROJECTION);
1473     glLoadIdentity ();
1474         glOrtho  (0, vid.width, vid.height, 0, -99999, 99999);
1475         glMatrixMode(GL_MODELVIEW);
1476     glLoadIdentity ();
1477         glDisable (GL_DEPTH_TEST);
1478         glDisable (GL_CULL_FACE);
1479         glDisable(GL_TEXTURE_2D);
1480         glEnable(GL_BLEND);
1481         glBlendFunc (GL_DST_COLOR, GL_ONE);
1482         glBegin (GL_TRIANGLES);
1483         glColor3f (1, 1, 1);
1484         glVertex2f (-5000, -5000);
1485         glVertex2f (10000, -5000);
1486         glVertex2f (-5000, 10000);
1487         glEnd ();
1488         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1489         glDisable(GL_BLEND);
1490         glEnable(GL_TEXTURE_2D);
1491         glEnable (GL_DEPTH_TEST);
1492         glEnable (GL_CULL_FACE);
1493 }
1494
1495 extern cvar_t contrast;
1496 extern cvar_t brightness;
1497 extern cvar_t gl_lightmode;
1498
1499 void GL_BlendView()
1500 {
1501         glMatrixMode(GL_PROJECTION);
1502     glLoadIdentity ();
1503         glOrtho  (0, vid.width, vid.height, 0, -99999, 99999);
1504         glMatrixMode(GL_MODELVIEW);
1505     glLoadIdentity ();
1506         glDisable (GL_DEPTH_TEST);
1507         glDisable (GL_CULL_FACE);
1508         glDisable(GL_TEXTURE_2D);
1509         glEnable(GL_BLEND);
1510         if (lighthalf)
1511         {
1512                 glBlendFunc (GL_DST_COLOR, GL_ONE);
1513                 glBegin (GL_TRIANGLES);
1514                 glColor3f (1, 1, 1);
1515                 glVertex2f (-5000, -5000);
1516                 glVertex2f (10000, -5000);
1517                 glVertex2f (-5000, 10000);
1518                 glEnd ();
1519         }
1520         glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1521         contrast.value = bound(0.2, contrast.value, 1.0);
1522         if (/*gl_polyblend.value && */v_blend[3])
1523         {
1524                 glBegin (GL_TRIANGLES);
1525                 glColor4fv (v_blend);
1526                 glVertex2f (-5000, -5000);
1527                 glVertex2f (10000, -5000);
1528                 glVertex2f (-5000, 10000);
1529                 glEnd ();
1530         }
1531
1532         glEnable (GL_CULL_FACE);
1533         glEnable (GL_DEPTH_TEST);
1534         glDisable(GL_BLEND);
1535         glEnable(GL_TEXTURE_2D);
1536 }
1537
1538 #define TIMEREPORT(DESC) \
1539         if (r_speeds2.value)\
1540         {\
1541                 temptime = -currtime;\
1542                 currtime = Sys_FloatTime();\
1543                 temptime += currtime;\
1544                 Con_Printf(DESC " %.4fms ", temptime * 1000.0);\
1545         }
1546
1547 /*
1548 ================
1549 R_RenderView
1550
1551 r_refdef must be set before the first call
1552 ================
1553 */
1554 extern qboolean intimerefresh;
1555 extern qboolean skyisvisible;
1556 extern void R_Sky();
1557 extern void UploadLightmaps();
1558 void R_RenderView (void)
1559 {
1560 //      double currtime, temptime;
1561 //      if (r_norefresh.value)
1562 //              return;
1563
1564         if (!r_worldentity.model || !cl.worldmodel)
1565                 Sys_Error ("R_RenderView: NULL worldmodel");
1566
1567         lighthalf = gl_lightmode.value;
1568
1569         FOG_framebegin();
1570
1571 //      if (r_speeds2.value)
1572 //      {
1573 //              currtime = Sys_FloatTime();
1574 //              Con_Printf("render time: ");
1575 //      }
1576         R_Clear();
1577 //      TIMEREPORT("R_Clear")
1578
1579         // render normal view
1580
1581         R_SetupFrame ();
1582         R_SetFrustum ();
1583         R_SetupGL ();
1584
1585         skypolyclear();
1586         wallpolyclear();
1587         transpolyclear();
1588         skyisvisible = false;
1589
1590         R_MarkLeaves ();        // done here so we know if we're in water
1591         R_DrawWorld ();         // adds static entities to the list
1592         if (!intimerefresh)
1593                 S_ExtraUpdate ();       // don't let sound get messed up if going slow
1594         R_DrawEntitiesOnList1 (); // BSP models
1595
1596         skypolyrender(); // fogged sky polys, affects depth
1597         if (skyname[0] && skyisvisible && !fogenabled)
1598                 R_Sky(); // does not affect depth, draws over the sky polys
1599
1600         UploadLightmaps();
1601         wallpolyrender();
1602
1603         R_DrawEntitiesOnList2 (); // other models
1604 //      R_RenderDlights ();
1605         R_DrawViewModel ();
1606         R_DrawParticles ();
1607
1608         transpolyrender();
1609
1610         FOG_frameend();
1611         GL_BlendView();
1612 //      if (r_speeds2.value)
1613 //              Con_Printf("\n");
1614 }