fix a bug that caused GL20 render path to always ask for tangents and
[divverent/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 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "image.h"
26
27 mempool_t *r_main_mempool;
28 rtexturepool_t *r_main_texturepool;
29
30 //
31 // screen size info
32 //
33 r_refdef_t r_refdef;
34 r_view_t r_view;
35 r_viewcache_t r_viewcache;
36
37 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
38 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
39 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
40 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
41 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
42 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
43 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
44 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
45 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
46 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
47 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
48 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
49 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
50 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
51 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
52 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
53 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
54 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
55 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
56 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
57 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
58 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
59 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
60 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this)"};
61 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
62 cvar_t r_q1bsp_skymasking = {0, "r_qb1sp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
63
64 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
65 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
66 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
67 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
68 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
69 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
70 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
71
72 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of hardware texture units reported by driver (note: setting this to 1 turns off gl_combine)"};
73
74 cvar_t r_glsl = {CVAR_SAVE, "r_glsl", "1", "enables use of OpenGL 2.0 pixel shaders for lighting"};
75 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
76 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
77 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
78 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
79
80 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "1", "enables animation smoothing on sprites (requires r_lerpmodels 1)"};
81 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
82 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
83
84 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
85 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
86 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
87 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
88 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
89 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
90 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
91
92 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
93 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
94 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
95 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
96
97 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
98
99 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
100
101 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
102
103 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
104 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
105
106 typedef struct r_glsl_bloomshader_s
107 {
108         int program;
109         int loc_Texture_Bloom;
110 }
111 r_glsl_bloomshader_t;
112
113 static struct r_bloomstate_s
114 {
115         qboolean enabled;
116         qboolean hdr;
117
118         int bloomwidth, bloomheight;
119
120         int screentexturewidth, screentextureheight;
121         rtexture_t *texture_screen;
122
123         int bloomtexturewidth, bloomtextureheight;
124         rtexture_t *texture_bloom;
125
126         r_glsl_bloomshader_t *shader;
127
128         // arrays for rendering the screen passes
129         float screentexcoord2f[8];
130         float bloomtexcoord2f[8];
131         float offsettexcoord2f[8];
132 }
133 r_bloomstate;
134
135 // shadow volume bsp struct with automatically growing nodes buffer
136 svbsp_t r_svbsp;
137
138 rtexture_t *r_texture_blanknormalmap;
139 rtexture_t *r_texture_white;
140 rtexture_t *r_texture_black;
141 rtexture_t *r_texture_notexture;
142 rtexture_t *r_texture_whitecube;
143 rtexture_t *r_texture_normalizationcube;
144 rtexture_t *r_texture_fogattenuation;
145 //rtexture_t *r_texture_fogintensity;
146
147 // information about each possible shader permutation
148 r_glsl_permutation_t r_glsl_permutations[SHADERPERMUTATION_MAX];
149 // currently selected permutation
150 r_glsl_permutation_t *r_glsl_permutation;
151
152 char r_qwskincache[MAX_SCOREBOARD][MAX_QPATH];
153 skinframe_t *r_qwskincache_skinframe[MAX_SCOREBOARD];
154
155 // vertex coordinates for a quad that covers the screen exactly
156 const static float r_screenvertex3f[12] =
157 {
158         0, 0, 0,
159         1, 0, 0,
160         1, 1, 0,
161         0, 1, 0
162 };
163
164 extern void R_DrawModelShadows(void);
165
166 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
167 {
168         int i;
169         for (i = 0;i < verts;i++)
170         {
171                 out[0] = in[0] * r;
172                 out[1] = in[1] * g;
173                 out[2] = in[2] * b;
174                 out[3] = in[3];
175                 in += 4;
176                 out += 4;
177         }
178 }
179
180 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
181 {
182         int i;
183         for (i = 0;i < verts;i++)
184         {
185                 out[0] = r;
186                 out[1] = g;
187                 out[2] = b;
188                 out[3] = a;
189                 out += 4;
190         }
191 }
192
193 // FIXME: move this to client?
194 void FOG_clear(void)
195 {
196         if (gamemode == GAME_NEHAHRA)
197         {
198                 Cvar_Set("gl_fogenable", "0");
199                 Cvar_Set("gl_fogdensity", "0.2");
200                 Cvar_Set("gl_fogred", "0.3");
201                 Cvar_Set("gl_foggreen", "0.3");
202                 Cvar_Set("gl_fogblue", "0.3");
203         }
204         r_refdef.fog_density = r_refdef.fog_red = r_refdef.fog_green = r_refdef.fog_blue = 0.0f;
205 }
206
207 float FogPoint_World(const vec3_t p)
208 {
209         int fogmasktableindex = (int)(VectorDistance((p), r_view.origin) * r_refdef.fogmasktabledistmultiplier);
210         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
211 }
212
213 float FogPoint_Model(const vec3_t p)
214 {
215         int fogmasktableindex = (int)(VectorDistance((p), rsurface_modelorg) * r_refdef.fogmasktabledistmultiplier);
216         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
217 }
218
219 static void R_BuildBlankTextures(void)
220 {
221         unsigned char data[4];
222         data[0] = 128; // normal X
223         data[1] = 128; // normal Y
224         data[2] = 255; // normal Z
225         data[3] = 128; // height
226         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
227         data[0] = 255;
228         data[1] = 255;
229         data[2] = 255;
230         data[3] = 255;
231         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
232         data[0] = 0;
233         data[1] = 0;
234         data[2] = 0;
235         data[3] = 255;
236         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
237 }
238
239 static void R_BuildNoTexture(void)
240 {
241         int x, y;
242         unsigned char pix[16][16][4];
243         // this makes a light grey/dark grey checkerboard texture
244         for (y = 0;y < 16;y++)
245         {
246                 for (x = 0;x < 16;x++)
247                 {
248                         if ((y < 8) ^ (x < 8))
249                         {
250                                 pix[y][x][0] = 128;
251                                 pix[y][x][1] = 128;
252                                 pix[y][x][2] = 128;
253                                 pix[y][x][3] = 255;
254                         }
255                         else
256                         {
257                                 pix[y][x][0] = 64;
258                                 pix[y][x][1] = 64;
259                                 pix[y][x][2] = 64;
260                                 pix[y][x][3] = 255;
261                         }
262                 }
263         }
264         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_RGBA, TEXF_MIPMAP, NULL);
265 }
266
267 static void R_BuildWhiteCube(void)
268 {
269         unsigned char data[6*1*1*4];
270         data[ 0] = 255;data[ 1] = 255;data[ 2] = 255;data[ 3] = 255;
271         data[ 4] = 255;data[ 5] = 255;data[ 6] = 255;data[ 7] = 255;
272         data[ 8] = 255;data[ 9] = 255;data[10] = 255;data[11] = 255;
273         data[12] = 255;data[13] = 255;data[14] = 255;data[15] = 255;
274         data[16] = 255;data[17] = 255;data[18] = 255;data[19] = 255;
275         data[20] = 255;data[21] = 255;data[22] = 255;data[23] = 255;
276         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
277 }
278
279 static void R_BuildNormalizationCube(void)
280 {
281         int x, y, side;
282         vec3_t v;
283         vec_t s, t, intensity;
284 #define NORMSIZE 64
285         unsigned char data[6][NORMSIZE][NORMSIZE][4];
286         for (side = 0;side < 6;side++)
287         {
288                 for (y = 0;y < NORMSIZE;y++)
289                 {
290                         for (x = 0;x < NORMSIZE;x++)
291                         {
292                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
293                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
294                                 switch(side)
295                                 {
296                                 default:
297                                 case 0:
298                                         v[0] = 1;
299                                         v[1] = -t;
300                                         v[2] = -s;
301                                         break;
302                                 case 1:
303                                         v[0] = -1;
304                                         v[1] = -t;
305                                         v[2] = s;
306                                         break;
307                                 case 2:
308                                         v[0] = s;
309                                         v[1] = 1;
310                                         v[2] = t;
311                                         break;
312                                 case 3:
313                                         v[0] = s;
314                                         v[1] = -1;
315                                         v[2] = -t;
316                                         break;
317                                 case 4:
318                                         v[0] = s;
319                                         v[1] = -t;
320                                         v[2] = 1;
321                                         break;
322                                 case 5:
323                                         v[0] = -s;
324                                         v[1] = -t;
325                                         v[2] = -1;
326                                         break;
327                                 }
328                                 intensity = 127.0f / sqrt(DotProduct(v, v));
329                                 data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[0]);
330                                 data[side][y][x][1] = (unsigned char)(128.0f + intensity * v[1]);
331                                 data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[2]);
332                                 data[side][y][x][3] = 255;
333                         }
334                 }
335         }
336         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
337 }
338
339 static void R_BuildFogTexture(void)
340 {
341         int x, b;
342 #define FOGWIDTH 64
343         unsigned char data1[FOGWIDTH][4];
344         //unsigned char data2[FOGWIDTH][4];
345         for (x = 0;x < FOGWIDTH;x++)
346         {
347                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
348                 data1[x][0] = b;
349                 data1[x][1] = b;
350                 data1[x][2] = b;
351                 data1[x][3] = 255;
352                 //data2[x][0] = 255 - b;
353                 //data2[x][1] = 255 - b;
354                 //data2[x][2] = 255 - b;
355                 //data2[x][3] = 255;
356         }
357         r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
358         //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
359 }
360
361 static const char *builtinshaderstring =
362 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
363 "// written by Forest 'LordHavoc' Hale\n"
364 "\n"
365 "// common definitions between vertex shader and fragment shader:\n"
366 "\n"
367 "#ifdef __GLSL_CG_DATA_TYPES\n"
368 "#define myhalf half\n"
369 "#define myhvec2 hvec2\n"
370 "#define myhvec3 hvec3\n"
371 "#define myhvec4 hvec4\n"
372 "#else\n"
373 "#define myhalf float\n"
374 "#define myhvec2 vec2\n"
375 "#define myhvec3 vec3\n"
376 "#define myhvec4 vec4\n"
377 "#endif\n"
378 "\n"
379 "varying vec2 TexCoord;\n"
380 "varying vec2 TexCoordLightmap;\n"
381 "\n"
382 "varying vec3 CubeVector;\n"
383 "varying vec3 LightVector;\n"
384 "varying vec3 EyeVector;\n"
385 "#ifdef USEFOG\n"
386 "varying vec3 EyeVectorModelSpace;\n"
387 "#endif\n"
388 "\n"
389 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
390 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
391 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
392 "\n"
393 "\n"
394 "\n"
395 "\n"
396 "// vertex shader specific:\n"
397 "#ifdef VERTEX_SHADER\n"
398 "\n"
399 "uniform vec3 LightPosition;\n"
400 "uniform vec3 EyePosition;\n"
401 "uniform vec3 LightDir;\n"
402 "\n"
403 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3)\n"
404 "\n"
405 "void main(void)\n"
406 "{\n"
407 "       gl_FrontColor = gl_Color;\n"
408 "       // copy the surface texcoord\n"
409 "       TexCoord = vec2(gl_TextureMatrix[0] * gl_MultiTexCoord0);\n"
410 "#if !defined(MODE_LIGHTSOURCE) && !defined(MODE_LIGHTDIRECTION)\n"
411 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
412 "#endif\n"
413 "\n"
414 "#ifdef MODE_LIGHTSOURCE\n"
415 "       // transform vertex position into light attenuation/cubemap space\n"
416 "       // (-1 to +1 across the light box)\n"
417 "       CubeVector = vec3(gl_TextureMatrix[3] * gl_Vertex);\n"
418 "\n"
419 "       // transform unnormalized light direction into tangent space\n"
420 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
421 "       //  normalize it per pixel)\n"
422 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
423 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
424 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
425 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
426 "#endif\n"
427 "\n"
428 "#ifdef MODE_LIGHTDIRECTION\n"
429 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
430 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
431 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
432 "#endif\n"
433 "\n"
434 "       // transform unnormalized eye direction into tangent space\n"
435 "#ifndef USEFOG\n"
436 "       vec3 EyeVectorModelSpace;\n"
437 "#endif\n"
438 "       EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
439 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
440 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
441 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
442 "\n"
443 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
444 "       VectorS = gl_MultiTexCoord1.xyz;\n"
445 "       VectorT = gl_MultiTexCoord2.xyz;\n"
446 "       VectorR = gl_MultiTexCoord3.xyz;\n"
447 "#endif\n"
448 "\n"
449 "       // transform vertex to camera space, using ftransform to match non-VS\n"
450 "       // rendering\n"
451 "       gl_Position = ftransform();\n"
452 "}\n"
453 "\n"
454 "#endif // VERTEX_SHADER\n"
455 "\n"
456 "\n"
457 "\n"
458 "\n"
459 "// fragment shader specific:\n"
460 "#ifdef FRAGMENT_SHADER\n"
461 "\n"
462 "// 11 textures, we can only use up to 16 on DX9-class hardware\n"
463 "uniform sampler2D Texture_Normal;\n"
464 "uniform sampler2D Texture_Color;\n"
465 "uniform sampler2D Texture_Gloss;\n"
466 "uniform samplerCube Texture_Cube;\n"
467 "uniform sampler2D Texture_Attenuation;\n"
468 "uniform sampler2D Texture_FogMask;\n"
469 "uniform sampler2D Texture_Pants;\n"
470 "uniform sampler2D Texture_Shirt;\n"
471 "uniform sampler2D Texture_Lightmap;\n"
472 "uniform sampler2D Texture_Deluxemap;\n"
473 "uniform sampler2D Texture_Glow;\n"
474 "\n"
475 "uniform myhvec3 LightColor;\n"
476 "uniform myhvec3 AmbientColor;\n"
477 "uniform myhvec3 DiffuseColor;\n"
478 "uniform myhvec3 SpecularColor;\n"
479 "uniform myhvec3 Color_Pants;\n"
480 "uniform myhvec3 Color_Shirt;\n"
481 "uniform myhvec3 FogColor;\n"
482 "\n"
483 "uniform myhalf GlowScale;\n"
484 "uniform myhalf SceneBrightness;\n"
485 "\n"
486 "uniform float OffsetMapping_Scale;\n"
487 "uniform float OffsetMapping_Bias;\n"
488 "uniform float FogRangeRecip;\n"
489 "\n"
490 "uniform myhalf AmbientScale;\n"
491 "uniform myhalf DiffuseScale;\n"
492 "uniform myhalf SpecularScale;\n"
493 "uniform myhalf SpecularPower;\n"
494 "\n"
495 "#ifdef USEOFFSETMAPPING\n"
496 "vec2 OffsetMapping(vec2 TexCoord)\n"
497 "{\n"
498 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
499 "       // 14 sample relief mapping: linear search and then binary search\n"
500 "       // this basically steps forward a small amount repeatedly until it finds\n"
501 "       // itself inside solid, then jitters forward and back using decreasing\n"
502 "       // amounts to find the impact\n"
503 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
504 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
505 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
506 "       vec3 RT = vec3(TexCoord, 1);\n"
507 "       OffsetVector *= 0.1;\n"
508 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
509 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
510 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
511 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
512 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
513 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
514 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
515 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
516 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
517 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
518 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
519 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
520 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
521 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
522 "       return RT.xy;\n"
523 "#else\n"
524 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
525 "       // this basically moves forward the full distance, and then backs up based\n"
526 "       // on height of samples\n"
527 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
528 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
529 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
530 "       TexCoord += OffsetVector;\n"
531 "       OffsetVector *= 0.333;\n"
532 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
533 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
534 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
535 "       return TexCoord;\n"
536 "#endif\n"
537 "}\n"
538 "#endif\n"
539 "\n"
540 "void main(void)\n"
541 "{\n"
542 "#ifdef USEOFFSETMAPPING\n"
543 "       // apply offsetmapping\n"
544 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
545 "#define TexCoord TexCoordOffset\n"
546 "#endif\n"
547 "\n"
548 "       // combine the diffuse textures (base, pants, shirt)\n"
549 "       myhvec4 color = myhvec4(texture2D(Texture_Color, TexCoord));\n"
550 "#ifdef USECOLORMAPPING\n"
551 "       color.rgb += myhvec3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhvec3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
552 "#endif\n"
553 "\n"
554 "\n"
555 "\n"
556 "\n"
557 "#ifdef MODE_LIGHTSOURCE\n"
558 "       // light source\n"
559 "\n"
560 "       // calculate surface normal, light normal, and specular normal\n"
561 "       // compute color intensity for the two textures (colormap and glossmap)\n"
562 "       // scale by light color and attenuation as efficiently as possible\n"
563 "       // (do as much scalar math as possible rather than vector math)\n"
564 "#ifdef USESPECULAR\n"
565 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
566 "       myhvec3 diffusenormal = myhvec3(normalize(LightVector));\n"
567 "       myhvec3 specularnormal = normalize(diffusenormal + myhvec3(normalize(EyeVector)));\n"
568 "\n"
569 "       // calculate directional shading\n"
570 "       color.rgb = LightColor * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (color.rgb * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))) + (SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower)) * myhvec3(texture2D(Texture_Gloss, TexCoord)));\n"
571 "#else\n"
572 "#ifdef USEDIFFUSE\n"
573 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
574 "       myhvec3 diffusenormal = myhvec3(normalize(LightVector));\n"
575 "\n"
576 "       // calculate directional shading\n"
577 "       color.rgb = color.rgb * LightColor * (myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))));\n"
578 "#else\n"
579 "       // calculate directionless shading\n"
580 "       color.rgb = color.rgb * LightColor * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
581 "#endif\n"
582 "#endif\n"
583 "\n"
584 "#ifdef USECUBEFILTER\n"
585 "       // apply light cubemap filter\n"
586 "       //color.rgb *= normalize(CubeVector) * 0.5 + 0.5;//vec3(textureCube(Texture_Cube, CubeVector));\n"
587 "       color.rgb *= myhvec3(textureCube(Texture_Cube, CubeVector));\n"
588 "#endif\n"
589 "\n"
590 "\n"
591 "\n"
592 "\n"
593 "#elif defined(MODE_LIGHTDIRECTION)\n"
594 "       // directional model lighting\n"
595 "\n"
596 "       // get the surface normal and light normal\n"
597 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
598 "       myhvec3 diffusenormal = myhvec3(normalize(LightVector));\n"
599 "\n"
600 "       // calculate directional shading\n"
601 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
602 "#ifdef USESPECULAR\n"
603 "       myhvec3 specularnormal = normalize(diffusenormal + myhvec3(normalize(EyeVector)));\n"
604 "       color.rgb += myhvec3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
605 "#endif\n"
606 "\n"
607 "\n"
608 "\n"
609 "\n"
610 "#elif defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
611 "       // deluxemap lightmapping using light vectors in modelspace (evil q3map2)\n"
612 "\n"
613 "       // get the surface normal and light normal\n"
614 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
615 "\n"
616 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
617 "       myhvec3 diffusenormal_modelspace = myhvec3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhvec3(0.5);\n"
618 "       myhvec3 diffusenormal = normalize(myhvec3(dot(diffusenormal_modelspace, myhvec3(VectorS)), dot(diffusenormal_modelspace, myhvec3(VectorT)), dot(diffusenormal_modelspace, myhvec3(VectorR))));\n"
619 "#else\n"
620 "       myhvec3 diffusenormal = normalize(myhvec3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhvec3(0.5));\n"
621 "#endif\n"
622 "       // calculate directional shading\n"
623 "       myhvec3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0)));\n"
624 "#ifdef USESPECULAR\n"
625 "       myhvec3 specularnormal = myhvec3(normalize(diffusenormal + myhvec3(normalize(EyeVector))));\n"
626 "       tempcolor += myhvec3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
627 "#endif\n"
628 "\n"
629 "       // apply lightmap color\n"
630 "       color.rgb = tempcolor * myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap)) + color.rgb * AmbientScale;\n"
631 "\n"
632 "\n"
633 "#else // MODE none (lightmap)\n"
634 "       // apply lightmap color\n"
635 "       color.rgb *= myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap)) * DiffuseScale + myhvec3(AmbientScale);\n"
636 "#endif // MODE\n"
637 "\n"
638 "       color *= myhvec4(gl_Color);\n"
639 "\n"
640 "#ifdef USEGLOW\n"
641 "       color.rgb += myhvec3(texture2D(Texture_Glow, TexCoord)) * GlowScale;\n"
642 "#endif\n"
643 "\n"
644 "#ifdef USEFOG\n"
645 "       // apply fog\n"
646 "       color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhvec2(length(EyeVectorModelSpace)*FogRangeRecip, 0.0))));\n"
647 "#endif\n"
648 "\n"
649 "       color.rgb *= SceneBrightness;\n"
650 "\n"
651 "       gl_FragColor = vec4(color);\n"
652 "}\n"
653 "\n"
654 "#endif // FRAGMENT_SHADER\n"
655 ;
656
657 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
658 const char *permutationinfo[][2] =
659 {
660         {"#define MODE_LIGHTSOURCE\n", " lightsource"},
661         {"#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
662         {"#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
663         {"#define MODE_LIGHTDIRECTION\n", " lightdirection"},
664         {"#define USEGLOW\n", " glow"},
665         {"#define USEFOG\n", " fog"},
666         {"#define USECOLORMAPPING\n", " colormapping"},
667         {"#define USEDIFFUSE\n", " diffuse"},
668         {"#define USESPECULAR\n", " specular"},
669         {"#define USECUBEFILTER\n", " cubefilter"},
670         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
671         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
672         {NULL, NULL}
673 };
674
675 void R_GLSL_CompilePermutation(const char *filename, int permutation)
676 {
677         int i;
678         qboolean shaderfound;
679         r_glsl_permutation_t *p = r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK);
680         int vertstrings_count;
681         int geomstrings_count;
682         int fragstrings_count;
683         char *shaderstring;
684         const char *vertstrings_list[32+1];
685         const char *geomstrings_list[32+1];
686         const char *fragstrings_list[32+1];
687         char permutationname[256];
688         if (p->compiled)
689                 return;
690         p->compiled = true;
691         p->program = 0;
692         vertstrings_list[0] = "#define VERTEX_SHADER\n";
693         geomstrings_list[0] = "#define GEOMETRY_SHADER\n";
694         fragstrings_list[0] = "#define FRAGMENT_SHADER\n";
695         vertstrings_count = 1;
696         geomstrings_count = 1;
697         fragstrings_count = 1;
698         permutationname[0] = 0;
699         for (i = 0;permutationinfo[i][0];i++)
700         {
701                 if (permutation & (1<<i))
702                 {
703                         vertstrings_list[vertstrings_count++] = permutationinfo[i][0];
704                         geomstrings_list[geomstrings_count++] = permutationinfo[i][0];
705                         fragstrings_list[fragstrings_count++] = permutationinfo[i][0];
706                         strlcat(permutationname, permutationinfo[i][1], sizeof(permutationname));
707                 }
708                 else
709                 {
710                         // keep line numbers correct
711                         vertstrings_list[vertstrings_count++] = "\n";
712                         geomstrings_list[geomstrings_count++] = "\n";
713                         fragstrings_list[fragstrings_count++] = "\n";
714                 }
715         }
716         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
717         shaderfound = false;
718         if (shaderstring)
719         {
720                 Con_DPrintf("GLSL shader text for \"%s\" loaded from disk\n", filename);
721                 vertstrings_list[vertstrings_count++] = shaderstring;
722                 geomstrings_list[geomstrings_count++] = shaderstring;
723                 fragstrings_list[fragstrings_count++] = shaderstring;
724                 shaderfound = true;
725         }
726         else if (!strcmp(filename, "glsl/default.glsl"))
727         {
728                 Con_DPrintf("GLSL shader text for \"%s\" loaded from engine\n", filename);
729                 vertstrings_list[vertstrings_count++] = builtinshaderstring;
730                 geomstrings_list[geomstrings_count++] = builtinshaderstring;
731                 fragstrings_list[fragstrings_count++] = builtinshaderstring;
732                 shaderfound = true;
733         }
734         // clear any lists that are not needed by this shader
735         if (!(permutation & SHADERPERMUTATION_USES_VERTEXSHADER))
736                 vertstrings_count = 0;
737         if (!(permutation & SHADERPERMUTATION_USES_GEOMETRYSHADER))
738                 geomstrings_count = 0;
739         if (!(permutation & SHADERPERMUTATION_USES_FRAGMENTSHADER))
740                 fragstrings_count = 0;
741         // compile the shader program
742         if (shaderfound && vertstrings_count + geomstrings_count + fragstrings_count)
743                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
744         if (p->program)
745         {
746                 CHECKGLERROR
747                 qglUseProgramObjectARB(p->program);CHECKGLERROR
748                 // look up all the uniform variable names we care about, so we don't
749                 // have to look them up every time we set them
750                 p->loc_Texture_Normal      = qglGetUniformLocationARB(p->program, "Texture_Normal");
751                 p->loc_Texture_Color       = qglGetUniformLocationARB(p->program, "Texture_Color");
752                 p->loc_Texture_Gloss       = qglGetUniformLocationARB(p->program, "Texture_Gloss");
753                 p->loc_Texture_Cube        = qglGetUniformLocationARB(p->program, "Texture_Cube");
754                 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
755                 p->loc_Texture_FogMask     = qglGetUniformLocationARB(p->program, "Texture_FogMask");
756                 p->loc_Texture_Pants       = qglGetUniformLocationARB(p->program, "Texture_Pants");
757                 p->loc_Texture_Shirt       = qglGetUniformLocationARB(p->program, "Texture_Shirt");
758                 p->loc_Texture_Lightmap    = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
759                 p->loc_Texture_Deluxemap   = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
760                 p->loc_Texture_Glow        = qglGetUniformLocationARB(p->program, "Texture_Glow");
761                 p->loc_FogColor            = qglGetUniformLocationARB(p->program, "FogColor");
762                 p->loc_LightPosition       = qglGetUniformLocationARB(p->program, "LightPosition");
763                 p->loc_EyePosition         = qglGetUniformLocationARB(p->program, "EyePosition");
764                 p->loc_LightColor          = qglGetUniformLocationARB(p->program, "LightColor");
765                 p->loc_Color_Pants         = qglGetUniformLocationARB(p->program, "Color_Pants");
766                 p->loc_Color_Shirt         = qglGetUniformLocationARB(p->program, "Color_Shirt");
767                 p->loc_FogRangeRecip       = qglGetUniformLocationARB(p->program, "FogRangeRecip");
768                 p->loc_AmbientScale        = qglGetUniformLocationARB(p->program, "AmbientScale");
769                 p->loc_DiffuseScale        = qglGetUniformLocationARB(p->program, "DiffuseScale");
770                 p->loc_SpecularPower       = qglGetUniformLocationARB(p->program, "SpecularPower");
771                 p->loc_SpecularScale       = qglGetUniformLocationARB(p->program, "SpecularScale");
772                 p->loc_GlowScale           = qglGetUniformLocationARB(p->program, "GlowScale");
773                 p->loc_SceneBrightness     = qglGetUniformLocationARB(p->program, "SceneBrightness");
774                 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
775                 p->loc_AmbientColor        = qglGetUniformLocationARB(p->program, "AmbientColor");
776                 p->loc_DiffuseColor        = qglGetUniformLocationARB(p->program, "DiffuseColor");
777                 p->loc_SpecularColor       = qglGetUniformLocationARB(p->program, "SpecularColor");
778                 p->loc_LightDir            = qglGetUniformLocationARB(p->program, "LightDir");
779                 // initialize the samplers to refer to the texture units we use
780                 if (p->loc_Texture_Normal >= 0)    qglUniform1iARB(p->loc_Texture_Normal, 0);
781                 if (p->loc_Texture_Color >= 0)     qglUniform1iARB(p->loc_Texture_Color, 1);
782                 if (p->loc_Texture_Gloss >= 0)     qglUniform1iARB(p->loc_Texture_Gloss, 2);
783                 if (p->loc_Texture_Cube >= 0)      qglUniform1iARB(p->loc_Texture_Cube, 3);
784                 if (p->loc_Texture_FogMask >= 0)   qglUniform1iARB(p->loc_Texture_FogMask, 4);
785                 if (p->loc_Texture_Pants >= 0)     qglUniform1iARB(p->loc_Texture_Pants, 5);
786                 if (p->loc_Texture_Shirt >= 0)     qglUniform1iARB(p->loc_Texture_Shirt, 6);
787                 if (p->loc_Texture_Lightmap >= 0)  qglUniform1iARB(p->loc_Texture_Lightmap, 7);
788                 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap, 8);
789                 if (p->loc_Texture_Glow >= 0)      qglUniform1iARB(p->loc_Texture_Glow, 9);
790                 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation, 10);
791                 CHECKGLERROR
792                 qglUseProgramObjectARB(0);CHECKGLERROR
793         }
794         else
795                 Con_Printf("permutation%s failed for shader %s, some features may not work properly!\n", permutationname, "glsl/default.glsl");
796         if (shaderstring)
797                 Mem_Free(shaderstring);
798 }
799
800 void R_GLSL_Restart_f(void)
801 {
802         int i;
803         for (i = 0;i < SHADERPERMUTATION_MAX;i++)
804                 if (r_glsl_permutations[i].program)
805                         GL_Backend_FreeProgram(r_glsl_permutations[i].program);
806         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
807 }
808
809 extern rtexture_t *r_shadow_attenuationgradienttexture;
810 extern rtexture_t *r_shadow_attenuation2dtexture;
811 extern rtexture_t *r_shadow_attenuation3dtexture;
812 int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale)
813 {
814         // select a permutation of the lighting shader appropriate to this
815         // combination of texture, entity, light source, and fogging, only use the
816         // minimum features necessary to avoid wasting rendering time in the
817         // fragment shader on features that are not being used
818         const char *shaderfilename = NULL;
819         unsigned int permutation = 0;
820         r_glsl_permutation = NULL;
821         // TODO: implement geometry-shader based shadow volumes someday
822         if (r_shadow_rtlight)
823         {
824                 // light source
825                 shaderfilename = "glsl/default.glsl";
826                 permutation = SHADERPERMUTATION_MODE_LIGHTSOURCE | SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
827                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
828                         permutation |= SHADERPERMUTATION_CUBEFILTER;
829                 if (diffusescale > 0)
830                         permutation |= SHADERPERMUTATION_DIFFUSE;
831                 if (specularscale > 0)
832                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
833                 if (r_refdef.fogenabled)
834                         permutation |= SHADERPERMUTATION_FOG;
835                 if (rsurface_texture->colormapping)
836                         permutation |= SHADERPERMUTATION_COLORMAPPING;
837                 if (r_glsl_offsetmapping.integer)
838                 {
839                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
840                         if (r_glsl_offsetmapping_reliefmapping.integer)
841                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
842                 }
843         }
844         else if (rsurface_texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
845         {
846                 // bright unshaded geometry
847                 shaderfilename = "glsl/default.glsl";
848                 permutation = SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
849                 if (rsurface_texture->currentskinframe->glow)
850                         permutation |= SHADERPERMUTATION_GLOW;
851                 if (r_refdef.fogenabled)
852                         permutation |= SHADERPERMUTATION_FOG;
853                 if (rsurface_texture->colormapping)
854                         permutation |= SHADERPERMUTATION_COLORMAPPING;
855                 if (r_glsl_offsetmapping.integer)
856                 {
857                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
858                         if (r_glsl_offsetmapping_reliefmapping.integer)
859                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
860                 }
861         }
862         else if (modellighting)
863         {
864                 // directional model lighting
865                 shaderfilename = "glsl/default.glsl";
866                 permutation = SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
867                 permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTION;
868                 if (rsurface_texture->currentskinframe->glow)
869                         permutation |= SHADERPERMUTATION_GLOW;
870                 if (specularscale > 0)
871                         permutation |= SHADERPERMUTATION_SPECULAR;
872                 if (r_refdef.fogenabled)
873                         permutation |= SHADERPERMUTATION_FOG;
874                 if (rsurface_texture->colormapping)
875                         permutation |= SHADERPERMUTATION_COLORMAPPING;
876                 if (r_glsl_offsetmapping.integer)
877                 {
878                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
879                         if (r_glsl_offsetmapping_reliefmapping.integer)
880                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
881                 }
882         }
883         else
884         {
885                 // lightmapped wall
886                 shaderfilename = "glsl/default.glsl";
887                 permutation = SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
888                 if (r_glsl_deluxemapping.integer >= 1 && rsurface_lightmaptexture && r_refdef.worldmodel && r_refdef.worldmodel->brushq3.deluxemapping)
889                 {
890                         // deluxemapping (light direction texture)
891                         if (rsurface_lightmaptexture && r_refdef.worldmodel && r_refdef.worldmodel->brushq3.deluxemapping && r_refdef.worldmodel->brushq3.deluxemapping_modelspace)
892                                 permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTIONMAP_MODELSPACE;
893                         else
894                                 permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
895                         if (specularscale > 0)
896                                 permutation |= SHADERPERMUTATION_SPECULAR;
897                 }
898                 else if (r_glsl_deluxemapping.integer >= 2)
899                 {
900                         // fake deluxemapping (uniform light direction in tangentspace)
901                         permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
902                         if (specularscale > 0)
903                                 permutation |= SHADERPERMUTATION_SPECULAR;
904                 }
905                 else
906                 {
907                         // ordinary lightmapping
908                         permutation |= 0;
909                 }
910                 if (rsurface_texture->currentskinframe->glow)
911                         permutation |= SHADERPERMUTATION_GLOW;
912                 if (r_refdef.fogenabled)
913                         permutation |= SHADERPERMUTATION_FOG;
914                 if (rsurface_texture->colormapping)
915                         permutation |= SHADERPERMUTATION_COLORMAPPING;
916                 if (r_glsl_offsetmapping.integer)
917                 {
918                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
919                         if (r_glsl_offsetmapping_reliefmapping.integer)
920                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
921                 }
922         }
923         if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].program)
924         {
925                 if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].compiled)
926                         R_GLSL_CompilePermutation(shaderfilename, permutation);
927                 if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].program)
928                 {
929                         // remove features until we find a valid permutation
930                         unsigned int i;
931                         for (i = SHADERPERMUTATION_MASK;;i>>=1)
932                         {
933                                 if (!i)
934                                         return 0; // utterly failed
935                                 // reduce i more quickly whenever it would not remove any bits
936                                 if (permutation < i)
937                                         continue;
938                                 permutation &= i;
939                                 if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].compiled)
940                                         R_GLSL_CompilePermutation(shaderfilename, permutation);
941                                 if (r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].program)
942                                         break;
943                         }
944                 }
945         }
946         r_glsl_permutation = r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK);
947         CHECKGLERROR
948         qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
949         R_Mesh_TexMatrix(0, &rsurface_texture->currenttexmatrix);
950         if (permutation & SHADERPERMUTATION_MODE_LIGHTSOURCE)
951         {
952                 if (r_glsl_permutation->loc_Texture_Cube >= 0 && r_shadow_rtlight) R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap));
953                 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, r_shadow_entitylightorigin[0], r_shadow_entitylightorigin[1], r_shadow_entitylightorigin[2]);
954                 if (permutation & SHADERPERMUTATION_DIFFUSE)
955                 {
956                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
957                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, ambientscale);
958                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, diffusescale);
959                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, specularscale);
960                 }
961                 else
962                 {
963                         // ambient only is simpler
964                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0] * ambientscale, lightcolorbase[1] * ambientscale, lightcolorbase[2] * ambientscale);
965                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, 1);
966                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, 0);
967                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, 0);
968                 }
969         }
970         else if (permutation & SHADERPERMUTATION_MODE_LIGHTDIRECTION)
971         {
972                 if (r_glsl_permutation->loc_AmbientColor >= 0)
973                         qglUniform3fARB(r_glsl_permutation->loc_AmbientColor, rsurface_entity->modellight_ambient[0] * ambientscale, rsurface_entity->modellight_ambient[1] * ambientscale, rsurface_entity->modellight_ambient[2] * ambientscale);
974                 if (r_glsl_permutation->loc_DiffuseColor >= 0)
975                         qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor, rsurface_entity->modellight_diffuse[0] * diffusescale, rsurface_entity->modellight_diffuse[1] * diffusescale, rsurface_entity->modellight_diffuse[2] * diffusescale);
976                 if (r_glsl_permutation->loc_SpecularColor >= 0)
977                         qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface_entity->modellight_diffuse[0] * specularscale, rsurface_entity->modellight_diffuse[1] * specularscale, rsurface_entity->modellight_diffuse[2] * specularscale);
978                 if (r_glsl_permutation->loc_LightDir >= 0)
979                         qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface_entity->modellight_lightdir[0], rsurface_entity->modellight_lightdir[1], rsurface_entity->modellight_lightdir[2]);
980         }
981         else
982         {
983                 if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_ambient.value * 2.0f / 128.0f);
984                 if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity * 2.0f);
985                 if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale * 2.0f);
986         }
987         if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(0, R_GetTexture(rsurface_texture->currentskinframe->nmap));
988         if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(1, R_GetTexture(rsurface_texture->basetexture));
989         if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(2, R_GetTexture(rsurface_texture->glosstexture));
990         //if (r_glsl_permutation->loc_Texture_Cube >= 0 && permutation & SHADERPERMUTATION_MODE_LIGHTSOURCE) R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap));
991         if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(10, R_GetTexture(r_shadow_attenuationgradienttexture));
992         if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(4, R_GetTexture(r_texture_fogattenuation));
993         if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(5, R_GetTexture(rsurface_texture->currentskinframe->pants));
994         if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(6, R_GetTexture(rsurface_texture->currentskinframe->shirt));
995         //if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(7, R_GetTexture(r_texture_white));
996         //if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
997         if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(9, R_GetTexture(rsurface_texture->currentskinframe->glow));
998         if (r_glsl_permutation->loc_GlowScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_GlowScale, r_hdr_glowintensity.value);
999         if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_view.colorscale);
1000         if (r_glsl_permutation->loc_FogColor >= 0)
1001         {
1002                 // additive passes are only darkened by fog, not tinted
1003                 if (r_shadow_rtlight || (rsurface_texture->currentmaterialflags & MATERIALFLAG_ADD))
1004                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
1005                 else
1006                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
1007         }
1008         if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface_modelorg[0], rsurface_modelorg[1], rsurface_modelorg[2]);
1009         if (r_glsl_permutation->loc_Color_Pants >= 0)
1010         {
1011                 if (rsurface_texture->currentskinframe->pants)
1012                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface_entity->colormap_pantscolor[0], rsurface_entity->colormap_pantscolor[1], rsurface_entity->colormap_pantscolor[2]);
1013                 else
1014                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
1015         }
1016         if (r_glsl_permutation->loc_Color_Shirt >= 0)
1017         {
1018                 if (rsurface_texture->currentskinframe->shirt)
1019                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface_entity->colormap_shirtcolor[0], rsurface_entity->colormap_shirtcolor[1], rsurface_entity->colormap_shirtcolor[2]);
1020                 else
1021                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
1022         }
1023         if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, r_refdef.fograngerecip);
1024         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface_texture->specularpower);
1025         if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
1026         CHECKGLERROR
1027         return permutation;
1028 }
1029
1030 void R_SwitchSurfaceShader(int permutation)
1031 {
1032         if (r_glsl_permutation != r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK))
1033         {
1034                 r_glsl_permutation = r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK);
1035                 CHECKGLERROR
1036                 qglUseProgramObjectARB(r_glsl_permutation->program);
1037                 CHECKGLERROR
1038         }
1039 }
1040
1041 #define SKINFRAME_HASH 1024
1042
1043 struct
1044 {
1045         int loadsequence; // incremented each level change
1046         memexpandablearray_t array;
1047         skinframe_t *hash[SKINFRAME_HASH];
1048 }
1049 r_skinframe;
1050
1051 void R_SkinFrame_PrepareForPurge(void)
1052 {
1053         r_skinframe.loadsequence++;
1054         // wrap it without hitting zero
1055         if (r_skinframe.loadsequence >= 200)
1056                 r_skinframe.loadsequence = 1;
1057 }
1058
1059 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
1060 {
1061         if (!skinframe)
1062                 return;
1063         // mark the skinframe as used for the purging code
1064         skinframe->loadsequence = r_skinframe.loadsequence;
1065 }
1066
1067 void R_SkinFrame_Purge(void)
1068 {
1069         int i;
1070         skinframe_t *s;
1071         for (i = 0;i < SKINFRAME_HASH;i++)
1072         {
1073                 for (s = r_skinframe.hash[i];s;s = s->next)
1074                 {
1075                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
1076                         {
1077                                 if (s->base == r_texture_notexture)     s->base   = NULL;
1078                                 if (s->nmap == r_texture_blanknormalmap)s->nmap   = NULL;
1079                                 if (s->merged == s->base)               s->merged = NULL;
1080                                 if (s->stain ) R_FreeTexture(s->stain );s->stain  = NULL;
1081                                 if (s->merged) R_FreeTexture(s->merged);s->merged = NULL;
1082                                 if (s->base  ) R_FreeTexture(s->base  );s->base   = NULL;
1083                                 if (s->pants ) R_FreeTexture(s->pants );s->pants  = NULL;
1084                                 if (s->shirt ) R_FreeTexture(s->shirt );s->shirt  = NULL;
1085                                 if (s->nmap  ) R_FreeTexture(s->nmap  );s->nmap   = NULL;
1086                                 if (s->gloss ) R_FreeTexture(s->gloss );s->gloss  = NULL;
1087                                 if (s->glow  ) R_FreeTexture(s->glow  );s->glow   = NULL;
1088                                 if (s->fog   ) R_FreeTexture(s->fog   );s->fog    = NULL;
1089                                 s->loadsequence = 0;
1090                         }
1091                 }
1092         }
1093 }
1094
1095 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
1096 {
1097         skinframe_t *item;
1098         int hashindex;
1099         char basename[MAX_QPATH];
1100
1101         Image_StripImageExtension(name, basename, sizeof(basename));
1102
1103         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
1104         for (item = r_skinframe.hash[hashindex];item;item = item->next)
1105                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
1106                         break;
1107         if (!item)
1108         {
1109                 if (!add)
1110                         return NULL;
1111                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
1112                 memset(item, 0, sizeof(*item));
1113                 strlcpy(item->basename, basename, sizeof(item->basename));
1114                 item->textureflags = textureflags;
1115                 item->comparewidth = comparewidth;
1116                 item->compareheight = compareheight;
1117                 item->comparecrc = comparecrc;
1118                 item->next = r_skinframe.hash[hashindex];
1119                 r_skinframe.hash[hashindex] = item;
1120         }
1121         R_SkinFrame_MarkUsed(item);
1122         return item;
1123 }
1124
1125 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
1126 {
1127         // FIXME: it should be possible to disable loading various layers using
1128         // cvars, to prevent wasted loading time and memory usage if the user does
1129         // not want them
1130         qboolean loadnormalmap = true;
1131         qboolean loadgloss = true;
1132         qboolean loadpantsandshirt = true;
1133         qboolean loadglow = true;
1134         int j;
1135         unsigned char *pixels;
1136         unsigned char *bumppixels;
1137         unsigned char *basepixels = NULL;
1138         int basepixels_width;
1139         int basepixels_height;
1140         skinframe_t *skinframe;
1141
1142         if (cls.state == ca_dedicated)
1143                 return NULL;
1144
1145         // return an existing skinframe if already loaded
1146         // if loading of the first image fails, don't make a new skinframe as it
1147         // would cause all future lookups of this to be missing
1148         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
1149         if (skinframe && skinframe->base)
1150                 return skinframe;
1151
1152         basepixels = loadimagepixels(name, complain, 0, 0);
1153         if (basepixels == NULL)
1154                 return NULL;
1155
1156         // we've got some pixels to store, so really allocate this new texture now
1157         if (!skinframe)
1158                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
1159         skinframe->stain = NULL;
1160         skinframe->merged = NULL;
1161         skinframe->base = r_texture_notexture;
1162         skinframe->pants = NULL;
1163         skinframe->shirt = NULL;
1164         skinframe->nmap = r_texture_blanknormalmap;
1165         skinframe->gloss = NULL;
1166         skinframe->glow = NULL;
1167         skinframe->fog = NULL;
1168
1169         basepixels_width = image_width;
1170         basepixels_height = image_height;
1171         skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1172
1173         if (textureflags & TEXF_ALPHA)
1174         {
1175                 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
1176                         if (basepixels[j] < 255)
1177                                 break;
1178                 if (j < basepixels_width * basepixels_height * 4)
1179                 {
1180                         // has transparent pixels
1181                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1182                         for (j = 0;j < image_width * image_height * 4;j += 4)
1183                         {
1184                                 pixels[j+0] = 255;
1185                                 pixels[j+1] = 255;
1186                                 pixels[j+2] = 255;
1187                                 pixels[j+3] = basepixels[j+3];
1188                         }
1189                         skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1190                         Mem_Free(pixels);
1191                 }
1192         }
1193
1194         // _norm is the name used by tenebrae and has been adopted as standard
1195         if (loadnormalmap)
1196         {
1197                 if ((pixels = loadimagepixels(va("%s_norm", skinframe->basename), false, 0, 0)) != NULL)
1198                 {
1199                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1200                         Mem_Free(pixels);
1201                         pixels = NULL;
1202                 }
1203                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixels(va("%s_bump", skinframe->basename), false, 0, 0)) != NULL)
1204                 {
1205                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1206                         Image_HeightmapToNormalmap(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
1207                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1208                         Mem_Free(pixels);
1209                         Mem_Free(bumppixels);
1210                 }
1211                 else if (r_shadow_bumpscale_basetexture.value > 0)
1212                 {
1213                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
1214                         Image_HeightmapToNormalmap(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
1215                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1216                         Mem_Free(pixels);
1217                 }
1218         }
1219         // _luma is supported for tenebrae compatibility
1220         // (I think it's a very stupid name, but oh well)
1221         // _glow is the preferred name
1222         if (loadglow          && ((pixels = loadimagepixels(va("%s_glow", skinframe->basename), false, 0, 0)) != NULL || (pixels = loadimagepixels(va("%s_luma", skinframe->basename), false, 0, 0)) != NULL)) {skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);Mem_Free(pixels);pixels = NULL;}
1223         if (loadgloss         && (pixels = loadimagepixels(va("%s_gloss", skinframe->basename), false, 0, 0)) != NULL) {skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);Mem_Free(pixels);pixels = NULL;}
1224         if (loadpantsandshirt && (pixels = loadimagepixels(va("%s_pants", skinframe->basename), false, 0, 0)) != NULL) {skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);Mem_Free(pixels);pixels = NULL;}
1225         if (loadpantsandshirt && (pixels = loadimagepixels(va("%s_shirt", skinframe->basename), false, 0, 0)) != NULL) {skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);Mem_Free(pixels);pixels = NULL;}
1226
1227         if (basepixels)
1228                 Mem_Free(basepixels);
1229
1230         return skinframe;
1231 }
1232
1233 static rtexture_t *R_SkinFrame_TextureForSkinLayer(const unsigned char *in, int width, int height, const char *name, const unsigned int *palette, int textureflags, qboolean force)
1234 {
1235         int i;
1236         if (!force)
1237         {
1238                 for (i = 0;i < width*height;i++)
1239                         if (((unsigned char *)&palette[in[i]])[3] > 0)
1240                                 break;
1241                 if (i == width*height)
1242                         return NULL;
1243         }
1244         return R_LoadTexture2D (r_main_texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
1245 }
1246
1247 skinframe_t *R_SkinFrame_LoadInternal(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height, int bitsperpixel, const unsigned int *palette, const unsigned int *alphapalette)
1248 {
1249         int i;
1250         unsigned char *temp1, *temp2;
1251         skinframe_t *skinframe;
1252
1253         if (cls.state == ca_dedicated)
1254                 return NULL;
1255
1256         // if already loaded just return it, otherwise make a new skinframe
1257         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*bitsperpixel/8) : 0, true);
1258         if (skinframe && skinframe->base)
1259                 return skinframe;
1260
1261         skinframe->stain = NULL;
1262         skinframe->merged = NULL;
1263         skinframe->base = r_texture_notexture;
1264         skinframe->pants = NULL;
1265         skinframe->shirt = NULL;
1266         skinframe->nmap = r_texture_blanknormalmap;
1267         skinframe->gloss = NULL;
1268         skinframe->glow = NULL;
1269         skinframe->fog = NULL;
1270
1271         // if no data was provided, then clearly the caller wanted to get a blank skinframe
1272         if (!skindata)
1273                 return NULL;
1274
1275         if (bitsperpixel == 32)
1276         {
1277                 if (r_shadow_bumpscale_basetexture.value > 0)
1278                 {
1279                         temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1280                         temp2 = temp1 + width * height * 4;
1281                         Image_HeightmapToNormalmap(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1282                         skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_RGBA, textureflags | TEXF_ALPHA, NULL);
1283                         Mem_Free(temp1);
1284                 }
1285                 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_RGBA, textureflags, NULL);
1286                 if (textureflags & TEXF_ALPHA)
1287                 {
1288                         for (i = 3;i < width * height * 4;i += 4)
1289                                 if (skindata[i] < 255)
1290                                         break;
1291                         if (i < width * height * 4)
1292                         {
1293                                 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
1294                                 memcpy(fogpixels, skindata, width * height * 4);
1295                                 for (i = 0;i < width * height * 4;i += 4)
1296                                         fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
1297                                 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_RGBA, textureflags, NULL);
1298                                 Mem_Free(fogpixels);
1299                         }
1300                 }
1301         }
1302         else if (bitsperpixel == 8)
1303         {
1304                 if (r_shadow_bumpscale_basetexture.value > 0)
1305                 {
1306                         temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1307                         temp2 = temp1 + width * height * 4;
1308                         if (bitsperpixel == 32)
1309                                 Image_HeightmapToNormalmap(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1310                         else
1311                         {
1312                                 // use either a custom palette or the quake palette
1313                                 Image_Copy8bitRGBA(skindata, temp1, width * height, palette ? palette : palette_complete);
1314                                 Image_HeightmapToNormalmap(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1315                         }
1316                         skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_RGBA, textureflags | TEXF_ALPHA, NULL);
1317                         Mem_Free(temp1);
1318                 }
1319                 // use either a custom palette, or the quake palette
1320                 skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_merged", skinframe->basename), palette ? palette : (loadglowtexture ? palette_nofullbrights : ((textureflags & TEXF_ALPHA) ? palette_transparent : palette_complete)), textureflags, true); // all
1321                 if (!palette && loadglowtexture)
1322                         skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_onlyfullbrights, textureflags, false); // glow
1323                 if (!palette && loadpantsandshirt)
1324                 {
1325                         skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_pantsaswhite, textureflags, false); // pants
1326                         skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_shirtaswhite, textureflags, false); // shirt
1327                 }
1328                 if (skinframe->pants || skinframe->shirt)
1329                         skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename),loadglowtexture ? palette_nocolormapnofullbrights : palette_nocolormap, textureflags, false); // no special colors
1330                 if (textureflags & TEXF_ALPHA)
1331                 {
1332                         // if not using a custom alphapalette, use the quake one
1333                         if (!alphapalette)
1334                                 alphapalette = palette_alpha;
1335                         for (i = 0;i < width * height;i++)
1336                                 if (((unsigned char *)alphapalette)[skindata[i]*4+3] < 255)
1337                                         break;
1338                         if (i < width * height)
1339                                 skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), alphapalette, textureflags, true); // fog mask
1340                 }
1341         }
1342
1343         return skinframe;
1344 }
1345
1346 skinframe_t *R_SkinFrame_LoadMissing(void)
1347 {
1348         skinframe_t *skinframe;
1349
1350         if (cls.state == ca_dedicated)
1351                 return NULL;
1352
1353         skinframe = R_SkinFrame_Find("missing", TEXF_PRECACHE, 0, 0, 0, true);
1354         skinframe->stain = NULL;
1355         skinframe->merged = NULL;
1356         skinframe->base = r_texture_notexture;
1357         skinframe->pants = NULL;
1358         skinframe->shirt = NULL;
1359         skinframe->nmap = r_texture_blanknormalmap;
1360         skinframe->gloss = NULL;
1361         skinframe->glow = NULL;
1362         skinframe->fog = NULL;
1363
1364         return skinframe;
1365 }
1366
1367 void gl_main_start(void)
1368 {
1369         int x;
1370         double r, alpha;
1371
1372         r = (-1.0/256.0) * (FOGMASKTABLEWIDTH * FOGMASKTABLEWIDTH);
1373         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
1374         {
1375                 alpha = 1 - exp(r / ((double)x*(double)x));
1376                 if (x == FOGMASKTABLEWIDTH - 1)
1377                         alpha = 0;
1378                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
1379         }
1380
1381         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1382         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1383
1384         // set up r_skinframe loading system for textures
1385         memset(&r_skinframe, 0, sizeof(r_skinframe));
1386         r_skinframe.loadsequence = 1;
1387         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
1388
1389         r_main_texturepool = R_AllocTexturePool();
1390         R_BuildBlankTextures();
1391         R_BuildNoTexture();
1392         if (gl_texturecubemap)
1393         {
1394                 R_BuildWhiteCube();
1395                 R_BuildNormalizationCube();
1396         }
1397         R_BuildFogTexture();
1398         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1399         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
1400         memset(&r_svbsp, 0, sizeof (r_svbsp));
1401 }
1402
1403 void gl_main_shutdown(void)
1404 {
1405         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1406         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1407
1408         // clear out the r_skinframe state
1409         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
1410         memset(&r_skinframe, 0, sizeof(r_skinframe));
1411
1412         if (r_svbsp.nodes)
1413                 Mem_Free(r_svbsp.nodes);
1414         memset(&r_svbsp, 0, sizeof (r_svbsp));
1415         R_FreeTexturePool(&r_main_texturepool);
1416         r_texture_blanknormalmap = NULL;
1417         r_texture_white = NULL;
1418         r_texture_black = NULL;
1419         r_texture_whitecube = NULL;
1420         r_texture_normalizationcube = NULL;
1421         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1422         R_GLSL_Restart_f();
1423 }
1424
1425 extern void CL_ParseEntityLump(char *entitystring);
1426 void gl_main_newmap(void)
1427 {
1428         // FIXME: move this code to client
1429         int l;
1430         char *entities, entname[MAX_QPATH];
1431         if (cl.worldmodel)
1432         {
1433                 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
1434                 l = (int)strlen(entname) - 4;
1435                 if (l >= 0 && !strcmp(entname + l, ".bsp"))
1436                 {
1437                         memcpy(entname + l, ".ent", 5);
1438                         if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
1439                         {
1440                                 CL_ParseEntityLump(entities);
1441                                 Mem_Free(entities);
1442                                 return;
1443                         }
1444                 }
1445                 if (cl.worldmodel->brush.entities)
1446                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
1447         }
1448 }
1449
1450 void GL_Main_Init(void)
1451 {
1452         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
1453
1454         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
1455         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
1456         if (gamemode == GAME_NEHAHRA)
1457         {
1458                 Cvar_RegisterVariable (&gl_fogenable);
1459                 Cvar_RegisterVariable (&gl_fogdensity);
1460                 Cvar_RegisterVariable (&gl_fogred);
1461                 Cvar_RegisterVariable (&gl_foggreen);
1462                 Cvar_RegisterVariable (&gl_fogblue);
1463                 Cvar_RegisterVariable (&gl_fogstart);
1464                 Cvar_RegisterVariable (&gl_fogend);
1465         }
1466         Cvar_RegisterVariable(&r_nearclip);
1467         Cvar_RegisterVariable(&r_showbboxes);
1468         Cvar_RegisterVariable(&r_showsurfaces);
1469         Cvar_RegisterVariable(&r_showtris);
1470         Cvar_RegisterVariable(&r_shownormals);
1471         Cvar_RegisterVariable(&r_showlighting);
1472         Cvar_RegisterVariable(&r_showshadowvolumes);
1473         Cvar_RegisterVariable(&r_showcollisionbrushes);
1474         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
1475         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
1476         Cvar_RegisterVariable(&r_showdisabledepthtest);
1477         Cvar_RegisterVariable(&r_drawportals);
1478         Cvar_RegisterVariable(&r_drawentities);
1479         Cvar_RegisterVariable(&r_cullentities_trace);
1480         Cvar_RegisterVariable(&r_cullentities_trace_samples);
1481         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
1482         Cvar_RegisterVariable(&r_cullentities_trace_delay);
1483         Cvar_RegisterVariable(&r_drawviewmodel);
1484         Cvar_RegisterVariable(&r_speeds);
1485         Cvar_RegisterVariable(&r_fullbrights);
1486         Cvar_RegisterVariable(&r_wateralpha);
1487         Cvar_RegisterVariable(&r_dynamic);
1488         Cvar_RegisterVariable(&r_fullbright);
1489         Cvar_RegisterVariable(&r_shadows);
1490         Cvar_RegisterVariable(&r_shadows_throwdistance);
1491         Cvar_RegisterVariable(&r_q1bsp_skymasking);
1492         Cvar_RegisterVariable(&r_textureunits);
1493         Cvar_RegisterVariable(&r_glsl);
1494         Cvar_RegisterVariable(&r_glsl_offsetmapping);
1495         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
1496         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
1497         Cvar_RegisterVariable(&r_glsl_deluxemapping);
1498         Cvar_RegisterVariable(&r_lerpsprites);
1499         Cvar_RegisterVariable(&r_lerpmodels);
1500         Cvar_RegisterVariable(&r_waterscroll);
1501         Cvar_RegisterVariable(&r_bloom);
1502         Cvar_RegisterVariable(&r_bloom_colorscale);
1503         Cvar_RegisterVariable(&r_bloom_brighten);
1504         Cvar_RegisterVariable(&r_bloom_blur);
1505         Cvar_RegisterVariable(&r_bloom_resolution);
1506         Cvar_RegisterVariable(&r_bloom_colorexponent);
1507         Cvar_RegisterVariable(&r_bloom_colorsubtract);
1508         Cvar_RegisterVariable(&r_hdr);
1509         Cvar_RegisterVariable(&r_hdr_scenebrightness);
1510         Cvar_RegisterVariable(&r_hdr_glowintensity);
1511         Cvar_RegisterVariable(&r_hdr_range);
1512         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
1513         Cvar_RegisterVariable(&developer_texturelogging);
1514         Cvar_RegisterVariable(&gl_lightmaps);
1515         Cvar_RegisterVariable(&r_test);
1516         Cvar_RegisterVariable(&r_batchmode);
1517         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
1518                 Cvar_SetValue("r_fullbrights", 0);
1519         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
1520 }
1521
1522 extern void R_Textures_Init(void);
1523 extern void GL_Draw_Init(void);
1524 extern void GL_Main_Init(void);
1525 extern void R_Shadow_Init(void);
1526 extern void R_Sky_Init(void);
1527 extern void GL_Surf_Init(void);
1528 extern void R_Light_Init(void);
1529 extern void R_Particles_Init(void);
1530 extern void R_Explosion_Init(void);
1531 extern void gl_backend_init(void);
1532 extern void Sbar_Init(void);
1533 extern void R_LightningBeams_Init(void);
1534 extern void Mod_RenderInit(void);
1535
1536 void Render_Init(void)
1537 {
1538         gl_backend_init();
1539         R_Textures_Init();
1540         GL_Main_Init();
1541         GL_Draw_Init();
1542         R_Shadow_Init();
1543         R_Sky_Init();
1544         GL_Surf_Init();
1545         Sbar_Init();
1546         R_Light_Init();
1547         R_Particles_Init();
1548         R_Explosion_Init();
1549         R_LightningBeams_Init();
1550         Mod_RenderInit();
1551 }
1552
1553 /*
1554 ===============
1555 GL_Init
1556 ===============
1557 */
1558 extern char *ENGINE_EXTENSIONS;
1559 void GL_Init (void)
1560 {
1561         VID_CheckExtensions();
1562
1563         // LordHavoc: report supported extensions
1564         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1565
1566         // clear to black (loading plaque will be seen over this)
1567         CHECKGLERROR
1568         qglClearColor(0,0,0,1);CHECKGLERROR
1569         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
1570 }
1571
1572 int R_CullBox(const vec3_t mins, const vec3_t maxs)
1573 {
1574         int i;
1575         mplane_t *p;
1576         for (i = 0;i < 4;i++)
1577         {
1578                 p = r_view.frustum + i;
1579                 switch(p->signbits)
1580                 {
1581                 default:
1582                 case 0:
1583                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1584                                 return true;
1585                         break;
1586                 case 1:
1587                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1588                                 return true;
1589                         break;
1590                 case 2:
1591                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1592                                 return true;
1593                         break;
1594                 case 3:
1595                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1596                                 return true;
1597                         break;
1598                 case 4:
1599                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1600                                 return true;
1601                         break;
1602                 case 5:
1603                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1604                                 return true;
1605                         break;
1606                 case 6:
1607                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1608                                 return true;
1609                         break;
1610                 case 7:
1611                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1612                                 return true;
1613                         break;
1614                 }
1615         }
1616         return false;
1617 }
1618
1619 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
1620 {
1621         int i;
1622         const mplane_t *p;
1623         for (i = 0;i < numplanes;i++)
1624         {
1625                 p = planes + i;
1626                 switch(p->signbits)
1627                 {
1628                 default:
1629                 case 0:
1630                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1631                                 return true;
1632                         break;
1633                 case 1:
1634                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1635                                 return true;
1636                         break;
1637                 case 2:
1638                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1639                                 return true;
1640                         break;
1641                 case 3:
1642                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1643                                 return true;
1644                         break;
1645                 case 4:
1646                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1647                                 return true;
1648                         break;
1649                 case 5:
1650                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1651                                 return true;
1652                         break;
1653                 case 6:
1654                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1655                                 return true;
1656                         break;
1657                 case 7:
1658                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1659                                 return true;
1660                         break;
1661                 }
1662         }
1663         return false;
1664 }
1665
1666 //==================================================================================
1667
1668 static void R_UpdateEntityLighting(entity_render_t *ent)
1669 {
1670         vec3_t tempdiffusenormal;
1671
1672         // fetch the lighting from the worldmodel data
1673         VectorSet(ent->modellight_ambient, r_ambient.value * (2.0f / 128.0f), r_ambient.value * (2.0f / 128.0f), r_ambient.value * (2.0f / 128.0f));
1674         VectorClear(ent->modellight_diffuse);
1675         VectorClear(tempdiffusenormal);
1676         if ((ent->flags & RENDER_LIGHT) && r_refdef.worldmodel && r_refdef.worldmodel->brush.LightPoint)
1677         {
1678                 vec3_t org;
1679                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
1680                 r_refdef.worldmodel->brush.LightPoint(r_refdef.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
1681         }
1682         else // highly rare
1683                 VectorSet(ent->modellight_ambient, 1, 1, 1);
1684
1685         // move the light direction into modelspace coordinates for lighting code
1686         Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
1687         VectorNormalize(ent->modellight_lightdir);
1688
1689         // scale ambient and directional light contributions according to rendering variables
1690         ent->modellight_ambient[0] *= ent->colormod[0] * r_refdef.lightmapintensity;
1691         ent->modellight_ambient[1] *= ent->colormod[1] * r_refdef.lightmapintensity;
1692         ent->modellight_ambient[2] *= ent->colormod[2] * r_refdef.lightmapintensity;
1693         ent->modellight_diffuse[0] *= ent->colormod[0] * r_refdef.lightmapintensity;
1694         ent->modellight_diffuse[1] *= ent->colormod[1] * r_refdef.lightmapintensity;
1695         ent->modellight_diffuse[2] *= ent->colormod[2] * r_refdef.lightmapintensity;
1696 }
1697
1698 static void R_View_UpdateEntityVisible (void)
1699 {
1700         int i, renderimask;
1701         entity_render_t *ent;
1702
1703         if (!r_drawentities.integer)
1704                 return;
1705
1706         renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL) : (chase_active.integer ? 0 : RENDER_EXTERIORMODEL);
1707         if (r_refdef.worldmodel && r_refdef.worldmodel->brush.BoxTouchingVisibleLeafs)
1708         {
1709                 // worldmodel can check visibility
1710                 for (i = 0;i < r_refdef.numentities;i++)
1711                 {
1712                         ent = r_refdef.entities[i];
1713                         r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && !R_CullBox(ent->mins, ent->maxs) && ((ent->effects & EF_NODEPTHTEST) || (ent->flags & RENDER_VIEWMODEL) || r_refdef.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.worldmodel, r_viewcache.world_leafvisible, ent->mins, ent->maxs));
1714                 }
1715                 if(r_cullentities_trace.integer)
1716                 {
1717                         for (i = 0;i < r_refdef.numentities;i++)
1718                         {
1719                                 ent = r_refdef.entities[i];
1720                                 if(r_viewcache.entityvisible[i] && !(ent->effects & EF_NODEPTHTEST) && !(ent->flags & RENDER_VIEWMODEL) && !(ent->model && (ent->model->name[0] == '*')))
1721                                 {
1722                                         if(Mod_CanSeeBox_Trace(r_cullentities_trace_samples.integer, r_cullentities_trace_enlarge.value, r_refdef.worldmodel, r_view.origin, ent->mins, ent->maxs))
1723                                                 ent->last_trace_visibility = realtime;
1724                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
1725                                                 r_viewcache.entityvisible[i] = 0;
1726                                 }
1727                         }
1728                 }
1729         }
1730         else
1731         {
1732                 // no worldmodel or it can't check visibility
1733                 for (i = 0;i < r_refdef.numentities;i++)
1734                 {
1735                         ent = r_refdef.entities[i];
1736                         r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && !R_CullBox(ent->mins, ent->maxs);
1737                 }
1738         }
1739
1740         // update entity lighting (even on hidden entities for r_shadows)
1741         for (i = 0;i < r_refdef.numentities;i++)
1742                 R_UpdateEntityLighting(r_refdef.entities[i]);
1743 }
1744
1745 // only used if skyrendermasked, and normally returns false
1746 int R_DrawBrushModelsSky (void)
1747 {
1748         int i, sky;
1749         entity_render_t *ent;
1750
1751         if (!r_drawentities.integer)
1752                 return false;
1753
1754         sky = false;
1755         for (i = 0;i < r_refdef.numentities;i++)
1756         {
1757                 if (!r_viewcache.entityvisible[i])
1758                         continue;
1759                 ent = r_refdef.entities[i];
1760                 if (!ent->model || !ent->model->DrawSky)
1761                         continue;
1762                 ent->model->DrawSky(ent);
1763                 sky = true;
1764         }
1765         return sky;
1766 }
1767
1768 void R_DrawNoModel(entity_render_t *ent);
1769 void R_DrawModels(void)
1770 {
1771         int i;
1772         entity_render_t *ent;
1773
1774         if (!r_drawentities.integer)
1775                 return;
1776
1777         for (i = 0;i < r_refdef.numentities;i++)
1778         {
1779                 if (!r_viewcache.entityvisible[i])
1780                         continue;
1781                 ent = r_refdef.entities[i];
1782                 r_refdef.stats.entities++;
1783                 if (ent->model && ent->model->Draw != NULL)
1784                         ent->model->Draw(ent);
1785                 else
1786                         R_DrawNoModel(ent);
1787         }
1788 }
1789
1790 static void R_View_SetFrustum(void)
1791 {
1792         double slopex, slopey;
1793
1794         // break apart the view matrix into vectors for various purposes
1795         Matrix4x4_ToVectors(&r_view.matrix, r_view.forward, r_view.left, r_view.up, r_view.origin);
1796         VectorNegate(r_view.left, r_view.right);
1797
1798 #if 0
1799         r_view.frustum[0].normal[0] = 0 - 1.0 / r_view.frustum_x;
1800         r_view.frustum[0].normal[1] = 0 - 0;
1801         r_view.frustum[0].normal[2] = -1 - 0;
1802         r_view.frustum[1].normal[0] = 0 + 1.0 / r_view.frustum_x;
1803         r_view.frustum[1].normal[1] = 0 + 0;
1804         r_view.frustum[1].normal[2] = -1 + 0;
1805         r_view.frustum[2].normal[0] = 0 - 0;
1806         r_view.frustum[2].normal[1] = 0 - 1.0 / r_view.frustum_y;
1807         r_view.frustum[2].normal[2] = -1 - 0;
1808         r_view.frustum[3].normal[0] = 0 + 0;
1809         r_view.frustum[3].normal[1] = 0 + 1.0 / r_view.frustum_y;
1810         r_view.frustum[3].normal[2] = -1 + 0;
1811 #endif
1812
1813 #if 0
1814         zNear = r_refdef.nearclip;
1815         nudge = 1.0 - 1.0 / (1<<23);
1816         r_view.frustum[4].normal[0] = 0 - 0;
1817         r_view.frustum[4].normal[1] = 0 - 0;
1818         r_view.frustum[4].normal[2] = -1 - -nudge;
1819         r_view.frustum[4].dist = 0 - -2 * zNear * nudge;
1820         r_view.frustum[5].normal[0] = 0 + 0;
1821         r_view.frustum[5].normal[1] = 0 + 0;
1822         r_view.frustum[5].normal[2] = -1 + -nudge;
1823         r_view.frustum[5].dist = 0 + -2 * zNear * nudge;
1824 #endif
1825
1826
1827
1828 #if 0
1829         r_view.frustum[0].normal[0] = m[3] - m[0];
1830         r_view.frustum[0].normal[1] = m[7] - m[4];
1831         r_view.frustum[0].normal[2] = m[11] - m[8];
1832         r_view.frustum[0].dist = m[15] - m[12];
1833
1834         r_view.frustum[1].normal[0] = m[3] + m[0];
1835         r_view.frustum[1].normal[1] = m[7] + m[4];
1836         r_view.frustum[1].normal[2] = m[11] + m[8];
1837         r_view.frustum[1].dist = m[15] + m[12];
1838
1839         r_view.frustum[2].normal[0] = m[3] - m[1];
1840         r_view.frustum[2].normal[1] = m[7] - m[5];
1841         r_view.frustum[2].normal[2] = m[11] - m[9];
1842         r_view.frustum[2].dist = m[15] - m[13];
1843
1844         r_view.frustum[3].normal[0] = m[3] + m[1];
1845         r_view.frustum[3].normal[1] = m[7] + m[5];
1846         r_view.frustum[3].normal[2] = m[11] + m[9];
1847         r_view.frustum[3].dist = m[15] + m[13];
1848
1849         r_view.frustum[4].normal[0] = m[3] - m[2];
1850         r_view.frustum[4].normal[1] = m[7] - m[6];
1851         r_view.frustum[4].normal[2] = m[11] - m[10];
1852         r_view.frustum[4].dist = m[15] - m[14];
1853
1854         r_view.frustum[5].normal[0] = m[3] + m[2];
1855         r_view.frustum[5].normal[1] = m[7] + m[6];
1856         r_view.frustum[5].normal[2] = m[11] + m[10];
1857         r_view.frustum[5].dist = m[15] + m[14];
1858 #endif
1859
1860
1861
1862         slopex = 1.0 / r_view.frustum_x;
1863         slopey = 1.0 / r_view.frustum_y;
1864         VectorMA(r_view.forward, -slopex, r_view.left, r_view.frustum[0].normal);
1865         VectorMA(r_view.forward,  slopex, r_view.left, r_view.frustum[1].normal);
1866         VectorMA(r_view.forward, -slopey, r_view.up  , r_view.frustum[2].normal);
1867         VectorMA(r_view.forward,  slopey, r_view.up  , r_view.frustum[3].normal);
1868         VectorCopy(r_view.forward, r_view.frustum[4].normal);
1869         VectorNormalize(r_view.frustum[0].normal);
1870         VectorNormalize(r_view.frustum[1].normal);
1871         VectorNormalize(r_view.frustum[2].normal);
1872         VectorNormalize(r_view.frustum[3].normal);
1873         r_view.frustum[0].dist = DotProduct (r_view.origin, r_view.frustum[0].normal);
1874         r_view.frustum[1].dist = DotProduct (r_view.origin, r_view.frustum[1].normal);
1875         r_view.frustum[2].dist = DotProduct (r_view.origin, r_view.frustum[2].normal);
1876         r_view.frustum[3].dist = DotProduct (r_view.origin, r_view.frustum[3].normal);
1877         r_view.frustum[4].dist = DotProduct (r_view.origin, r_view.frustum[4].normal) + r_refdef.nearclip;
1878         PlaneClassify(&r_view.frustum[0]);
1879         PlaneClassify(&r_view.frustum[1]);
1880         PlaneClassify(&r_view.frustum[2]);
1881         PlaneClassify(&r_view.frustum[3]);
1882         PlaneClassify(&r_view.frustum[4]);
1883
1884         // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
1885         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward, -1024 * slopex, r_view.left, -1024 * slopey, r_view.up, r_view.frustumcorner[0]);
1886         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward,  1024 * slopex, r_view.left, -1024 * slopey, r_view.up, r_view.frustumcorner[1]);
1887         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward, -1024 * slopex, r_view.left,  1024 * slopey, r_view.up, r_view.frustumcorner[2]);
1888         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward,  1024 * slopex, r_view.left,  1024 * slopey, r_view.up, r_view.frustumcorner[3]);
1889
1890         // LordHavoc: note to all quake engine coders, Quake had a special case
1891         // for 90 degrees which assumed a square view (wrong), so I removed it,
1892         // Quake2 has it disabled as well.
1893
1894         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
1895         //RotatePointAroundVector( r_view.frustum[0].normal, r_view.up, r_view.forward, -(90 - r_refdef.fov_x / 2));
1896         //r_view.frustum[0].dist = DotProduct (r_view.origin, frustum[0].normal);
1897         //PlaneClassify(&frustum[0]);
1898
1899         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
1900         //RotatePointAroundVector( r_view.frustum[1].normal, r_view.up, r_view.forward, (90 - r_refdef.fov_x / 2));
1901         //r_view.frustum[1].dist = DotProduct (r_view.origin, frustum[1].normal);
1902         //PlaneClassify(&frustum[1]);
1903
1904         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
1905         //RotatePointAroundVector( r_view.frustum[2].normal, r_view.left, r_view.forward, -(90 - r_refdef.fov_y / 2));
1906         //r_view.frustum[2].dist = DotProduct (r_view.origin, frustum[2].normal);
1907         //PlaneClassify(&frustum[2]);
1908
1909         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
1910         //RotatePointAroundVector( r_view.frustum[3].normal, r_view.left, r_view.forward, (90 - r_refdef.fov_y / 2));
1911         //r_view.frustum[3].dist = DotProduct (r_view.origin, frustum[3].normal);
1912         //PlaneClassify(&frustum[3]);
1913
1914         // nearclip plane
1915         //VectorCopy(r_view.forward, r_view.frustum[4].normal);
1916         //r_view.frustum[4].dist = DotProduct (r_view.origin, frustum[4].normal) + r_nearclip.value;
1917         //PlaneClassify(&frustum[4]);
1918 }
1919
1920 void R_View_Update(void)
1921 {
1922         R_View_SetFrustum();
1923         R_View_WorldVisibility();
1924         R_View_UpdateEntityVisible();
1925 }
1926
1927 void R_SetupView(const matrix4x4_t *matrix)
1928 {
1929         if (r_refdef.rtworldshadows || r_refdef.rtdlightshadows)
1930                 GL_SetupView_Mode_PerspectiveInfiniteFarClip(r_view.frustum_x, r_view.frustum_y, r_refdef.nearclip);
1931         else
1932                 GL_SetupView_Mode_Perspective(r_view.frustum_x, r_view.frustum_y, r_refdef.nearclip, r_refdef.farclip);
1933
1934         GL_SetupView_Orientation_FromEntity(matrix);
1935 }
1936
1937 void R_ResetViewRendering2D(void)
1938 {
1939         if (gl_support_fragment_shader)
1940         {
1941                 qglUseProgramObjectARB(0);CHECKGLERROR
1942         }
1943
1944         DrawQ_Finish();
1945
1946         // GL is weird because it's bottom to top, r_view.y is top to bottom
1947         qglViewport(r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
1948         GL_SetupView_Mode_Ortho(0, 0, 1, 1, -10, 100);
1949         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1950         GL_Color(1, 1, 1, 1);
1951         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
1952         GL_BlendFunc(GL_ONE, GL_ZERO);
1953         GL_AlphaTest(false);
1954         GL_ScissorTest(false);
1955         GL_DepthMask(false);
1956         GL_DepthRange(0, 1);
1957         GL_DepthTest(false);
1958         R_Mesh_Matrix(&identitymatrix);
1959         R_Mesh_ResetTextureState();
1960         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1961         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
1962         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1963         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1964         qglStencilMask(~0);CHECKGLERROR
1965         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1966         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1967         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
1968 }
1969
1970 void R_ResetViewRendering3D(void)
1971 {
1972         if (gl_support_fragment_shader)
1973         {
1974                 qglUseProgramObjectARB(0);CHECKGLERROR
1975         }
1976
1977         DrawQ_Finish();
1978
1979         // GL is weird because it's bottom to top, r_view.y is top to bottom
1980         qglViewport(r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
1981         R_SetupView(&r_view.matrix);
1982         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1983         GL_Color(1, 1, 1, 1);
1984         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
1985         GL_BlendFunc(GL_ONE, GL_ZERO);
1986         GL_AlphaTest(false);
1987         GL_ScissorTest(true);
1988         GL_DepthMask(true);
1989         GL_DepthRange(0, 1);
1990         GL_DepthTest(true);
1991         R_Mesh_Matrix(&identitymatrix);
1992         R_Mesh_ResetTextureState();
1993         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1994         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
1995         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1996         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1997         qglStencilMask(~0);CHECKGLERROR
1998         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1999         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
2000         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
2001 }
2002
2003 /*
2004         R_Bloom_SetupShader(
2005 "// bloom shader\n"
2006 "// written by Forest 'LordHavoc' Hale\n"
2007 "\n"
2008 "// common definitions between vertex shader and fragment shader:\n"
2009 "\n"
2010 "#ifdef __GLSL_CG_DATA_TYPES\n"
2011 "#define myhalf half\n"
2012 "#define myhvec2 hvec2\n"
2013 "#define myhvec3 hvec3\n"
2014 "#define myhvec4 hvec4\n"
2015 "#else\n"
2016 "#define myhalf float\n"
2017 "#define myhvec2 vec2\n"
2018 "#define myhvec3 vec3\n"
2019 "#define myhvec4 vec4\n"
2020 "#endif\n"
2021 "\n"
2022 "varying vec2 ScreenTexCoord;\n"
2023 "varying vec2 BloomTexCoord;\n"
2024 "\n"
2025 "\n"
2026 "\n"
2027 "\n"
2028 "// vertex shader specific:\n"
2029 "#ifdef VERTEX_SHADER\n"
2030 "\n"
2031 "void main(void)\n"
2032 "{\n"
2033 "       ScreenTexCoord = vec2(gl_MultiTexCoord0);\n"
2034 "       BloomTexCoord = vec2(gl_MultiTexCoord1);\n"
2035 "       // transform vertex to camera space, using ftransform to match non-VS\n"
2036 "       // rendering\n"
2037 "       gl_Position = ftransform();\n"
2038 "}\n"
2039 "\n"
2040 "#endif // VERTEX_SHADER\n"
2041 "\n"
2042 "\n"
2043 "\n"
2044 "\n"
2045 "// fragment shader specific:\n"
2046 "#ifdef FRAGMENT_SHADER\n"
2047 "\n"
2048 "void main(void)\n"
2049 "{\n"
2050 "       int x, y;
2051 "       myhvec3 color = myhvec3(texture2D(Texture_Screen, ScreenTexCoord));\n"
2052 "       for (x = -BLUR_X;x <= BLUR_X;x++)
2053 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2054 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2055 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2056 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2057
2058 "       gl_FragColor = vec4(color);\n"
2059 "}\n"
2060 "\n"
2061 "#endif // FRAGMENT_SHADER\n"
2062 */
2063
2064 void R_RenderScene(void);
2065
2066 void R_Bloom_StartFrame(void)
2067 {
2068         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
2069
2070         // set bloomwidth and bloomheight to the bloom resolution that will be
2071         // used (often less than the screen resolution for faster rendering)
2072         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_view.width);
2073         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_view.height / r_view.width;
2074         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_view.height);
2075
2076         // calculate desired texture sizes
2077         if (gl_support_arb_texture_non_power_of_two)
2078         {
2079                 screentexturewidth = r_view.width;
2080                 screentextureheight = r_view.height;
2081                 bloomtexturewidth = r_bloomstate.bloomwidth;
2082                 bloomtextureheight = r_bloomstate.bloomheight;
2083         }
2084         else
2085         {
2086                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
2087                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
2088                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
2089                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
2090         }
2091
2092         if (r_hdr.integer)
2093         {
2094                 screentexturewidth = screentextureheight = 0;
2095         }
2096         else if (r_bloom.integer)
2097         {
2098         }
2099         else
2100         {
2101                 screentexturewidth = screentextureheight = 0;
2102                 bloomtexturewidth = bloomtextureheight = 0;
2103         }
2104
2105         if ((!bloomtexturewidth && !bloomtextureheight) || r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512 || screentexturewidth > gl_max_texture_size || screentextureheight > gl_max_texture_size || bloomtexturewidth > gl_max_texture_size || bloomtextureheight > gl_max_texture_size)
2106         {
2107                 // can't use bloom if the parameters are too weird
2108                 // can't use bloom if the card does not support the texture size
2109                 if (r_bloomstate.texture_screen)
2110                         R_FreeTexture(r_bloomstate.texture_screen);
2111                 if (r_bloomstate.texture_bloom)
2112                         R_FreeTexture(r_bloomstate.texture_bloom);
2113                 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
2114                 return;
2115         }
2116
2117         r_bloomstate.enabled = true;
2118         r_bloomstate.hdr = r_hdr.integer != 0;
2119
2120         // allocate textures as needed
2121         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
2122         {
2123                 if (r_bloomstate.texture_screen)
2124                         R_FreeTexture(r_bloomstate.texture_screen);
2125                 r_bloomstate.texture_screen = NULL;
2126                 r_bloomstate.screentexturewidth = screentexturewidth;
2127                 r_bloomstate.screentextureheight = screentextureheight;
2128                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
2129                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2130         }
2131         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
2132         {
2133                 if (r_bloomstate.texture_bloom)
2134                         R_FreeTexture(r_bloomstate.texture_bloom);
2135                 r_bloomstate.texture_bloom = NULL;
2136                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
2137                 r_bloomstate.bloomtextureheight = bloomtextureheight;
2138                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
2139                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_RGBA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2140         }
2141
2142         // set up a texcoord array for the full resolution screen image
2143         // (we have to keep this around to copy back during final render)
2144         r_bloomstate.screentexcoord2f[0] = 0;
2145         r_bloomstate.screentexcoord2f[1] = (float)r_view.height / (float)r_bloomstate.screentextureheight;
2146         r_bloomstate.screentexcoord2f[2] = (float)r_view.width / (float)r_bloomstate.screentexturewidth;
2147         r_bloomstate.screentexcoord2f[3] = (float)r_view.height / (float)r_bloomstate.screentextureheight;
2148         r_bloomstate.screentexcoord2f[4] = (float)r_view.width / (float)r_bloomstate.screentexturewidth;
2149         r_bloomstate.screentexcoord2f[5] = 0;
2150         r_bloomstate.screentexcoord2f[6] = 0;
2151         r_bloomstate.screentexcoord2f[7] = 0;
2152
2153         // set up a texcoord array for the reduced resolution bloom image
2154         // (which will be additive blended over the screen image)
2155         r_bloomstate.bloomtexcoord2f[0] = 0;
2156         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2157         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2158         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2159         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2160         r_bloomstate.bloomtexcoord2f[5] = 0;
2161         r_bloomstate.bloomtexcoord2f[6] = 0;
2162         r_bloomstate.bloomtexcoord2f[7] = 0;
2163 }
2164
2165 void R_Bloom_CopyScreenTexture(float colorscale)
2166 {
2167         r_refdef.stats.bloom++;
2168
2169         R_ResetViewRendering2D();
2170         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2171         R_Mesh_ColorPointer(NULL, 0, 0);
2172         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
2173         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
2174
2175         // copy view into the screen texture
2176         GL_ActiveTexture(0);
2177         CHECKGLERROR
2178         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
2179         r_refdef.stats.bloom_copypixels += r_view.width * r_view.height;
2180
2181         // now scale it down to the bloom texture size
2182         CHECKGLERROR
2183         qglViewport(r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2184         GL_BlendFunc(GL_ONE, GL_ZERO);
2185         GL_Color(colorscale, colorscale, colorscale, 1);
2186         // TODO: optimize with multitexture or GLSL
2187         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2188         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2189
2190         // we now have a bloom image in the framebuffer
2191         // copy it into the bloom image texture for later processing
2192         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2193         GL_ActiveTexture(0);
2194         CHECKGLERROR
2195         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2196         r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2197 }
2198
2199 void R_Bloom_CopyHDRTexture(void)
2200 {
2201         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2202         GL_ActiveTexture(0);
2203         CHECKGLERROR
2204         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
2205         r_refdef.stats.bloom_copypixels += r_view.width * r_view.height;
2206 }
2207
2208 void R_Bloom_MakeTexture(void)
2209 {
2210         int x, range, dir;
2211         float xoffset, yoffset, r, brighten;
2212
2213         r_refdef.stats.bloom++;
2214
2215         R_ResetViewRendering2D();
2216         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2217         R_Mesh_ColorPointer(NULL, 0, 0);
2218
2219         // we have a bloom image in the framebuffer
2220         CHECKGLERROR
2221         qglViewport(r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2222
2223         for (x = 1;x < r_bloom_colorexponent.value;)
2224         {
2225                 x *= 2;
2226                 r = bound(0, r_bloom_colorexponent.value / x, 1);
2227                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
2228                 GL_Color(r, r, r, 1);
2229                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2230                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2231                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2232                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2233
2234                 // copy the vertically blurred bloom view to a texture
2235                 GL_ActiveTexture(0);
2236                 CHECKGLERROR
2237                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2238                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2239         }
2240
2241         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
2242         brighten = r_bloom_brighten.value;
2243         if (r_hdr.integer)
2244                 brighten *= r_hdr_range.value;
2245         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2246         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.offsettexcoord2f, 0, 0);
2247
2248         for (dir = 0;dir < 2;dir++)
2249         {
2250                 // blend on at multiple vertical offsets to achieve a vertical blur
2251                 // TODO: do offset blends using GLSL
2252                 GL_BlendFunc(GL_ONE, GL_ZERO);
2253                 for (x = -range;x <= range;x++)
2254                 {
2255                         if (!dir){xoffset = 0;yoffset = x;}
2256                         else {xoffset = x;yoffset = 0;}
2257                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
2258                         yoffset /= (float)r_bloomstate.bloomtextureheight;
2259                         // compute a texcoord array with the specified x and y offset
2260                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
2261                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2262                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2263                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2264                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2265                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
2266                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
2267                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
2268                         // this r value looks like a 'dot' particle, fading sharply to
2269                         // black at the edges
2270                         // (probably not realistic but looks good enough)
2271                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
2272                         //r = (dir ? 1.0f : brighten)/(range*2+1);
2273                         r = (dir ? 1.0f : brighten)/(range*2+1)*(1 - x*x/(float)(range*range));
2274                         GL_Color(r, r, r, 1);
2275                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2276                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2277                         GL_BlendFunc(GL_ONE, GL_ONE);
2278                 }
2279
2280                 // copy the vertically blurred bloom view to a texture
2281                 GL_ActiveTexture(0);
2282                 CHECKGLERROR
2283                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2284                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2285         }
2286
2287         // apply subtract last
2288         // (just like it would be in a GLSL shader)
2289         if (r_bloom_colorsubtract.value > 0 && gl_support_ext_blend_subtract)
2290         {
2291                 GL_BlendFunc(GL_ONE, GL_ZERO);
2292                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2293                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2294                 GL_Color(1, 1, 1, 1);
2295                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2296                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2297
2298                 GL_BlendFunc(GL_ONE, GL_ONE);
2299                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
2300                 R_Mesh_TexBind(0, R_GetTexture(r_texture_white));
2301                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2302                 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
2303                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2304                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2305                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
2306
2307                 // copy the darkened bloom view to a texture
2308                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2309                 GL_ActiveTexture(0);
2310                 CHECKGLERROR
2311                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2312                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2313         }
2314 }
2315
2316 void R_HDR_RenderBloomTexture(void)
2317 {
2318         int oldwidth, oldheight;
2319
2320         oldwidth = r_view.width;
2321         oldheight = r_view.height;
2322         r_view.width = r_bloomstate.bloomwidth;
2323         r_view.height = r_bloomstate.bloomheight;
2324
2325         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
2326         // TODO: add exposure compensation features
2327         // TODO: add fp16 framebuffer support
2328
2329         r_view.colorscale = r_bloom_colorscale.value * r_hdr_scenebrightness.value;
2330         if (r_hdr.integer)
2331                 r_view.colorscale /= r_hdr_range.value;
2332         R_RenderScene();
2333
2334         R_ResetViewRendering2D();
2335
2336         R_Bloom_CopyHDRTexture();
2337         R_Bloom_MakeTexture();
2338
2339         R_ResetViewRendering3D();
2340
2341         R_ClearScreen();
2342         if (r_timereport_active)
2343                 R_TimeReport("clear");
2344
2345
2346         // restore the view settings
2347         r_view.width = oldwidth;
2348         r_view.height = oldheight;
2349 }
2350
2351 static void R_BlendView(void)
2352 {
2353         if (r_bloomstate.enabled && r_bloomstate.hdr)
2354         {
2355                 // render high dynamic range bloom effect
2356                 // the bloom texture was made earlier this render, so we just need to
2357                 // blend it onto the screen...
2358                 R_ResetViewRendering2D();
2359                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2360                 R_Mesh_ColorPointer(NULL, 0, 0);
2361                 GL_Color(1, 1, 1, 1);
2362                 GL_BlendFunc(GL_ONE, GL_ONE);
2363                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2364                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2365                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2366                 r_refdef.stats.bloom_drawpixels += r_view.width * r_view.height;
2367         }
2368         else if (r_bloomstate.enabled)
2369         {
2370                 // render simple bloom effect
2371                 // copy the screen and shrink it and darken it for the bloom process
2372                 R_Bloom_CopyScreenTexture(r_bloom_colorscale.value);
2373                 // make the bloom texture
2374                 R_Bloom_MakeTexture();
2375                 // put the original screen image back in place and blend the bloom
2376                 // texture on it
2377                 R_ResetViewRendering2D();
2378                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2379                 R_Mesh_ColorPointer(NULL, 0, 0);
2380                 GL_Color(1, 1, 1, 1);
2381                 GL_BlendFunc(GL_ONE, GL_ZERO);
2382                 // do both in one pass if possible
2383                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2384                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2385                 if (r_textureunits.integer >= 2 && gl_combine.integer)
2386                 {
2387                         R_Mesh_TexCombine(1, GL_ADD, GL_ADD, 1, 1);
2388                         R_Mesh_TexBind(1, R_GetTexture(r_bloomstate.texture_screen));
2389                         R_Mesh_TexCoordPointer(1, 2, r_bloomstate.screentexcoord2f, 0, 0);
2390                 }
2391                 else
2392                 {
2393                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2394                         r_refdef.stats.bloom_drawpixels += r_view.width * r_view.height;
2395                         // now blend on the bloom texture
2396                         GL_BlendFunc(GL_ONE, GL_ONE);
2397                         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
2398                         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
2399                 }
2400                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2401                 r_refdef.stats.bloom_drawpixels += r_view.width * r_view.height;
2402         }
2403         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
2404         {
2405                 // apply a color tint to the whole view
2406                 R_ResetViewRendering2D();
2407                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2408                 R_Mesh_ColorPointer(NULL, 0, 0);
2409                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2410                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
2411                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2412         }
2413 }
2414
2415 void R_RenderScene(void);
2416
2417 matrix4x4_t r_waterscrollmatrix;
2418
2419 void R_UpdateVariables(void)
2420 {
2421         R_Textures_Frame();
2422
2423         r_refdef.farclip = 4096;
2424         if (r_refdef.worldmodel)
2425                 r_refdef.farclip += VectorDistance(r_refdef.worldmodel->normalmins, r_refdef.worldmodel->normalmaxs);
2426         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
2427
2428         r_refdef.polygonfactor = 0;
2429         r_refdef.polygonoffset = 0;
2430         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_shadow_polygonfactor.value;
2431         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_shadow_polygonoffset.value;
2432
2433         r_refdef.rtworld = r_shadow_realtime_world.integer;
2434         r_refdef.rtworldshadows = r_shadow_realtime_world_shadows.integer && gl_stencil;
2435         r_refdef.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
2436         r_refdef.rtdlightshadows = r_refdef.rtdlight && (r_refdef.rtworld ? r_shadow_realtime_world_dlightshadows.integer : r_shadow_realtime_dlight_shadows.integer) && gl_stencil;
2437         r_refdef.lightmapintensity = r_refdef.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
2438         if (r_showsurfaces.integer)
2439         {
2440                 r_refdef.rtworld = false;
2441                 r_refdef.rtworldshadows = false;
2442                 r_refdef.rtdlight = false;
2443                 r_refdef.rtdlightshadows = false;
2444                 r_refdef.lightmapintensity = 0;
2445         }
2446
2447         if (gamemode == GAME_NEHAHRA)
2448         {
2449                 if (gl_fogenable.integer)
2450                 {
2451                         r_refdef.oldgl_fogenable = true;
2452                         r_refdef.fog_density = gl_fogdensity.value;
2453                         r_refdef.fog_red = gl_fogred.value;
2454                         r_refdef.fog_green = gl_foggreen.value;
2455                         r_refdef.fog_blue = gl_fogblue.value;
2456                 }
2457                 else if (r_refdef.oldgl_fogenable)
2458                 {
2459                         r_refdef.oldgl_fogenable = false;
2460                         r_refdef.fog_density = 0;
2461                         r_refdef.fog_red = 0;
2462                         r_refdef.fog_green = 0;
2463                         r_refdef.fog_blue = 0;
2464                 }
2465         }
2466         if (r_refdef.fog_density)
2467         {
2468                 r_refdef.fogcolor[0] = bound(0.0f, r_refdef.fog_red  , 1.0f);
2469                 r_refdef.fogcolor[1] = bound(0.0f, r_refdef.fog_green, 1.0f);
2470                 r_refdef.fogcolor[2] = bound(0.0f, r_refdef.fog_blue , 1.0f);
2471         }
2472         if (r_refdef.fog_density)
2473         {
2474                 r_refdef.fogenabled = true;
2475                 // this is the point where the fog reaches 0.9986 alpha, which we
2476                 // consider a good enough cutoff point for the texture
2477                 // (0.9986 * 256 == 255.6)
2478                 r_refdef.fogrange = 400 / r_refdef.fog_density;
2479                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
2480                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
2481                 // fog color was already set
2482         }
2483         else
2484                 r_refdef.fogenabled = false;
2485 }
2486
2487 /*
2488 ================
2489 R_RenderView
2490 ================
2491 */
2492 void R_RenderView(void)
2493 {
2494         if (!r_refdef.entities/* || !r_refdef.worldmodel*/)
2495                 return; //Host_Error ("R_RenderView: NULL worldmodel");
2496
2497         R_Shadow_UpdateWorldLightSelection();
2498
2499         CHECKGLERROR
2500         if (r_timereport_active)
2501                 R_TimeReport("setup");
2502
2503         R_View_Update();
2504         if (r_timereport_active)
2505                 R_TimeReport("visibility");
2506
2507         R_ResetViewRendering3D();
2508
2509         R_ClearScreen();
2510         if (r_timereport_active)
2511                 R_TimeReport("clear");
2512
2513         R_Bloom_StartFrame();
2514
2515         // this produces a bloom texture to be used in R_BlendView() later
2516         if (r_hdr.integer)
2517                 R_HDR_RenderBloomTexture();
2518
2519         r_view.colorscale = r_hdr_scenebrightness.value;
2520         R_RenderScene();
2521
2522         R_BlendView();
2523         if (r_timereport_active)
2524                 R_TimeReport("blendview");
2525
2526         GL_Scissor(0, 0, vid.width, vid.height);
2527         GL_ScissorTest(false);
2528         CHECKGLERROR
2529 }
2530
2531 extern void R_DrawLightningBeams (void);
2532 extern void VM_CL_AddPolygonsToMeshQueue (void);
2533 extern void R_DrawPortals (void);
2534 extern cvar_t cl_locs_show;
2535 static void R_DrawLocs(void);
2536 static void R_DrawEntityBBoxes(void);
2537 void R_RenderScene(void)
2538 {
2539         // don't let sound skip if going slow
2540         if (r_refdef.extraupdate)
2541                 S_ExtraUpdate ();
2542
2543         R_ResetViewRendering3D();
2544
2545         R_MeshQueue_BeginScene();
2546
2547         R_SkyStartFrame();
2548
2549         Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.time) * 0.025 * r_waterscroll.value, sin(r_refdef.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
2550
2551         if (cl.csqc_vidvars.drawworld)
2552         {
2553                 // don't let sound skip if going slow
2554                 if (r_refdef.extraupdate)
2555                         S_ExtraUpdate ();
2556
2557                 if (r_refdef.worldmodel && r_refdef.worldmodel->DrawSky)
2558                 {
2559                         r_refdef.worldmodel->DrawSky(r_refdef.worldentity);
2560                         if (r_timereport_active)
2561                                 R_TimeReport("worldsky");
2562                 }
2563
2564                 if (R_DrawBrushModelsSky() && r_timereport_active)
2565                         R_TimeReport("bmodelsky");
2566
2567                 if (r_refdef.worldmodel && r_refdef.worldmodel->Draw)
2568                 {
2569                         r_refdef.worldmodel->Draw(r_refdef.worldentity);
2570                         if (r_timereport_active)
2571                                 R_TimeReport("world");
2572                 }
2573         }
2574
2575         // don't let sound skip if going slow
2576         if (r_refdef.extraupdate)
2577                 S_ExtraUpdate ();
2578
2579         R_DrawModels();
2580         if (r_timereport_active)
2581                 R_TimeReport("models");
2582
2583         // don't let sound skip if going slow
2584         if (r_refdef.extraupdate)
2585                 S_ExtraUpdate ();
2586
2587         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
2588         {
2589                 R_DrawModelShadows();
2590
2591                 R_ResetViewRendering3D();
2592
2593                 // don't let sound skip if going slow
2594                 if (r_refdef.extraupdate)
2595                         S_ExtraUpdate ();
2596         }
2597
2598         R_ShadowVolumeLighting(false);
2599         if (r_timereport_active)
2600                 R_TimeReport("rtlights");
2601
2602         // don't let sound skip if going slow
2603         if (r_refdef.extraupdate)
2604                 S_ExtraUpdate ();
2605
2606         if (cl.csqc_vidvars.drawworld)
2607         {
2608                 R_DrawLightningBeams();
2609                 if (r_timereport_active)
2610                         R_TimeReport("lightning");
2611
2612                 R_DrawParticles();
2613                 if (r_timereport_active)
2614                         R_TimeReport("particles");
2615
2616                 R_DrawExplosions();
2617                 if (r_timereport_active)
2618                         R_TimeReport("explosions");
2619         }
2620
2621         if (gl_support_fragment_shader)
2622         {
2623                 qglUseProgramObjectARB(0);CHECKGLERROR
2624         }
2625         VM_CL_AddPolygonsToMeshQueue();
2626
2627         if (cl_locs_show.integer)
2628         {
2629                 R_DrawLocs();
2630                 if (r_timereport_active)
2631                         R_TimeReport("showlocs");
2632         }
2633
2634         if (r_drawportals.integer)
2635         {
2636                 R_DrawPortals();
2637                 if (r_timereport_active)
2638                         R_TimeReport("portals");
2639         }
2640
2641         if (r_showbboxes.value > 0)
2642         {
2643                 R_DrawEntityBBoxes();
2644                 if (r_timereport_active)
2645                         R_TimeReport("bboxes");
2646         }
2647
2648         if (gl_support_fragment_shader)
2649         {
2650                 qglUseProgramObjectARB(0);CHECKGLERROR
2651         }
2652         R_MeshQueue_RenderTransparent();
2653         if (r_timereport_active)
2654                 R_TimeReport("drawtrans");
2655
2656         if (gl_support_fragment_shader)
2657         {
2658                 qglUseProgramObjectARB(0);CHECKGLERROR
2659         }
2660
2661         if (cl.csqc_vidvars.drawworld)
2662         {
2663                 R_DrawCoronas();
2664                 if (r_timereport_active)
2665                         R_TimeReport("coronas");
2666         }
2667
2668         // don't let sound skip if going slow
2669         if (r_refdef.extraupdate)
2670                 S_ExtraUpdate ();
2671
2672         R_ResetViewRendering2D();
2673 }
2674
2675 static const int bboxelements[36] =
2676 {
2677         5, 1, 3, 5, 3, 7,
2678         6, 2, 0, 6, 0, 4,
2679         7, 3, 2, 7, 2, 6,
2680         4, 0, 1, 4, 1, 5,
2681         4, 5, 7, 4, 7, 6,
2682         1, 0, 2, 1, 2, 3,
2683 };
2684
2685 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
2686 {
2687         int i;
2688         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
2689         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2690         GL_DepthMask(false);
2691         GL_DepthRange(0, 1);
2692         R_Mesh_Matrix(&identitymatrix);
2693         R_Mesh_ResetTextureState();
2694
2695         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
2696         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
2697         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
2698         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
2699         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
2700         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
2701         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
2702         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
2703         R_FillColors(color4f, 8, cr, cg, cb, ca);
2704         if (r_refdef.fogenabled)
2705         {
2706                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
2707                 {
2708                         f1 = FogPoint_World(v);
2709                         f2 = 1 - f1;
2710                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
2711                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
2712                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
2713                 }
2714         }
2715         R_Mesh_VertexPointer(vertex3f, 0, 0);
2716         R_Mesh_ColorPointer(color4f, 0, 0);
2717         R_Mesh_ResetTextureState();
2718         R_Mesh_Draw(0, 8, 12, bboxelements, 0, 0);
2719 }
2720
2721 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2722 {
2723         int i;
2724         float color[4];
2725         prvm_edict_t *edict;
2726         // this function draws bounding boxes of server entities
2727         if (!sv.active)
2728                 return;
2729         SV_VM_Begin();
2730         for (i = 0;i < numsurfaces;i++)
2731         {
2732                 edict = PRVM_EDICT_NUM(surfacelist[i]);
2733                 switch ((int)edict->fields.server->solid)
2734                 {
2735                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
2736                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
2737                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
2738                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
2739                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
2740                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
2741                 }
2742                 color[3] *= r_showbboxes.value;
2743                 color[3] = bound(0, color[3], 1);
2744                 GL_DepthTest(!r_showdisabledepthtest.integer);
2745                 GL_CullFace(GL_BACK);
2746                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
2747         }
2748         SV_VM_End();
2749 }
2750
2751 static void R_DrawEntityBBoxes(void)
2752 {
2753         int i;
2754         prvm_edict_t *edict;
2755         vec3_t center;
2756         // this function draws bounding boxes of server entities
2757         if (!sv.active)
2758                 return;
2759         SV_VM_Begin();
2760         for (i = 0;i < prog->num_edicts;i++)
2761         {
2762                 edict = PRVM_EDICT_NUM(i);
2763                 if (edict->priv.server->free)
2764                         continue;
2765                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
2766                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
2767         }
2768         SV_VM_End();
2769 }
2770
2771 int nomodelelements[24] =
2772 {
2773         5, 2, 0,
2774         5, 1, 2,
2775         5, 0, 3,
2776         5, 3, 1,
2777         0, 2, 4,
2778         2, 1, 4,
2779         3, 0, 4,
2780         1, 3, 4
2781 };
2782
2783 float nomodelvertex3f[6*3] =
2784 {
2785         -16,   0,   0,
2786          16,   0,   0,
2787           0, -16,   0,
2788           0,  16,   0,
2789           0,   0, -16,
2790           0,   0,  16
2791 };
2792
2793 float nomodelcolor4f[6*4] =
2794 {
2795         0.0f, 0.0f, 0.5f, 1.0f,
2796         0.0f, 0.0f, 0.5f, 1.0f,
2797         0.0f, 0.5f, 0.0f, 1.0f,
2798         0.0f, 0.5f, 0.0f, 1.0f,
2799         0.5f, 0.0f, 0.0f, 1.0f,
2800         0.5f, 0.0f, 0.0f, 1.0f
2801 };
2802
2803 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2804 {
2805         int i;
2806         float f1, f2, *c;
2807         float color4f[6*4];
2808         // this is only called once per entity so numsurfaces is always 1, and
2809         // surfacelist is always {0}, so this code does not handle batches
2810         R_Mesh_Matrix(&ent->matrix);
2811
2812         if (ent->flags & EF_ADDITIVE)
2813         {
2814                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2815                 GL_DepthMask(false);
2816         }
2817         else if (ent->alpha < 1)
2818         {
2819                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2820                 GL_DepthMask(false);
2821         }
2822         else
2823         {
2824                 GL_BlendFunc(GL_ONE, GL_ZERO);
2825                 GL_DepthMask(true);
2826         }
2827         GL_DepthRange(0, (ent->flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
2828         GL_DepthTest(!(ent->effects & EF_NODEPTHTEST));
2829         GL_CullFace((ent->effects & EF_DOUBLESIDED) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
2830         R_Mesh_VertexPointer(nomodelvertex3f, 0, 0);
2831         if (r_refdef.fogenabled)
2832         {
2833                 vec3_t org;
2834                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
2835                 R_Mesh_ColorPointer(color4f, 0, 0);
2836                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
2837                 f1 = FogPoint_World(org);
2838                 f2 = 1 - f1;
2839                 for (i = 0, c = color4f;i < 6;i++, c += 4)
2840                 {
2841                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
2842                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
2843                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
2844                         c[3] *= ent->alpha;
2845                 }
2846         }
2847         else if (ent->alpha != 1)
2848         {
2849                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
2850                 R_Mesh_ColorPointer(color4f, 0, 0);
2851                 for (i = 0, c = color4f;i < 6;i++, c += 4)
2852                         c[3] *= ent->alpha;
2853         }
2854         else
2855                 R_Mesh_ColorPointer(nomodelcolor4f, 0, 0);
2856         R_Mesh_ResetTextureState();
2857         R_Mesh_Draw(0, 6, 8, nomodelelements, 0, 0);
2858 }
2859
2860 void R_DrawNoModel(entity_render_t *ent)
2861 {
2862         vec3_t org;
2863         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
2864         //if ((ent->effects & EF_ADDITIVE) || (ent->alpha < 1))
2865                 R_MeshQueue_AddTransparent(ent->effects & EF_NODEPTHTEST ? r_view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, r_shadow_rtlight);
2866         //else
2867         //      R_DrawNoModelCallback(ent, 0);
2868 }
2869
2870 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
2871 {
2872         vec3_t right1, right2, diff, normal;
2873
2874         VectorSubtract (org2, org1, normal);
2875
2876         // calculate 'right' vector for start
2877         VectorSubtract (r_view.origin, org1, diff);
2878         CrossProduct (normal, diff, right1);
2879         VectorNormalize (right1);
2880
2881         // calculate 'right' vector for end
2882         VectorSubtract (r_view.origin, org2, diff);
2883         CrossProduct (normal, diff, right2);
2884         VectorNormalize (right2);
2885
2886         vert[ 0] = org1[0] + width * right1[0];
2887         vert[ 1] = org1[1] + width * right1[1];
2888         vert[ 2] = org1[2] + width * right1[2];
2889         vert[ 3] = org1[0] - width * right1[0];
2890         vert[ 4] = org1[1] - width * right1[1];
2891         vert[ 5] = org1[2] - width * right1[2];
2892         vert[ 6] = org2[0] - width * right2[0];
2893         vert[ 7] = org2[1] - width * right2[1];
2894         vert[ 8] = org2[2] - width * right2[2];
2895         vert[ 9] = org2[0] + width * right2[0];
2896         vert[10] = org2[1] + width * right2[1];
2897         vert[11] = org2[2] + width * right2[2];
2898 }
2899
2900 float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
2901
2902 void R_DrawSprite(int blendfunc1, int blendfunc2, rtexture_t *texture, rtexture_t *fogtexture, qboolean depthdisable, qboolean depthshort, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2, float cr, float cg, float cb, float ca)
2903 {
2904         float fog = 1.0f;
2905         float vertex3f[12];
2906
2907         if (r_refdef.fogenabled)
2908                 fog = FogPoint_World(origin);
2909
2910         R_Mesh_Matrix(&identitymatrix);
2911         GL_BlendFunc(blendfunc1, blendfunc2);
2912         GL_DepthMask(false);
2913         GL_DepthRange(0, depthshort ? 0.0625 : 1);
2914         GL_DepthTest(!depthdisable);
2915
2916         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
2917         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
2918         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
2919         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
2920         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
2921         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
2922         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
2923         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
2924         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
2925         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
2926         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
2927         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
2928
2929         R_Mesh_VertexPointer(vertex3f, 0, 0);
2930         R_Mesh_ColorPointer(NULL, 0, 0);
2931         R_Mesh_ResetTextureState();
2932         R_Mesh_TexBind(0, R_GetTexture(texture));
2933         R_Mesh_TexCoordPointer(0, 2, spritetexcoord2f, 0, 0);
2934         // FIXME: fixed function path can't properly handle r_view.colorscale > 1
2935         GL_Color(cr * fog * r_view.colorscale, cg * fog * r_view.colorscale, cb * fog * r_view.colorscale, ca);
2936         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2937
2938         if (blendfunc2 == GL_ONE_MINUS_SRC_ALPHA)
2939         {
2940                 R_Mesh_TexBind(0, R_GetTexture(fogtexture));
2941                 GL_BlendFunc(blendfunc1, GL_ONE);
2942                 fog = 1 - fog;
2943                 GL_Color(r_refdef.fogcolor[0] * fog * r_view.colorscale, r_refdef.fogcolor[1] * fog * r_view.colorscale, r_refdef.fogcolor[2] * fog * r_view.colorscale, ca);
2944                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2945         }
2946 }
2947
2948 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
2949 {
2950         int i;
2951         float *vertex3f;
2952         float v[3];
2953         VectorSet(v, x, y, z);
2954         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
2955                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
2956                         break;
2957         if (i == mesh->numvertices)
2958         {
2959                 if (mesh->numvertices < mesh->maxvertices)
2960                 {
2961                         VectorCopy(v, vertex3f);
2962                         mesh->numvertices++;
2963                 }
2964                 return mesh->numvertices;
2965         }
2966         else
2967                 return i;
2968 }
2969
2970 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
2971 {
2972         int i;
2973         int *e, element[3];
2974         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
2975         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
2976         e = mesh->element3i + mesh->numtriangles * 3;
2977         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
2978         {
2979                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
2980                 if (mesh->numtriangles < mesh->maxtriangles)
2981                 {
2982                         *e++ = element[0];
2983                         *e++ = element[1];
2984                         *e++ = element[2];
2985                         mesh->numtriangles++;
2986                 }
2987                 element[1] = element[2];
2988         }
2989 }
2990
2991 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
2992 {
2993         int i;
2994         int *e, element[3];
2995         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
2996         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
2997         e = mesh->element3i + mesh->numtriangles * 3;
2998         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
2999         {
3000                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
3001                 if (mesh->numtriangles < mesh->maxtriangles)
3002                 {
3003                         *e++ = element[0];
3004                         *e++ = element[1];
3005                         *e++ = element[2];
3006                         mesh->numtriangles++;
3007                 }
3008                 element[1] = element[2];
3009         }
3010 }
3011
3012 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
3013 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
3014 {
3015         int planenum, planenum2;
3016         int w;
3017         int tempnumpoints;
3018         mplane_t *plane, *plane2;
3019         double maxdist;
3020         double temppoints[2][256*3];
3021         // figure out how large a bounding box we need to properly compute this brush
3022         maxdist = 0;
3023         for (w = 0;w < numplanes;w++)
3024                 maxdist = max(maxdist, planes[w].dist);
3025         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
3026         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
3027         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
3028         {
3029                 w = 0;
3030                 tempnumpoints = 4;
3031                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
3032                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
3033                 {
3034                         if (planenum2 == planenum)
3035                                 continue;
3036                         PolygonD_Divide(tempnumpoints, temppoints[w], plane2->normal[0], plane2->normal[1], plane2->normal[2], plane2->dist, R_MESH_PLANE_DIST_EPSILON, 0, NULL, NULL, 256, temppoints[!w], &tempnumpoints, NULL);
3037                         w = !w;
3038                 }
3039                 if (tempnumpoints < 3)
3040                         continue;
3041                 // generate elements forming a triangle fan for this polygon
3042                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
3043         }
3044 }
3045
3046 static void R_DrawCollisionBrush(const colbrushf_t *brush)
3047 {
3048         int i;
3049         R_Mesh_VertexPointer(brush->points->v, 0, 0);
3050         i = (int)(((size_t)brush) / sizeof(colbrushf_t));
3051         GL_Color((i & 31) * (1.0f / 32.0f) * r_view.colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_view.colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_view.colorscale, 0.2f);
3052         GL_LockArrays(0, brush->numpoints);
3053         R_Mesh_Draw(0, brush->numpoints, brush->numtriangles, brush->elements, 0, 0);
3054         GL_LockArrays(0, 0);
3055 }
3056
3057 static void R_DrawCollisionSurface(const entity_render_t *ent, const msurface_t *surface)
3058 {
3059         int i;
3060         if (!surface->num_collisiontriangles)
3061                 return;
3062         R_Mesh_VertexPointer(surface->data_collisionvertex3f, 0, 0);
3063         i = (int)(((size_t)surface) / sizeof(msurface_t));
3064         GL_Color((i & 31) * (1.0f / 32.0f) * r_view.colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_view.colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_view.colorscale, 0.2f);
3065         GL_LockArrays(0, surface->num_collisionvertices);
3066         R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i, 0, 0);
3067         GL_LockArrays(0, 0);
3068 }
3069
3070 static void R_Texture_AddLayer(texture_t *t, qboolean depthmask, int blendfunc1, int blendfunc2, texturelayertype_t type, rtexture_t *texture, const matrix4x4_t *matrix, float r, float g, float b, float a)
3071 {
3072         texturelayer_t *layer;
3073         layer = t->currentlayers + t->currentnumlayers++;
3074         layer->type = type;
3075         layer->depthmask = depthmask;
3076         layer->blendfunc1 = blendfunc1;
3077         layer->blendfunc2 = blendfunc2;
3078         layer->texture = texture;
3079         layer->texmatrix = *matrix;
3080         layer->color[0] = r * r_view.colorscale;
3081         layer->color[1] = g * r_view.colorscale;
3082         layer->color[2] = b * r_view.colorscale;
3083         layer->color[3] = a;
3084 }
3085
3086 void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
3087 {
3088         int i;
3089         model_t *model = ent->model;
3090
3091         // switch to an alternate material if this is a q1bsp animated material
3092         {
3093                 texture_t *texture = t;
3094                 int s = ent->skinnum;
3095                 if ((unsigned int)s >= (unsigned int)model->numskins)
3096                         s = 0;
3097                 if (model->skinscenes)
3098                 {
3099                         if (model->skinscenes[s].framecount > 1)
3100                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
3101                         else
3102                                 s = model->skinscenes[s].firstframe;
3103                 }
3104                 if (s > 0)
3105                         t = t + s * model->num_surfaces;
3106                 if (t->animated)
3107                 {
3108                         // use an alternate animation if the entity's frame is not 0,
3109                         // and only if the texture has an alternate animation
3110                         if (ent->frame != 0 && t->anim_total[1])
3111                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.time * 5.0f) % t->anim_total[1]) : 0];
3112                         else
3113                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.time * 5.0f) % t->anim_total[0]) : 0];
3114                 }
3115                 texture->currentframe = t;
3116         }
3117
3118         // update currentskinframe to be a qw skin or animation frame
3119         if ((i = ent->entitynumber - 1) >= 0 && i < cl.maxclients)
3120         {
3121                 if (strcmp(r_qwskincache[i], cl.scores[i].qw_skin))
3122                 {
3123                         strlcpy(r_qwskincache[i], cl.scores[i].qw_skin, sizeof(r_qwskincache[i]));
3124                         Con_DPrintf("loading skins/%s\n", r_qwskincache[i]);
3125                         r_qwskincache_skinframe[i] = R_SkinFrame_LoadExternal(va("skins/%s", r_qwskincache[i]), TEXF_PRECACHE | (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP, developer.integer > 0);
3126                 }
3127                 t->currentskinframe = r_qwskincache_skinframe[i];
3128                 if (t->currentskinframe == NULL)
3129                         t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
3130         }
3131         else if (t->numskinframes >= 2)
3132                 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
3133         if (t->backgroundnumskinframes >= 2)
3134                 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - ent->frame2time)) % t->backgroundnumskinframes];
3135
3136         t->currentmaterialflags = t->basematerialflags;
3137         t->currentalpha = ent->alpha;
3138         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
3139                 t->currentalpha *= r_wateralpha.value;
3140         if (!(ent->flags & RENDER_LIGHT))
3141                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
3142         if (ent->effects & EF_ADDITIVE)
3143                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
3144         else if (t->currentalpha < 1)
3145                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
3146         if (ent->effects & EF_DOUBLESIDED)
3147                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
3148         if (ent->effects & EF_NODEPTHTEST)
3149                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
3150         if (ent->flags & RENDER_VIEWMODEL)
3151                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
3152         if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
3153                 t->currenttexmatrix = r_waterscrollmatrix;
3154         else
3155                 t->currenttexmatrix = identitymatrix;
3156         if (t->backgroundnumskinframes && !(t->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
3157                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
3158
3159         t->colormapping = VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f);
3160         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
3161         t->glosstexture = r_texture_white;
3162         t->backgroundbasetexture = t->backgroundnumskinframes ? ((!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base) : r_texture_white;
3163         t->backgroundglosstexture = r_texture_white;
3164         t->specularpower = r_shadow_glossexponent.value;
3165         // TODO: store reference values for these in the texture?
3166         t->specularscale = 0;
3167         if (r_shadow_gloss.integer > 0)
3168         {
3169                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
3170                 {
3171                         if (r_shadow_glossintensity.value > 0)
3172                         {
3173                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_black;
3174                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_black;
3175                                 t->specularscale = r_shadow_glossintensity.value;
3176                         }
3177                 }
3178                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
3179                         t->specularscale = r_shadow_gloss2intensity.value;
3180         }
3181
3182         t->currentnumlayers = 0;
3183         if (!(t->currentmaterialflags & MATERIALFLAG_NODRAW))
3184         {
3185                 if (gl_lightmaps.integer)
3186                         R_Texture_AddLayer(t, true, GL_ONE, GL_ZERO, TEXTURELAYERTYPE_LITTEXTURE, r_texture_white, &identitymatrix, 1, 1, 1, 1);
3187                 else if (!(t->currentmaterialflags & MATERIALFLAG_SKY))
3188                 {
3189                         int blendfunc1, blendfunc2, depthmask;
3190                         if (t->currentmaterialflags & MATERIALFLAG_ADD)
3191                         {
3192                                 blendfunc1 = GL_SRC_ALPHA;
3193                                 blendfunc2 = GL_ONE;
3194                         }
3195                         else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
3196                         {
3197                                 blendfunc1 = GL_SRC_ALPHA;
3198                                 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
3199                         }
3200                         else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
3201                         {
3202                                 blendfunc1 = t->customblendfunc[0];
3203                                 blendfunc2 = t->customblendfunc[1];
3204                         }
3205                         else
3206                         {
3207                                 blendfunc1 = GL_ONE;
3208                                 blendfunc2 = GL_ZERO;
3209                         }
3210                         depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
3211                         if (t->currentmaterialflags & (MATERIALFLAG_WATER | MATERIALFLAG_WALL))
3212                         {
3213                                 rtexture_t *currentbasetexture;
3214                                 int layerflags = 0;
3215                                 if (r_refdef.fogenabled && (t->currentmaterialflags & MATERIALFLAG_BLENDED))
3216                                         layerflags |= TEXTURELAYERFLAG_FOGDARKEN;
3217                                 currentbasetexture = (VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) < (1.0f / 1048576.0f) && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
3218                                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
3219                                 {
3220                                         // fullbright is not affected by r_refdef.lightmapintensity
3221                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, ent->colormod[0], ent->colormod[1], ent->colormod[2], t->currentalpha);
3222                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
3223                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * ent->colormod[0], ent->colormap_pantscolor[1] * ent->colormod[1], ent->colormap_pantscolor[2] * ent->colormod[2], t->currentalpha);
3224                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
3225                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * ent->colormod[0], ent->colormap_shirtcolor[1] * ent->colormod[1], ent->colormap_shirtcolor[2] * ent->colormod[2], t->currentalpha);
3226                                 }
3227                                 else
3228                                 {
3229                                         float colorscale;
3230                                         colorscale = 2;
3231                                         // q3bsp has no lightmap updates, so the lightstylevalue that
3232                                         // would normally be baked into the lightmap must be
3233                                         // applied to the color
3234                                         if (ent->model->type == mod_brushq3)
3235                                                 colorscale *= r_refdef.lightstylevalue[0] * (1.0f / 256.0f);
3236                                         colorscale *= r_refdef.lightmapintensity;
3237                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, currentbasetexture, &t->currenttexmatrix, ent->colormod[0] * colorscale, ent->colormod[1] * colorscale, ent->colormod[2] * colorscale, t->currentalpha);
3238                                         if (r_ambient.value >= (1.0f/64.0f))
3239                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, ent->colormod[0] * r_ambient.value * (1.0f / 64.0f), ent->colormod[1] * r_ambient.value * (1.0f / 64.0f), ent->colormod[2] * r_ambient.value * (1.0f / 64.0f), t->currentalpha);
3240                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
3241                                         {
3242                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * ent->colormod[0] * colorscale, ent->colormap_pantscolor[1] * ent->colormod[1] * colorscale, ent->colormap_pantscolor[2]  * ent->colormod[2] * colorscale, t->currentalpha);
3243                                                 if (r_ambient.value >= (1.0f/64.0f))
3244                                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * ent->colormod[0] * r_ambient.value * (1.0f / 64.0f), ent->colormap_pantscolor[1] * ent->colormod[1] * r_ambient.value * (1.0f / 64.0f), ent->colormap_pantscolor[2] * ent->colormod[2] * r_ambient.value * (1.0f / 64.0f), t->currentalpha);
3245                                         }
3246                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
3247                                         {
3248                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * ent->colormod[0] * colorscale, ent->colormap_shirtcolor[1] * ent->colormod[1] * colorscale, ent->colormap_shirtcolor[2] * ent->colormod[2] * colorscale, t->currentalpha);
3249                                                 if (r_ambient.value >= (1.0f/64.0f))
3250                                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * ent->colormod[0] * r_ambient.value * (1.0f / 64.0f), ent->colormap_shirtcolor[1] * ent->colormod[1] * r_ambient.value * (1.0f / 64.0f), ent->colormap_shirtcolor[2] * ent->colormod[2] * r_ambient.value * (1.0f / 64.0f), t->currentalpha);
3251                                         }
3252                                 }
3253                                 if (t->currentskinframe->glow != NULL)
3254                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->glow, &t->currenttexmatrix, r_hdr_glowintensity.value, r_hdr_glowintensity.value, r_hdr_glowintensity.value, t->currentalpha);
3255                                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
3256                                 {
3257                                         // if this is opaque use alpha blend which will darken the earlier
3258                                         // passes cheaply.
3259                                         //
3260                                         // if this is an alpha blended material, all the earlier passes
3261                                         // were darkened by fog already, so we only need to add the fog
3262                                         // color ontop through the fog mask texture
3263                                         //
3264                                         // if this is an additive blended material, all the earlier passes
3265                                         // were darkened by fog already, and we should not add fog color
3266                                         // (because the background was not darkened, there is no fog color
3267                                         // that was lost behind it).
3268                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->currentskinframe->fog, &identitymatrix, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], t->currentalpha);
3269                                 }
3270                         }
3271                 }
3272         }
3273 }
3274
3275 void R_UpdateAllTextureInfo(entity_render_t *ent)
3276 {
3277         int i;
3278         if (ent->model)
3279                 for (i = 0;i < ent->model->num_texturesperskin;i++)
3280                         R_UpdateTextureInfo(ent, ent->model->data_textures + i);
3281 }
3282
3283 int rsurface_array_size = 0;
3284 float *rsurface_array_modelvertex3f = NULL;
3285 float *rsurface_array_modelsvector3f = NULL;
3286 float *rsurface_array_modeltvector3f = NULL;
3287 float *rsurface_array_modelnormal3f = NULL;
3288 float *rsurface_array_deformedvertex3f = NULL;
3289 float *rsurface_array_deformedsvector3f = NULL;
3290 float *rsurface_array_deformedtvector3f = NULL;
3291 float *rsurface_array_deformednormal3f = NULL;
3292 float *rsurface_array_color4f = NULL;
3293 float *rsurface_array_texcoord3f = NULL;
3294
3295 void R_Mesh_ResizeArrays(int newvertices)
3296 {
3297         float *base;
3298         if (rsurface_array_size >= newvertices)
3299                 return;
3300         if (rsurface_array_modelvertex3f)
3301                 Mem_Free(rsurface_array_modelvertex3f);
3302         rsurface_array_size = (newvertices + 1023) & ~1023;
3303         base = (float *)Mem_Alloc(r_main_mempool, rsurface_array_size * sizeof(float[31]));
3304         rsurface_array_modelvertex3f     = base + rsurface_array_size * 0;
3305         rsurface_array_modelsvector3f    = base + rsurface_array_size * 3;
3306         rsurface_array_modeltvector3f    = base + rsurface_array_size * 6;
3307         rsurface_array_modelnormal3f     = base + rsurface_array_size * 9;
3308         rsurface_array_deformedvertex3f  = base + rsurface_array_size * 12;
3309         rsurface_array_deformedsvector3f = base + rsurface_array_size * 15;
3310         rsurface_array_deformedtvector3f = base + rsurface_array_size * 18;
3311         rsurface_array_deformednormal3f  = base + rsurface_array_size * 21;
3312         rsurface_array_texcoord3f        = base + rsurface_array_size * 24;
3313         rsurface_array_color4f           = base + rsurface_array_size * 27;
3314 }
3315
3316 float *rsurface_modelvertex3f;
3317 int rsurface_modelvertex3f_bufferobject;
3318 size_t rsurface_modelvertex3f_bufferoffset;
3319 float *rsurface_modelsvector3f;
3320 int rsurface_modelsvector3f_bufferobject;
3321 size_t rsurface_modelsvector3f_bufferoffset;
3322 float *rsurface_modeltvector3f;
3323 int rsurface_modeltvector3f_bufferobject;
3324 size_t rsurface_modeltvector3f_bufferoffset;
3325 float *rsurface_modelnormal3f;
3326 int rsurface_modelnormal3f_bufferobject;
3327 size_t rsurface_modelnormal3f_bufferoffset;
3328 float *rsurface_vertex3f;
3329 int rsurface_vertex3f_bufferobject;
3330 size_t rsurface_vertex3f_bufferoffset;
3331 float *rsurface_svector3f;
3332 int rsurface_svector3f_bufferobject;
3333 size_t rsurface_svector3f_bufferoffset;
3334 float *rsurface_tvector3f;
3335 int rsurface_tvector3f_bufferobject;
3336 size_t rsurface_tvector3f_bufferoffset;
3337 float *rsurface_normal3f;
3338 int rsurface_normal3f_bufferobject;
3339 size_t rsurface_normal3f_bufferoffset;
3340 float *rsurface_lightmapcolor4f;
3341 int rsurface_lightmapcolor4f_bufferobject;
3342 size_t rsurface_lightmapcolor4f_bufferoffset;
3343 vec3_t rsurface_modelorg;
3344 qboolean rsurface_generatedvertex;
3345 const entity_render_t *rsurface_entity;
3346 const model_t *rsurface_model;
3347 texture_t *rsurface_texture;
3348 rtexture_t *rsurface_lightmaptexture;
3349 rtexture_t *rsurface_deluxemaptexture;
3350 rsurfmode_t rsurface_mode;
3351 int rsurface_lightmode; // 0 = lightmap or fullbright, 1 = color array from q3bsp, 2 = vertex shaded model
3352
3353 void RSurf_CleanUp(void)
3354 {
3355         CHECKGLERROR
3356         if (rsurface_mode == RSURFMODE_GLSL)
3357         {
3358                 qglUseProgramObjectARB(0);CHECKGLERROR
3359         }
3360         GL_AlphaTest(false);
3361         rsurface_mode = RSURFMODE_NONE;
3362         rsurface_lightmaptexture = NULL;
3363         rsurface_deluxemaptexture = NULL;
3364         rsurface_texture = NULL;
3365 }
3366
3367 void RSurf_ActiveWorldEntity(void)
3368 {
3369         RSurf_CleanUp();
3370         rsurface_entity = r_refdef.worldentity;
3371         rsurface_model = r_refdef.worldmodel;
3372         if (rsurface_array_size < rsurface_model->surfmesh.num_vertices)
3373                 R_Mesh_ResizeArrays(rsurface_model->surfmesh.num_vertices);
3374         R_Mesh_Matrix(&identitymatrix);
3375         VectorCopy(r_view.origin, rsurface_modelorg);
3376         rsurface_modelvertex3f  = rsurface_model->surfmesh.data_vertex3f;
3377         rsurface_modelvertex3f_bufferobject = rsurface_model->surfmesh.vbo;
3378         rsurface_modelvertex3f_bufferoffset = rsurface_model->surfmesh.vbooffset_vertex3f;
3379         rsurface_modelsvector3f = rsurface_model->surfmesh.data_svector3f;
3380         rsurface_modelsvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3381         rsurface_modelsvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_svector3f;
3382         rsurface_modeltvector3f = rsurface_model->surfmesh.data_tvector3f;
3383         rsurface_modeltvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3384         rsurface_modeltvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_tvector3f;
3385         rsurface_modelnormal3f  = rsurface_model->surfmesh.data_normal3f;
3386         rsurface_modelnormal3f_bufferobject = rsurface_model->surfmesh.vbo;
3387         rsurface_modelnormal3f_bufferoffset = rsurface_model->surfmesh.vbooffset_normal3f;
3388         rsurface_generatedvertex = false;
3389         rsurface_vertex3f  = rsurface_modelvertex3f;
3390         rsurface_vertex3f_bufferobject = rsurface_modelvertex3f_bufferobject;
3391         rsurface_vertex3f_bufferoffset = rsurface_modelvertex3f_bufferoffset;
3392         rsurface_svector3f = rsurface_modelsvector3f;
3393         rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject;
3394         rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset;
3395         rsurface_tvector3f = rsurface_modeltvector3f;
3396         rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject;
3397         rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset;
3398         rsurface_normal3f  = rsurface_modelnormal3f;
3399         rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject;
3400         rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset;
3401 }
3402
3403 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
3404 {
3405         RSurf_CleanUp();
3406         rsurface_entity = ent;
3407         rsurface_model = ent->model;
3408         if (rsurface_array_size < rsurface_model->surfmesh.num_vertices)
3409                 R_Mesh_ResizeArrays(rsurface_model->surfmesh.num_vertices);
3410         R_Mesh_Matrix(&ent->matrix);
3411         Matrix4x4_Transform(&ent->inversematrix, r_view.origin, rsurface_modelorg);
3412         if (rsurface_model->surfmesh.isanimated && (rsurface_entity->frameblend[0].lerp != 1 || rsurface_entity->frameblend[0].frame != 0))
3413         {
3414                 if (wanttangents)
3415                 {
3416                         rsurface_modelvertex3f = rsurface_array_modelvertex3f;
3417                         rsurface_modelsvector3f = rsurface_array_modelsvector3f;
3418                         rsurface_modeltvector3f = rsurface_array_modeltvector3f;
3419                         rsurface_modelnormal3f = rsurface_array_modelnormal3f;
3420                         Mod_Alias_GetMesh_Vertices(rsurface_model, rsurface_entity->frameblend, rsurface_array_modelvertex3f, rsurface_array_modelnormal3f, rsurface_array_modelsvector3f, rsurface_array_modeltvector3f);
3421                 }
3422                 else if (wantnormals)
3423                 {
3424                         rsurface_modelvertex3f = rsurface_array_modelvertex3f;
3425                         rsurface_modelsvector3f = NULL;
3426                         rsurface_modeltvector3f = NULL;
3427                         rsurface_modelnormal3f = rsurface_array_modelnormal3f;
3428                         Mod_Alias_GetMesh_Vertices(rsurface_model, rsurface_entity->frameblend, rsurface_array_modelvertex3f, rsurface_array_modelnormal3f, NULL, NULL);
3429                 }
3430                 else
3431                 {
3432                         rsurface_modelvertex3f = rsurface_array_modelvertex3f;
3433                         rsurface_modelsvector3f = NULL;
3434                         rsurface_modeltvector3f = NULL;
3435                         rsurface_modelnormal3f = NULL;
3436                         Mod_Alias_GetMesh_Vertices(rsurface_model, rsurface_entity->frameblend, rsurface_array_modelvertex3f, NULL, NULL, NULL);
3437                 }
3438                 rsurface_modelvertex3f_bufferobject = 0;
3439                 rsurface_modelvertex3f_bufferoffset = 0;
3440                 rsurface_modelsvector3f_bufferobject = 0;
3441                 rsurface_modelsvector3f_bufferoffset = 0;
3442                 rsurface_modeltvector3f_bufferobject = 0;
3443                 rsurface_modeltvector3f_bufferoffset = 0;
3444                 rsurface_modelnormal3f_bufferobject = 0;
3445                 rsurface_modelnormal3f_bufferoffset = 0;
3446                 rsurface_generatedvertex = true;
3447         }
3448         else
3449         {
3450                 rsurface_modelvertex3f  = rsurface_model->surfmesh.data_vertex3f;
3451                 rsurface_modelvertex3f_bufferobject = rsurface_model->surfmesh.vbo;
3452                 rsurface_modelvertex3f_bufferoffset = rsurface_model->surfmesh.vbooffset_vertex3f;
3453                 rsurface_modelsvector3f = rsurface_model->surfmesh.data_svector3f;
3454                 rsurface_modelsvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3455                 rsurface_modelsvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_svector3f;
3456                 rsurface_modeltvector3f = rsurface_model->surfmesh.data_tvector3f;
3457                 rsurface_modeltvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3458                 rsurface_modeltvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_tvector3f;
3459                 rsurface_modelnormal3f  = rsurface_model->surfmesh.data_normal3f;
3460                 rsurface_modelnormal3f_bufferobject = rsurface_model->surfmesh.vbo;
3461                 rsurface_modelnormal3f_bufferoffset = rsurface_model->surfmesh.vbooffset_normal3f;
3462                 rsurface_generatedvertex = false;
3463         }
3464         rsurface_vertex3f  = rsurface_modelvertex3f;
3465         rsurface_vertex3f_bufferobject = rsurface_modelvertex3f_bufferobject;
3466         rsurface_vertex3f_bufferoffset = rsurface_modelvertex3f_bufferoffset;
3467         rsurface_svector3f = rsurface_modelsvector3f;
3468         rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject;
3469         rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset;
3470         rsurface_tvector3f = rsurface_modeltvector3f;
3471         rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject;
3472         rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset;
3473         rsurface_normal3f  = rsurface_modelnormal3f;
3474         rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject;
3475         rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset;
3476 }
3477
3478 void RSurf_PrepareVerticesForBatch(qboolean generatenormals, qboolean generatetangents, int texturenumsurfaces, msurface_t **texturesurfacelist)
3479 {
3480         // if vertices are dynamic (animated models), generate them into the temporary rsurface_array_model* arrays and point rsurface_model* at them instead of the static data from the model itself
3481         if (rsurface_generatedvertex)
3482         {
3483                 if (rsurface_texture->textureflags & (Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
3484                         generatetangents = true;
3485                 if (generatetangents)
3486                         generatenormals = true;
3487                 if (generatenormals && !rsurface_modelnormal3f)
3488                 {
3489                         rsurface_normal3f = rsurface_modelnormal3f = rsurface_array_modelnormal3f;
3490                         rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject = 0;
3491                         rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset = 0;
3492                         Mod_BuildNormals(0, rsurface_model->surfmesh.num_vertices, rsurface_model->surfmesh.num_triangles, rsurface_modelvertex3f, rsurface_model->surfmesh.data_element3i, rsurface_array_modelnormal3f, r_smoothnormals_areaweighting.integer);
3493                 }
3494                 if (generatetangents && !rsurface_modelsvector3f)
3495                 {
3496                         rsurface_svector3f = rsurface_modelsvector3f = rsurface_array_modelsvector3f;
3497                         rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject = 0;
3498                         rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset = 0;
3499                         rsurface_tvector3f = rsurface_modeltvector3f = rsurface_array_modeltvector3f;
3500                         rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject = 0;
3501                         rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset = 0;
3502                         Mod_BuildTextureVectorsFromNormals(0, rsurface_model->surfmesh.num_vertices, rsurface_model->surfmesh.num_triangles, rsurface_modelvertex3f, rsurface_model->surfmesh.data_texcoordtexture2f, rsurface_modelnormal3f, rsurface_model->surfmesh.data_element3i, rsurface_array_modelsvector3f, rsurface_array_modeltvector3f, r_smoothnormals_areaweighting.integer);
3503                 }
3504         }
3505         // if vertices are deformed (sprite flares and things in maps, possibly water waves, bulges and other deformations), generate them into rsurface_deform* arrays from whatever the rsurface_model* array pointers point to (may be static model data or generated data for an animated model)
3506         if (rsurface_texture->textureflags & (Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
3507         {
3508                 int texturesurfaceindex;
3509                 float center[3], forward[3], right[3], up[3], v[4][3];
3510                 matrix4x4_t matrix1, imatrix1;
3511                 Matrix4x4_Transform(&rsurface_entity->inversematrix, r_view.forward, forward);
3512                 Matrix4x4_Transform(&rsurface_entity->inversematrix, r_view.right, right);
3513                 Matrix4x4_Transform(&rsurface_entity->inversematrix, r_view.up, up);
3514                 // make deformed versions of only the model vertices used by the specified surfaces
3515                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3516                 {
3517                         int i, j;
3518                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3519                         // a single autosprite surface can contain multiple sprites...
3520                         for (j = 0;j < surface->num_vertices - 3;j += 4)
3521                         {
3522                                 VectorClear(center);
3523                                 for (i = 0;i < 4;i++)
3524                                         VectorAdd(center, (rsurface_modelvertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
3525                                 VectorScale(center, 0.25f, center);
3526                                 if (rsurface_texture->textureflags & Q3TEXTUREFLAG_AUTOSPRITE2)
3527                                 {
3528                                         forward[0] = rsurface_modelorg[0] - center[0];
3529                                         forward[1] = rsurface_modelorg[1] - center[1];
3530                                         forward[2] = 0;
3531                                         VectorNormalize(forward);
3532                                         right[0] = forward[1];
3533                                         right[1] = -forward[0];
3534                                         right[2] = 0;
3535                                         VectorSet(up, 0, 0, 1);
3536                                 }
3537                                 // FIXME: calculate vectors from triangle edges instead of using texture vectors as an easy way out?
3538                                 Matrix4x4_FromVectors(&matrix1, (rsurface_modelnormal3f + 3 * surface->num_firstvertex) + j*3, (rsurface_modelsvector3f + 3 * surface->num_firstvertex) + j*3, (rsurface_modeltvector3f + 3 * surface->num_firstvertex) + j*3, center);
3539                                 Matrix4x4_Invert_Simple(&imatrix1, &matrix1);
3540                                 for (i = 0;i < 4;i++)
3541                                         Matrix4x4_Transform(&imatrix1, (rsurface_modelvertex3f + 3 * surface->num_firstvertex) + (j+i)*3, v[i]);
3542                                 for (i = 0;i < 4;i++)
3543                                         VectorMAMAMAM(1, center, v[i][0], forward, v[i][1], right, v[i][2], up, rsurface_array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
3544                         }
3545                         Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface_modelvertex3f, rsurface_model->surfmesh.data_element3i + surface->num_firsttriangle * 3, rsurface_array_deformednormal3f, r_smoothnormals_areaweighting.integer);
3546                         Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface_modelvertex3f, rsurface_model->surfmesh.data_texcoordtexture2f, rsurface_array_deformednormal3f, rsurface_model->surfmesh.data_element3i + surface->num_firsttriangle * 3, rsurface_array_deformedsvector3f, rsurface_array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
3547                 }
3548                 rsurface_vertex3f = rsurface_array_deformedvertex3f;
3549                 rsurface_vertex3f_bufferobject = 0;
3550                 rsurface_vertex3f_bufferoffset = 0;
3551                 rsurface_svector3f = rsurface_array_deformedsvector3f;
3552                 rsurface_svector3f_bufferobject = 0;
3553                 rsurface_svector3f_bufferoffset = 0;
3554                 rsurface_tvector3f = rsurface_array_deformedtvector3f;
3555                 rsurface_tvector3f_bufferobject = 0;
3556                 rsurface_tvector3f_bufferoffset = 0;
3557                 rsurface_normal3f = rsurface_array_deformednormal3f;
3558                 rsurface_normal3f_bufferobject = 0;
3559                 rsurface_normal3f_bufferoffset = 0;
3560         }
3561         else
3562         {
3563                 rsurface_vertex3f  = rsurface_modelvertex3f;
3564                 rsurface_vertex3f_bufferobject = rsurface_modelvertex3f_bufferobject;
3565                 rsurface_vertex3f_bufferoffset = rsurface_modelvertex3f_bufferoffset;
3566                 rsurface_svector3f = rsurface_modelsvector3f;
3567                 rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject;
3568                 rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset;
3569                 rsurface_tvector3f = rsurface_modeltvector3f;
3570                 rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject;
3571                 rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset;
3572                 rsurface_normal3f  = rsurface_modelnormal3f;
3573                 rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject;
3574                 rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset;
3575         }
3576         R_Mesh_VertexPointer(rsurface_vertex3f, rsurface_vertex3f_bufferobject, rsurface_vertex3f_bufferoffset);
3577 }
3578
3579 void RSurf_DrawBatch_Simple(int texturenumsurfaces, msurface_t **texturesurfacelist)
3580 {
3581         int i, j;
3582         const msurface_t *surface = texturesurfacelist[0];
3583         const msurface_t *surface2;
3584         int firstvertex;
3585         int endvertex;
3586         int numvertices;
3587         int numtriangles;
3588         // TODO: lock all array ranges before render, rather than on each surface
3589         if (texturenumsurfaces == 1)
3590         {
3591                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
3592                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle), rsurface_model->surfmesh.ebo, (sizeof(int[3]) * surface->num_firsttriangle));
3593         }
3594         else if (r_batchmode.integer == 2)
3595         {
3596                 #define MAXBATCHTRIANGLES 4096
3597                 int batchtriangles = 0;
3598                 int batchelements[MAXBATCHTRIANGLES*3];
3599                 for (i = 0;i < texturenumsurfaces;i = j)
3600                 {
3601                         surface = texturesurfacelist[i];
3602                         j = i + 1;
3603                         if (surface->num_triangles > MAXBATCHTRIANGLES)
3604                         {
3605                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle), rsurface_model->surfmesh.ebo, (sizeof(int[3]) * surface->num_firsttriangle));
3606                                 continue;
3607                         }
3608                         memcpy(batchelements, rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
3609                         batchtriangles = surface->num_triangles;
3610                         firstvertex = surface->num_firstvertex;
3611                         endvertex = surface->num_firstvertex + surface->num_vertices;
3612                         for (;j < texturenumsurfaces;j++)
3613                         {
3614                                 surface2 = texturesurfacelist[j];
3615                                 if (batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
3616                                         break;
3617                                 memcpy(batchelements + batchtriangles * 3, rsurface_model->surfmesh.data_element3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
3618                                 batchtriangles += surface2->num_triangles;
3619                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
3620   &