]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rmain.c
removed r_shadow_realtime_world_dlightshadows cvar, now the
[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_depthfirst = {CVAR_SAVE, "r_depthfirst", "1", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
38 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
39 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
40 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)"};
41 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
42 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
43 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"};
44 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"};
45 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
46 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"};
47 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"};
48 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"};
49 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
50 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
51 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
52 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
53 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
54 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
55 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
56 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
57 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
58 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
59 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
60 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
61 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this)"};
62 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
63 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
64
65 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
66 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
67 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
68 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
69 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
70 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
71 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
72
73 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)"};
74
75 cvar_t r_glsl = {CVAR_SAVE, "r_glsl", "1", "enables use of OpenGL 2.0 pixel shaders for lighting"};
76 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
77 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
78 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
79 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)"};
80
81 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "1", "enables animation smoothing on sprites (requires r_lerpmodels 1)"};
82 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
83 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
84
85 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
86 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
87 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
88 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
89 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
90 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
91 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
92
93 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
94 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
95 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
96 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)"};
97
98 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"};
99
100 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"};
101
102 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
103
104 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
105 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
106
107 typedef struct r_glsl_bloomshader_s
108 {
109         int program;
110         int loc_Texture_Bloom;
111 }
112 r_glsl_bloomshader_t;
113
114 static struct r_bloomstate_s
115 {
116         qboolean enabled;
117         qboolean hdr;
118
119         int bloomwidth, bloomheight;
120
121         int screentexturewidth, screentextureheight;
122         rtexture_t *texture_screen;
123
124         int bloomtexturewidth, bloomtextureheight;
125         rtexture_t *texture_bloom;
126
127         r_glsl_bloomshader_t *shader;
128
129         // arrays for rendering the screen passes
130         float screentexcoord2f[8];
131         float bloomtexcoord2f[8];
132         float offsettexcoord2f[8];
133 }
134 r_bloomstate;
135
136 // shadow volume bsp struct with automatically growing nodes buffer
137 svbsp_t r_svbsp;
138
139 rtexture_t *r_texture_blanknormalmap;
140 rtexture_t *r_texture_white;
141 rtexture_t *r_texture_black;
142 rtexture_t *r_texture_notexture;
143 rtexture_t *r_texture_whitecube;
144 rtexture_t *r_texture_normalizationcube;
145 rtexture_t *r_texture_fogattenuation;
146 //rtexture_t *r_texture_fogintensity;
147
148 // information about each possible shader permutation
149 r_glsl_permutation_t r_glsl_permutations[SHADERPERMUTATION_MAX];
150 // currently selected permutation
151 r_glsl_permutation_t *r_glsl_permutation;
152
153 char r_qwskincache[MAX_SCOREBOARD][MAX_QPATH];
154 skinframe_t *r_qwskincache_skinframe[MAX_SCOREBOARD];
155
156 // vertex coordinates for a quad that covers the screen exactly
157 const static float r_screenvertex3f[12] =
158 {
159         0, 0, 0,
160         1, 0, 0,
161         1, 1, 0,
162         0, 1, 0
163 };
164
165 extern void R_DrawModelShadows(void);
166
167 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
168 {
169         int i;
170         for (i = 0;i < verts;i++)
171         {
172                 out[0] = in[0] * r;
173                 out[1] = in[1] * g;
174                 out[2] = in[2] * b;
175                 out[3] = in[3];
176                 in += 4;
177                 out += 4;
178         }
179 }
180
181 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
182 {
183         int i;
184         for (i = 0;i < verts;i++)
185         {
186                 out[0] = r;
187                 out[1] = g;
188                 out[2] = b;
189                 out[3] = a;
190                 out += 4;
191         }
192 }
193
194 // FIXME: move this to client?
195 void FOG_clear(void)
196 {
197         if (gamemode == GAME_NEHAHRA)
198         {
199                 Cvar_Set("gl_fogenable", "0");
200                 Cvar_Set("gl_fogdensity", "0.2");
201                 Cvar_Set("gl_fogred", "0.3");
202                 Cvar_Set("gl_foggreen", "0.3");
203                 Cvar_Set("gl_fogblue", "0.3");
204         }
205         r_refdef.fog_density = r_refdef.fog_red = r_refdef.fog_green = r_refdef.fog_blue = 0.0f;
206 }
207
208 float FogPoint_World(const vec3_t p)
209 {
210         int fogmasktableindex = (int)(VectorDistance((p), r_view.origin) * r_refdef.fogmasktabledistmultiplier);
211         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
212 }
213
214 float FogPoint_Model(const vec3_t p)
215 {
216         int fogmasktableindex = (int)(VectorDistance((p), rsurface_modelorg) * r_refdef.fogmasktabledistmultiplier);
217         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
218 }
219
220 static void R_BuildBlankTextures(void)
221 {
222         unsigned char data[4];
223         data[0] = 128; // normal X
224         data[1] = 128; // normal Y
225         data[2] = 255; // normal Z
226         data[3] = 128; // height
227         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
228         data[0] = 255;
229         data[1] = 255;
230         data[2] = 255;
231         data[3] = 255;
232         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
233         data[0] = 0;
234         data[1] = 0;
235         data[2] = 0;
236         data[3] = 255;
237         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_RGBA, TEXF_PRECACHE, NULL);
238 }
239
240 static void R_BuildNoTexture(void)
241 {
242         int x, y;
243         unsigned char pix[16][16][4];
244         // this makes a light grey/dark grey checkerboard texture
245         for (y = 0;y < 16;y++)
246         {
247                 for (x = 0;x < 16;x++)
248                 {
249                         if ((y < 8) ^ (x < 8))
250                         {
251                                 pix[y][x][0] = 128;
252                                 pix[y][x][1] = 128;
253                                 pix[y][x][2] = 128;
254                                 pix[y][x][3] = 255;
255                         }
256                         else
257                         {
258                                 pix[y][x][0] = 64;
259                                 pix[y][x][1] = 64;
260                                 pix[y][x][2] = 64;
261                                 pix[y][x][3] = 255;
262                         }
263                 }
264         }
265         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_RGBA, TEXF_MIPMAP, NULL);
266 }
267
268 static void R_BuildWhiteCube(void)
269 {
270         unsigned char data[6*1*1*4];
271         data[ 0] = 255;data[ 1] = 255;data[ 2] = 255;data[ 3] = 255;
272         data[ 4] = 255;data[ 5] = 255;data[ 6] = 255;data[ 7] = 255;
273         data[ 8] = 255;data[ 9] = 255;data[10] = 255;data[11] = 255;
274         data[12] = 255;data[13] = 255;data[14] = 255;data[15] = 255;
275         data[16] = 255;data[17] = 255;data[18] = 255;data[19] = 255;
276         data[20] = 255;data[21] = 255;data[22] = 255;data[23] = 255;
277         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
278 }
279
280 static void R_BuildNormalizationCube(void)
281 {
282         int x, y, side;
283         vec3_t v;
284         vec_t s, t, intensity;
285 #define NORMSIZE 64
286         unsigned char data[6][NORMSIZE][NORMSIZE][4];
287         for (side = 0;side < 6;side++)
288         {
289                 for (y = 0;y < NORMSIZE;y++)
290                 {
291                         for (x = 0;x < NORMSIZE;x++)
292                         {
293                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
294                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
295                                 switch(side)
296                                 {
297                                 default:
298                                 case 0:
299                                         v[0] = 1;
300                                         v[1] = -t;
301                                         v[2] = -s;
302                                         break;
303                                 case 1:
304                                         v[0] = -1;
305                                         v[1] = -t;
306                                         v[2] = s;
307                                         break;
308                                 case 2:
309                                         v[0] = s;
310                                         v[1] = 1;
311                                         v[2] = t;
312                                         break;
313                                 case 3:
314                                         v[0] = s;
315                                         v[1] = -1;
316                                         v[2] = -t;
317                                         break;
318                                 case 4:
319                                         v[0] = s;
320                                         v[1] = -t;
321                                         v[2] = 1;
322                                         break;
323                                 case 5:
324                                         v[0] = -s;
325                                         v[1] = -t;
326                                         v[2] = -1;
327                                         break;
328                                 }
329                                 intensity = 127.0f / sqrt(DotProduct(v, v));
330                                 data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[0]);
331                                 data[side][y][x][1] = (unsigned char)(128.0f + intensity * v[1]);
332                                 data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[2]);
333                                 data[side][y][x][3] = 255;
334                         }
335                 }
336         }
337         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_CLAMP, NULL);
338 }
339
340 static void R_BuildFogTexture(void)
341 {
342         int x, b;
343 #define FOGWIDTH 64
344         unsigned char data1[FOGWIDTH][4];
345         //unsigned char data2[FOGWIDTH][4];
346         for (x = 0;x < FOGWIDTH;x++)
347         {
348                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
349                 data1[x][0] = b;
350                 data1[x][1] = b;
351                 data1[x][2] = b;
352                 data1[x][3] = 255;
353                 //data2[x][0] = 255 - b;
354                 //data2[x][1] = 255 - b;
355                 //data2[x][2] = 255 - b;
356                 //data2[x][3] = 255;
357         }
358         r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
359         //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_RGBA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
360 }
361
362 static const char *builtinshaderstring =
363 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
364 "// written by Forest 'LordHavoc' Hale\n"
365 "\n"
366 "// common definitions between vertex shader and fragment shader:\n"
367 "\n"
368 "#ifdef __GLSL_CG_DATA_TYPES\n"
369 "#define myhalf half\n"
370 "#define myhvec2 hvec2\n"
371 "#define myhvec3 hvec3\n"
372 "#define myhvec4 hvec4\n"
373 "#else\n"
374 "#define myhalf float\n"
375 "#define myhvec2 vec2\n"
376 "#define myhvec3 vec3\n"
377 "#define myhvec4 vec4\n"
378 "#endif\n"
379 "\n"
380 "varying vec2 TexCoord;\n"
381 "varying vec2 TexCoordLightmap;\n"
382 "\n"
383 "varying vec3 CubeVector;\n"
384 "varying vec3 LightVector;\n"
385 "varying vec3 EyeVector;\n"
386 "#ifdef USEFOG\n"
387 "varying vec3 EyeVectorModelSpace;\n"
388 "#endif\n"
389 "\n"
390 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
391 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
392 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
393 "\n"
394 "\n"
395 "\n"
396 "\n"
397 "// vertex shader specific:\n"
398 "#ifdef VERTEX_SHADER\n"
399 "\n"
400 "uniform vec3 LightPosition;\n"
401 "uniform vec3 EyePosition;\n"
402 "uniform vec3 LightDir;\n"
403 "\n"
404 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3)\n"
405 "\n"
406 "void main(void)\n"
407 "{\n"
408 "       gl_FrontColor = gl_Color;\n"
409 "       // copy the surface texcoord\n"
410 "       TexCoord = vec2(gl_TextureMatrix[0] * gl_MultiTexCoord0);\n"
411 "#if !defined(MODE_LIGHTSOURCE) && !defined(MODE_LIGHTDIRECTION)\n"
412 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
413 "#endif\n"
414 "\n"
415 "#ifdef MODE_LIGHTSOURCE\n"
416 "       // transform vertex position into light attenuation/cubemap space\n"
417 "       // (-1 to +1 across the light box)\n"
418 "       CubeVector = vec3(gl_TextureMatrix[3] * gl_Vertex);\n"
419 "\n"
420 "       // transform unnormalized light direction into tangent space\n"
421 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
422 "       //  normalize it per pixel)\n"
423 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
424 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
425 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
426 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
427 "#endif\n"
428 "\n"
429 "#ifdef MODE_LIGHTDIRECTION\n"
430 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
431 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
432 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
433 "#endif\n"
434 "\n"
435 "       // transform unnormalized eye direction into tangent space\n"
436 "#ifndef USEFOG\n"
437 "       vec3 EyeVectorModelSpace;\n"
438 "#endif\n"
439 "       EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
440 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
441 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
442 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
443 "\n"
444 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
445 "       VectorS = gl_MultiTexCoord1.xyz;\n"
446 "       VectorT = gl_MultiTexCoord2.xyz;\n"
447 "       VectorR = gl_MultiTexCoord3.xyz;\n"
448 "#endif\n"
449 "\n"
450 "       // transform vertex to camera space, using ftransform to match non-VS\n"
451 "       // rendering\n"
452 "       gl_Position = ftransform();\n"
453 "}\n"
454 "\n"
455 "#endif // VERTEX_SHADER\n"
456 "\n"
457 "\n"
458 "\n"
459 "\n"
460 "// fragment shader specific:\n"
461 "#ifdef FRAGMENT_SHADER\n"
462 "\n"
463 "// 11 textures, we can only use up to 16 on DX9-class hardware\n"
464 "uniform sampler2D Texture_Normal;\n"
465 "uniform sampler2D Texture_Color;\n"
466 "uniform sampler2D Texture_Gloss;\n"
467 "uniform samplerCube Texture_Cube;\n"
468 "uniform sampler2D Texture_Attenuation;\n"
469 "uniform sampler2D Texture_FogMask;\n"
470 "uniform sampler2D Texture_Pants;\n"
471 "uniform sampler2D Texture_Shirt;\n"
472 "uniform sampler2D Texture_Lightmap;\n"
473 "uniform sampler2D Texture_Deluxemap;\n"
474 "uniform sampler2D Texture_Glow;\n"
475 "\n"
476 "uniform myhvec3 LightColor;\n"
477 "uniform myhvec3 AmbientColor;\n"
478 "uniform myhvec3 DiffuseColor;\n"
479 "uniform myhvec3 SpecularColor;\n"
480 "uniform myhvec3 Color_Pants;\n"
481 "uniform myhvec3 Color_Shirt;\n"
482 "uniform myhvec3 FogColor;\n"
483 "\n"
484 "uniform myhalf GlowScale;\n"
485 "uniform myhalf SceneBrightness;\n"
486 "\n"
487 "uniform float OffsetMapping_Scale;\n"
488 "uniform float OffsetMapping_Bias;\n"
489 "uniform float FogRangeRecip;\n"
490 "\n"
491 "uniform myhalf AmbientScale;\n"
492 "uniform myhalf DiffuseScale;\n"
493 "uniform myhalf SpecularScale;\n"
494 "uniform myhalf SpecularPower;\n"
495 "\n"
496 "#ifdef USEOFFSETMAPPING\n"
497 "vec2 OffsetMapping(vec2 TexCoord)\n"
498 "{\n"
499 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
500 "       // 14 sample relief mapping: linear search and then binary search\n"
501 "       // this basically steps forward a small amount repeatedly until it finds\n"
502 "       // itself inside solid, then jitters forward and back using decreasing\n"
503 "       // amounts to find the impact\n"
504 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
505 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
506 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
507 "       vec3 RT = vec3(TexCoord, 1);\n"
508 "       OffsetVector *= 0.1;\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);\n"
518 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
519 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
520 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
521 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
522 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
523 "       return RT.xy;\n"
524 "#else\n"
525 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
526 "       // this basically moves forward the full distance, and then backs up based\n"
527 "       // on height of samples\n"
528 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
529 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
530 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
531 "       TexCoord += OffsetVector;\n"
532 "       OffsetVector *= 0.333;\n"
533 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
534 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
535 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
536 "       return TexCoord;\n"
537 "#endif\n"
538 "}\n"
539 "#endif\n"
540 "\n"
541 "void main(void)\n"
542 "{\n"
543 "#ifdef USEOFFSETMAPPING\n"
544 "       // apply offsetmapping\n"
545 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
546 "#define TexCoord TexCoordOffset\n"
547 "#endif\n"
548 "\n"
549 "       // combine the diffuse textures (base, pants, shirt)\n"
550 "       myhvec4 color = myhvec4(texture2D(Texture_Color, TexCoord));\n"
551 "#ifdef USECOLORMAPPING\n"
552 "       color.rgb += myhvec3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhvec3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
553 "#endif\n"
554 "\n"
555 "\n"
556 "\n"
557 "\n"
558 "#ifdef MODE_LIGHTSOURCE\n"
559 "       // light source\n"
560 "\n"
561 "       // calculate surface normal, light normal, and specular normal\n"
562 "       // compute color intensity for the two textures (colormap and glossmap)\n"
563 "       // scale by light color and attenuation as efficiently as possible\n"
564 "       // (do as much scalar math as possible rather than vector math)\n"
565 "#ifdef USESPECULAR\n"
566 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
567 "       myhvec3 diffusenormal = myhvec3(normalize(LightVector));\n"
568 "       myhvec3 specularnormal = normalize(diffusenormal + myhvec3(normalize(EyeVector)));\n"
569 "\n"
570 "       // calculate directional shading\n"
571 "       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"
572 "#else\n"
573 "#ifdef USEDIFFUSE\n"
574 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
575 "       myhvec3 diffusenormal = myhvec3(normalize(LightVector));\n"
576 "\n"
577 "       // calculate directional shading\n"
578 "       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"
579 "#else\n"
580 "       // calculate directionless shading\n"
581 "       color.rgb = color.rgb * LightColor * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
582 "#endif\n"
583 "#endif\n"
584 "\n"
585 "#ifdef USECUBEFILTER\n"
586 "       // apply light cubemap filter\n"
587 "       //color.rgb *= normalize(CubeVector) * 0.5 + 0.5;//vec3(textureCube(Texture_Cube, CubeVector));\n"
588 "       color.rgb *= myhvec3(textureCube(Texture_Cube, CubeVector));\n"
589 "#endif\n"
590 "\n"
591 "\n"
592 "\n"
593 "\n"
594 "#elif defined(MODE_LIGHTDIRECTION)\n"
595 "       // directional model lighting\n"
596 "\n"
597 "       // get the surface normal and light normal\n"
598 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
599 "       myhvec3 diffusenormal = myhvec3(LightVector);\n"
600 "\n"
601 "       // calculate directional shading\n"
602 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
603 "#ifdef USESPECULAR\n"
604 "       myhvec3 specularnormal = normalize(diffusenormal + myhvec3(normalize(EyeVector)));\n"
605 "       color.rgb += myhvec3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
606 "#endif\n"
607 "\n"
608 "\n"
609 "\n"
610 "\n"
611 "#elif defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
612 "       // deluxemap lightmapping using light vectors in modelspace (evil q3map2)\n"
613 "\n"
614 "       // get the surface normal and light normal\n"
615 "       myhvec3 surfacenormal = normalize(myhvec3(texture2D(Texture_Normal, TexCoord)) - myhvec3(0.5));\n"
616 "\n"
617 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
618 "       myhvec3 diffusenormal_modelspace = myhvec3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhvec3(0.5);\n"
619 "       myhvec3 diffusenormal = normalize(myhvec3(dot(diffusenormal_modelspace, myhvec3(VectorS)), dot(diffusenormal_modelspace, myhvec3(VectorT)), dot(diffusenormal_modelspace, myhvec3(VectorR))));\n"
620 "#else\n"
621 "       myhvec3 diffusenormal = normalize(myhvec3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhvec3(0.5));\n"
622 "#endif\n"
623 "       // calculate directional shading\n"
624 "       myhvec3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0)));\n"
625 "#ifdef USESPECULAR\n"
626 "       myhvec3 specularnormal = myhvec3(normalize(diffusenormal + myhvec3(normalize(EyeVector))));\n"
627 "       tempcolor += myhvec3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
628 "#endif\n"
629 "\n"
630 "       // apply lightmap color\n"
631 "       color.rgb = tempcolor * myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap)) + color.rgb * AmbientScale;\n"
632 "\n"
633 "\n"
634 "#else // MODE none (lightmap)\n"
635 "       // apply lightmap color\n"
636 "       color.rgb *= myhvec3(texture2D(Texture_Lightmap, TexCoordLightmap)) * DiffuseScale + myhvec3(AmbientScale);\n"
637 "#endif // MODE\n"
638 "\n"
639 "       color *= myhvec4(gl_Color);\n"
640 "\n"
641 "#ifdef USEGLOW\n"
642 "       color.rgb += myhvec3(texture2D(Texture_Glow, TexCoord)) * GlowScale;\n"
643 "#endif\n"
644 "\n"
645 "#ifdef USEFOG\n"
646 "       // apply fog\n"
647 "       color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhvec2(length(EyeVectorModelSpace)*FogRangeRecip, 0.0))));\n"
648 "#endif\n"
649 "\n"
650 "       color.rgb *= SceneBrightness;\n"
651 "\n"
652 "       gl_FragColor = vec4(color);\n"
653 "}\n"
654 "\n"
655 "#endif // FRAGMENT_SHADER\n"
656 ;
657
658 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
659 const char *permutationinfo[][2] =
660 {
661         {"#define MODE_LIGHTSOURCE\n", " lightsource"},
662         {"#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
663         {"#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
664         {"#define MODE_LIGHTDIRECTION\n", " lightdirection"},
665         {"#define USEGLOW\n", " glow"},
666         {"#define USEFOG\n", " fog"},
667         {"#define USECOLORMAPPING\n", " colormapping"},
668         {"#define USEDIFFUSE\n", " diffuse"},
669         {"#define USESPECULAR\n", " specular"},
670         {"#define USECUBEFILTER\n", " cubefilter"},
671         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
672         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
673         {NULL, NULL}
674 };
675
676 void R_GLSL_CompilePermutation(const char *filename, int permutation)
677 {
678         int i;
679         qboolean shaderfound;
680         r_glsl_permutation_t *p = r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK);
681         int vertstrings_count;
682         int geomstrings_count;
683         int fragstrings_count;
684         char *shaderstring;
685         const char *vertstrings_list[32+1];
686         const char *geomstrings_list[32+1];
687         const char *fragstrings_list[32+1];
688         char permutationname[256];
689         if (p->compiled)
690                 return;
691         p->compiled = true;
692         p->program = 0;
693         vertstrings_list[0] = "#define VERTEX_SHADER\n";
694         geomstrings_list[0] = "#define GEOMETRY_SHADER\n";
695         fragstrings_list[0] = "#define FRAGMENT_SHADER\n";
696         vertstrings_count = 1;
697         geomstrings_count = 1;
698         fragstrings_count = 1;
699         permutationname[0] = 0;
700         for (i = 0;permutationinfo[i][0];i++)
701         {
702                 if (permutation & (1<<i))
703                 {
704                         vertstrings_list[vertstrings_count++] = permutationinfo[i][0];
705                         geomstrings_list[geomstrings_count++] = permutationinfo[i][0];
706                         fragstrings_list[fragstrings_count++] = permutationinfo[i][0];
707                         strlcat(permutationname, permutationinfo[i][1], sizeof(permutationname));
708                 }
709                 else
710                 {
711                         // keep line numbers correct
712                         vertstrings_list[vertstrings_count++] = "\n";
713                         geomstrings_list[geomstrings_count++] = "\n";
714                         fragstrings_list[fragstrings_count++] = "\n";
715                 }
716         }
717         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
718         shaderfound = false;
719         if (shaderstring)
720         {
721                 Con_DPrintf("GLSL shader text for \"%s\" loaded from disk\n", filename);
722                 vertstrings_list[vertstrings_count++] = shaderstring;
723                 geomstrings_list[geomstrings_count++] = shaderstring;
724                 fragstrings_list[fragstrings_count++] = shaderstring;
725                 shaderfound = true;
726         }
727         else if (!strcmp(filename, "glsl/default.glsl"))
728         {
729                 Con_DPrintf("GLSL shader text for \"%s\" loaded from engine\n", filename);
730                 vertstrings_list[vertstrings_count++] = builtinshaderstring;
731                 geomstrings_list[geomstrings_count++] = builtinshaderstring;
732                 fragstrings_list[fragstrings_count++] = builtinshaderstring;
733                 shaderfound = true;
734         }
735         // clear any lists that are not needed by this shader
736         if (!(permutation & SHADERPERMUTATION_USES_VERTEXSHADER))
737                 vertstrings_count = 0;
738         if (!(permutation & SHADERPERMUTATION_USES_GEOMETRYSHADER))
739                 geomstrings_count = 0;
740         if (!(permutation & SHADERPERMUTATION_USES_FRAGMENTSHADER))
741                 fragstrings_count = 0;
742         // compile the shader program
743         if (shaderfound && vertstrings_count + geomstrings_count + fragstrings_count)
744                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
745         if (p->program)
746         {
747                 CHECKGLERROR
748                 qglUseProgramObjectARB(p->program);CHECKGLERROR
749                 // look up all the uniform variable names we care about, so we don't
750                 // have to look them up every time we set them
751                 p->loc_Texture_Normal      = qglGetUniformLocationARB(p->program, "Texture_Normal");
752                 p->loc_Texture_Color       = qglGetUniformLocationARB(p->program, "Texture_Color");
753                 p->loc_Texture_Gloss       = qglGetUniformLocationARB(p->program, "Texture_Gloss");
754                 p->loc_Texture_Cube        = qglGetUniformLocationARB(p->program, "Texture_Cube");
755                 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
756                 p->loc_Texture_FogMask     = qglGetUniformLocationARB(p->program, "Texture_FogMask");
757                 p->loc_Texture_Pants       = qglGetUniformLocationARB(p->program, "Texture_Pants");
758                 p->loc_Texture_Shirt       = qglGetUniformLocationARB(p->program, "Texture_Shirt");
759                 p->loc_Texture_Lightmap    = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
760                 p->loc_Texture_Deluxemap   = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
761                 p->loc_Texture_Glow        = qglGetUniformLocationARB(p->program, "Texture_Glow");
762                 p->loc_FogColor            = qglGetUniformLocationARB(p->program, "FogColor");
763                 p->loc_LightPosition       = qglGetUniformLocationARB(p->program, "LightPosition");
764                 p->loc_EyePosition         = qglGetUniformLocationARB(p->program, "EyePosition");
765                 p->loc_LightColor          = qglGetUniformLocationARB(p->program, "LightColor");
766                 p->loc_Color_Pants         = qglGetUniformLocationARB(p->program, "Color_Pants");
767                 p->loc_Color_Shirt         = qglGetUniformLocationARB(p->program, "Color_Shirt");
768                 p->loc_FogRangeRecip       = qglGetUniformLocationARB(p->program, "FogRangeRecip");
769                 p->loc_AmbientScale        = qglGetUniformLocationARB(p->program, "AmbientScale");
770                 p->loc_DiffuseScale        = qglGetUniformLocationARB(p->program, "DiffuseScale");
771                 p->loc_SpecularPower       = qglGetUniformLocationARB(p->program, "SpecularPower");
772                 p->loc_SpecularScale       = qglGetUniformLocationARB(p->program, "SpecularScale");
773                 p->loc_GlowScale           = qglGetUniformLocationARB(p->program, "GlowScale");
774                 p->loc_SceneBrightness     = qglGetUniformLocationARB(p->program, "SceneBrightness");
775                 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
776                 p->loc_AmbientColor        = qglGetUniformLocationARB(p->program, "AmbientColor");
777                 p->loc_DiffuseColor        = qglGetUniformLocationARB(p->program, "DiffuseColor");
778                 p->loc_SpecularColor       = qglGetUniformLocationARB(p->program, "SpecularColor");
779                 p->loc_LightDir            = qglGetUniformLocationARB(p->program, "LightDir");
780                 // initialize the samplers to refer to the texture units we use
781                 if (p->loc_Texture_Normal >= 0)    qglUniform1iARB(p->loc_Texture_Normal, 0);
782                 if (p->loc_Texture_Color >= 0)     qglUniform1iARB(p->loc_Texture_Color, 1);
783                 if (p->loc_Texture_Gloss >= 0)     qglUniform1iARB(p->loc_Texture_Gloss, 2);
784                 if (p->loc_Texture_Cube >= 0)      qglUniform1iARB(p->loc_Texture_Cube, 3);
785                 if (p->loc_Texture_FogMask >= 0)   qglUniform1iARB(p->loc_Texture_FogMask, 4);
786                 if (p->loc_Texture_Pants >= 0)     qglUniform1iARB(p->loc_Texture_Pants, 5);
787                 if (p->loc_Texture_Shirt >= 0)     qglUniform1iARB(p->loc_Texture_Shirt, 6);
788                 if (p->loc_Texture_Lightmap >= 0)  qglUniform1iARB(p->loc_Texture_Lightmap, 7);
789                 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap, 8);
790                 if (p->loc_Texture_Glow >= 0)      qglUniform1iARB(p->loc_Texture_Glow, 9);
791                 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation, 10);
792                 CHECKGLERROR
793                 qglUseProgramObjectARB(0);CHECKGLERROR
794         }
795         else
796                 Con_Printf("permutation%s failed for shader %s, some features may not work properly!\n", permutationname, "glsl/default.glsl");
797         if (shaderstring)
798                 Mem_Free(shaderstring);
799 }
800
801 void R_GLSL_Restart_f(void)
802 {
803         int i;
804         for (i = 0;i < SHADERPERMUTATION_MAX;i++)
805                 if (r_glsl_permutations[i].program)
806                         GL_Backend_FreeProgram(r_glsl_permutations[i].program);
807         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
808 }
809
810 extern rtexture_t *r_shadow_attenuationgradienttexture;
811 extern rtexture_t *r_shadow_attenuation2dtexture;
812 extern rtexture_t *r_shadow_attenuation3dtexture;
813 int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale)
814 {
815         // select a permutation of the lighting shader appropriate to this
816         // combination of texture, entity, light source, and fogging, only use the
817         // minimum features necessary to avoid wasting rendering time in the
818         // fragment shader on features that are not being used
819         const char *shaderfilename = NULL;
820         unsigned int permutation = 0;
821         r_glsl_permutation = NULL;
822         // TODO: implement geometry-shader based shadow volumes someday
823         if (r_shadow_rtlight)
824         {
825                 // light source
826                 shaderfilename = "glsl/default.glsl";
827                 permutation = SHADERPERMUTATION_MODE_LIGHTSOURCE | SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
828                 if (r_shadow_rtlight->currentcubemap != r_texture_whitecube)
829                         permutation |= SHADERPERMUTATION_CUBEFILTER;
830                 if (diffusescale > 0)
831                         permutation |= SHADERPERMUTATION_DIFFUSE;
832                 if (specularscale > 0)
833                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
834                 if (r_refdef.fogenabled)
835                         permutation |= SHADERPERMUTATION_FOG;
836                 if (rsurface_texture->colormapping)
837                         permutation |= SHADERPERMUTATION_COLORMAPPING;
838                 if (r_glsl_offsetmapping.integer)
839                 {
840                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
841                         if (r_glsl_offsetmapping_reliefmapping.integer)
842                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
843                 }
844         }
845         else if (rsurface_texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
846         {
847                 // bright unshaded geometry
848                 shaderfilename = "glsl/default.glsl";
849                 permutation = SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
850                 if (rsurface_texture->currentskinframe->glow)
851                         permutation |= SHADERPERMUTATION_GLOW;
852                 if (r_refdef.fogenabled)
853                         permutation |= SHADERPERMUTATION_FOG;
854                 if (rsurface_texture->colormapping)
855                         permutation |= SHADERPERMUTATION_COLORMAPPING;
856                 if (r_glsl_offsetmapping.integer)
857                 {
858                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
859                         if (r_glsl_offsetmapping_reliefmapping.integer)
860                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
861                 }
862         }
863         else if (modellighting)
864         {
865                 // directional model lighting
866                 shaderfilename = "glsl/default.glsl";
867                 permutation = SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
868                 permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTION;
869                 if (rsurface_texture->currentskinframe->glow)
870                         permutation |= SHADERPERMUTATION_GLOW;
871                 if (specularscale > 0)
872                         permutation |= SHADERPERMUTATION_SPECULAR;
873                 if (r_refdef.fogenabled)
874                         permutation |= SHADERPERMUTATION_FOG;
875                 if (rsurface_texture->colormapping)
876                         permutation |= SHADERPERMUTATION_COLORMAPPING;
877                 if (r_glsl_offsetmapping.integer)
878                 {
879                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
880                         if (r_glsl_offsetmapping_reliefmapping.integer)
881                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
882                 }
883         }
884         else
885         {
886                 // lightmapped wall
887                 shaderfilename = "glsl/default.glsl";
888                 permutation = SHADERPERMUTATION_USES_VERTEXSHADER | SHADERPERMUTATION_USES_FRAGMENTSHADER;
889                 if (r_glsl_deluxemapping.integer >= 1 && rsurface_uselightmaptexture && r_refdef.worldmodel && r_refdef.worldmodel->brushq3.deluxemapping)
890                 {
891                         // deluxemapping (light direction texture)
892                         if (rsurface_uselightmaptexture && r_refdef.worldmodel && r_refdef.worldmodel->brushq3.deluxemapping && r_refdef.worldmodel->brushq3.deluxemapping_modelspace)
893                                 permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTIONMAP_MODELSPACE;
894                         else
895                                 permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
896                         if (specularscale > 0)
897                                 permutation |= SHADERPERMUTATION_SPECULAR;
898                 }
899                 else if (r_glsl_deluxemapping.integer >= 2)
900                 {
901                         // fake deluxemapping (uniform light direction in tangentspace)
902                         permutation |= SHADERPERMUTATION_MODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
903                         if (specularscale > 0)
904                                 permutation |= SHADERPERMUTATION_SPECULAR;
905                 }
906                 else
907                 {
908                         // ordinary lightmapping
909                         permutation |= 0;
910                 }
911                 if (rsurface_texture->currentskinframe->glow)
912                         permutation |= SHADERPERMUTATION_GLOW;
913                 if (r_refdef.fogenabled)
914                         permutation |= SHADERPERMUTATION_FOG;
915                 if (rsurface_texture->colormapping)
916                         permutation |= SHADERPERMUTATION_COLORMAPPING;
917                 if (r_glsl_offsetmapping.integer)
918                 {
919                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
920                         if (r_glsl_offsetmapping_reliefmapping.integer)
921                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
922                 }
923         }
924         if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].program)
925         {
926                 if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].compiled)
927                         R_GLSL_CompilePermutation(shaderfilename, permutation);
928                 if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].program)
929                 {
930                         // remove features until we find a valid permutation
931                         unsigned int i;
932                         for (i = SHADERPERMUTATION_MASK;;i>>=1)
933                         {
934                                 if (!i)
935                                         return 0; // utterly failed
936                                 // reduce i more quickly whenever it would not remove any bits
937                                 if (permutation < i)
938                                         continue;
939                                 permutation &= i;
940                                 if (!r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].compiled)
941                                         R_GLSL_CompilePermutation(shaderfilename, permutation);
942                                 if (r_glsl_permutations[permutation & SHADERPERMUTATION_MASK].program)
943                                         break;
944                         }
945                 }
946         }
947         r_glsl_permutation = r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK);
948         CHECKGLERROR
949         qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
950         R_Mesh_TexMatrix(0, &rsurface_texture->currenttexmatrix);
951         if (permutation & SHADERPERMUTATION_MODE_LIGHTSOURCE)
952         {
953                 if (r_glsl_permutation->loc_Texture_Cube >= 0 && r_shadow_rtlight) R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap));
954                 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]);
955                 if (permutation & SHADERPERMUTATION_DIFFUSE)
956                 {
957                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
958                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, ambientscale);
959                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, diffusescale);
960                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, specularscale);
961                 }
962                 else
963                 {
964                         // ambient only is simpler
965                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0] * ambientscale, lightcolorbase[1] * ambientscale, lightcolorbase[2] * ambientscale);
966                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, 1);
967                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, 0);
968                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, 0);
969                 }
970         }
971         else if (permutation & SHADERPERMUTATION_MODE_LIGHTDIRECTION)
972         {
973                 if (r_glsl_permutation->loc_AmbientColor >= 0)
974                         qglUniform3fARB(r_glsl_permutation->loc_AmbientColor, rsurface_entity->modellight_ambient[0] * ambientscale, rsurface_entity->modellight_ambient[1] * ambientscale, rsurface_entity->modellight_ambient[2] * ambientscale);
975                 if (r_glsl_permutation->loc_DiffuseColor >= 0)
976                         qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor, rsurface_entity->modellight_diffuse[0] * diffusescale, rsurface_entity->modellight_diffuse[1] * diffusescale, rsurface_entity->modellight_diffuse[2] * diffusescale);
977                 if (r_glsl_permutation->loc_SpecularColor >= 0)
978                         qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface_entity->modellight_diffuse[0] * specularscale, rsurface_entity->modellight_diffuse[1] * specularscale, rsurface_entity->modellight_diffuse[2] * specularscale);
979                 if (r_glsl_permutation->loc_LightDir >= 0)
980                         qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface_entity->modellight_lightdir[0], rsurface_entity->modellight_lightdir[1], rsurface_entity->modellight_lightdir[2]);
981         }
982         else
983         {
984                 if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_ambient.value * 2.0f / 128.0f);
985                 if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity * 2.0f);
986                 if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale * 2.0f);
987         }
988         if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(0, R_GetTexture(rsurface_texture->currentskinframe->nmap));
989         if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(1, R_GetTexture(rsurface_texture->basetexture));
990         if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(2, R_GetTexture(rsurface_texture->glosstexture));
991         //if (r_glsl_permutation->loc_Texture_Cube >= 0 && permutation & SHADERPERMUTATION_MODE_LIGHTSOURCE) R_Mesh_TexBindCubeMap(3, R_GetTexture(r_shadow_rtlight->currentcubemap));
992         if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(10, R_GetTexture(r_shadow_attenuationgradienttexture));
993         if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(4, R_GetTexture(r_texture_fogattenuation));
994         if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(5, R_GetTexture(rsurface_texture->currentskinframe->pants));
995         if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(6, R_GetTexture(rsurface_texture->currentskinframe->shirt));
996         //if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(7, R_GetTexture(r_texture_white));
997         //if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
998         if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(9, R_GetTexture(rsurface_texture->currentskinframe->glow));
999         if (r_glsl_permutation->loc_GlowScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_GlowScale, r_hdr_glowintensity.value);
1000         if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_view.colorscale);
1001         if (r_glsl_permutation->loc_FogColor >= 0)
1002         {
1003                 // additive passes are only darkened by fog, not tinted
1004                 if (r_shadow_rtlight || (rsurface_texture->currentmaterialflags & MATERIALFLAG_ADD))
1005                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
1006                 else
1007                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
1008         }
1009         if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface_modelorg[0], rsurface_modelorg[1], rsurface_modelorg[2]);
1010         if (r_glsl_permutation->loc_Color_Pants >= 0)
1011         {
1012                 if (rsurface_texture->currentskinframe->pants)
1013                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface_entity->colormap_pantscolor[0], rsurface_entity->colormap_pantscolor[1], rsurface_entity->colormap_pantscolor[2]);
1014                 else
1015                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
1016         }
1017         if (r_glsl_permutation->loc_Color_Shirt >= 0)
1018         {
1019                 if (rsurface_texture->currentskinframe->shirt)
1020                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface_entity->colormap_shirtcolor[0], rsurface_entity->colormap_shirtcolor[1], rsurface_entity->colormap_shirtcolor[2]);
1021                 else
1022                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
1023         }
1024         if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, r_refdef.fograngerecip);
1025         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface_texture->specularpower);
1026         if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
1027         CHECKGLERROR
1028         return permutation;
1029 }
1030
1031 void R_SwitchSurfaceShader(int permutation)
1032 {
1033         if (r_glsl_permutation != r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK))
1034         {
1035                 r_glsl_permutation = r_glsl_permutations + (permutation & SHADERPERMUTATION_MASK);
1036                 CHECKGLERROR
1037                 qglUseProgramObjectARB(r_glsl_permutation->program);
1038                 CHECKGLERROR
1039         }
1040 }
1041
1042 #define SKINFRAME_HASH 1024
1043
1044 struct
1045 {
1046         int loadsequence; // incremented each level change
1047         memexpandablearray_t array;
1048         skinframe_t *hash[SKINFRAME_HASH];
1049 }
1050 r_skinframe;
1051
1052 void R_SkinFrame_PrepareForPurge(void)
1053 {
1054         r_skinframe.loadsequence++;
1055         // wrap it without hitting zero
1056         if (r_skinframe.loadsequence >= 200)
1057                 r_skinframe.loadsequence = 1;
1058 }
1059
1060 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
1061 {
1062         if (!skinframe)
1063                 return;
1064         // mark the skinframe as used for the purging code
1065         skinframe->loadsequence = r_skinframe.loadsequence;
1066 }
1067
1068 void R_SkinFrame_Purge(void)
1069 {
1070         int i;
1071         skinframe_t *s;
1072         for (i = 0;i < SKINFRAME_HASH;i++)
1073         {
1074                 for (s = r_skinframe.hash[i];s;s = s->next)
1075                 {
1076                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
1077                         {
1078                                 if (s->base == r_texture_notexture)     s->base   = NULL;
1079                                 if (s->nmap == r_texture_blanknormalmap)s->nmap   = NULL;
1080                                 if (s->merged == s->base)               s->merged = NULL;
1081                                 if (s->stain ) R_FreeTexture(s->stain );s->stain  = NULL;
1082                                 if (s->merged) R_FreeTexture(s->merged);s->merged = NULL;
1083                                 if (s->base  ) R_FreeTexture(s->base  );s->base   = NULL;
1084                                 if (s->pants ) R_FreeTexture(s->pants );s->pants  = NULL;
1085                                 if (s->shirt ) R_FreeTexture(s->shirt );s->shirt  = NULL;
1086                                 if (s->nmap  ) R_FreeTexture(s->nmap  );s->nmap   = NULL;
1087                                 if (s->gloss ) R_FreeTexture(s->gloss );s->gloss  = NULL;
1088                                 if (s->glow  ) R_FreeTexture(s->glow  );s->glow   = NULL;
1089                                 if (s->fog   ) R_FreeTexture(s->fog   );s->fog    = NULL;
1090                                 s->loadsequence = 0;
1091                         }
1092                 }
1093         }
1094 }
1095
1096 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
1097 {
1098         skinframe_t *item;
1099         int hashindex;
1100         char basename[MAX_QPATH];
1101
1102         Image_StripImageExtension(name, basename, sizeof(basename));
1103
1104         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
1105         for (item = r_skinframe.hash[hashindex];item;item = item->next)
1106                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
1107                         break;
1108         if (!item)
1109         {
1110                 if (!add)
1111                         return NULL;
1112                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
1113                 memset(item, 0, sizeof(*item));
1114                 strlcpy(item->basename, basename, sizeof(item->basename));
1115                 item->textureflags = textureflags;
1116                 item->comparewidth = comparewidth;
1117                 item->compareheight = compareheight;
1118                 item->comparecrc = comparecrc;
1119                 item->next = r_skinframe.hash[hashindex];
1120                 r_skinframe.hash[hashindex] = item;
1121         }
1122         R_SkinFrame_MarkUsed(item);
1123         return item;
1124 }
1125
1126 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
1127 {
1128         // FIXME: it should be possible to disable loading various layers using
1129         // cvars, to prevent wasted loading time and memory usage if the user does
1130         // not want them
1131         qboolean loadnormalmap = true;
1132         qboolean loadgloss = true;
1133         qboolean loadpantsandshirt = true;
1134         qboolean loadglow = true;
1135         int j;
1136         unsigned char *pixels;
1137         unsigned char *bumppixels;
1138         unsigned char *basepixels = NULL;
1139         int basepixels_width;
1140         int basepixels_height;
1141         skinframe_t *skinframe;
1142
1143         if (cls.state == ca_dedicated)
1144                 return NULL;
1145
1146         // return an existing skinframe if already loaded
1147         // if loading of the first image fails, don't make a new skinframe as it
1148         // would cause all future lookups of this to be missing
1149         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
1150         if (skinframe && skinframe->base)
1151                 return skinframe;
1152
1153         basepixels = loadimagepixels(name, complain, 0, 0);
1154         if (basepixels == NULL)
1155                 return NULL;
1156
1157         // we've got some pixels to store, so really allocate this new texture now
1158         if (!skinframe)
1159                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
1160         skinframe->stain = NULL;
1161         skinframe->merged = NULL;
1162         skinframe->base = r_texture_notexture;
1163         skinframe->pants = NULL;
1164         skinframe->shirt = NULL;
1165         skinframe->nmap = r_texture_blanknormalmap;
1166         skinframe->gloss = NULL;
1167         skinframe->glow = NULL;
1168         skinframe->fog = NULL;
1169
1170         basepixels_width = image_width;
1171         basepixels_height = image_height;
1172         skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1173
1174         if (textureflags & TEXF_ALPHA)
1175         {
1176                 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
1177                         if (basepixels[j] < 255)
1178                                 break;
1179                 if (j < basepixels_width * basepixels_height * 4)
1180                 {
1181                         // has transparent pixels
1182                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1183                         for (j = 0;j < image_width * image_height * 4;j += 4)
1184                         {
1185                                 pixels[j+0] = 255;
1186                                 pixels[j+1] = 255;
1187                                 pixels[j+2] = 255;
1188                                 pixels[j+3] = basepixels[j+3];
1189                         }
1190                         skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1191                         Mem_Free(pixels);
1192                 }
1193         }
1194
1195         // _norm is the name used by tenebrae and has been adopted as standard
1196         if (loadnormalmap)
1197         {
1198                 if ((pixels = loadimagepixels(va("%s_norm", skinframe->basename), false, 0, 0)) != NULL)
1199                 {
1200                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1201                         Mem_Free(pixels);
1202                         pixels = NULL;
1203                 }
1204                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixels(va("%s_bump", skinframe->basename), false, 0, 0)) != NULL)
1205                 {
1206                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1207                         Image_HeightmapToNormalmap(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
1208                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1209                         Mem_Free(pixels);
1210                         Mem_Free(bumppixels);
1211                 }
1212                 else if (r_shadow_bumpscale_basetexture.value > 0)
1213                 {
1214                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
1215                         Image_HeightmapToNormalmap(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
1216                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_RGBA, skinframe->textureflags, NULL);
1217                         Mem_Free(pixels);
1218                 }
1219         }
1220         // _luma is supported for tenebrae compatibility
1221         // (I think it's a very stupid name, but oh well)
1222         // _glow is the preferred name
1223         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;}
1224         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;}
1225         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;}
1226         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;}
1227
1228         if (basepixels)
1229                 Mem_Free(basepixels);
1230
1231         return skinframe;
1232 }
1233
1234 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)
1235 {
1236         int i;
1237         if (!force)
1238         {
1239                 for (i = 0;i < width*height;i++)
1240                         if (((unsigned char *)&palette[in[i]])[3] > 0)
1241                                 break;
1242                 if (i == width*height)
1243                         return NULL;
1244         }
1245         return R_LoadTexture2D (r_main_texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
1246 }
1247
1248 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)
1249 {
1250         int i;
1251         unsigned char *temp1, *temp2;
1252         skinframe_t *skinframe;
1253
1254         if (cls.state == ca_dedicated)
1255                 return NULL;
1256
1257         // if already loaded just return it, otherwise make a new skinframe
1258         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*bitsperpixel/8) : 0, true);
1259         if (skinframe && skinframe->base)
1260                 return skinframe;
1261
1262         skinframe->stain = NULL;
1263         skinframe->merged = NULL;
1264         skinframe->base = r_texture_notexture;
1265         skinframe->pants = NULL;
1266         skinframe->shirt = NULL;
1267         skinframe->nmap = r_texture_blanknormalmap;
1268         skinframe->gloss = NULL;
1269         skinframe->glow = NULL;
1270         skinframe->fog = NULL;
1271
1272         // if no data was provided, then clearly the caller wanted to get a blank skinframe
1273         if (!skindata)
1274                 return NULL;
1275
1276         if (bitsperpixel == 32)
1277         {
1278                 if (r_shadow_bumpscale_basetexture.value > 0)
1279                 {
1280                         temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1281                         temp2 = temp1 + width * height * 4;
1282                         Image_HeightmapToNormalmap(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1283                         skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_RGBA, textureflags | TEXF_ALPHA, NULL);
1284                         Mem_Free(temp1);
1285                 }
1286                 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_RGBA, textureflags, NULL);
1287                 if (textureflags & TEXF_ALPHA)
1288                 {
1289                         for (i = 3;i < width * height * 4;i += 4)
1290                                 if (skindata[i] < 255)
1291                                         break;
1292                         if (i < width * height * 4)
1293                         {
1294                                 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
1295                                 memcpy(fogpixels, skindata, width * height * 4);
1296                                 for (i = 0;i < width * height * 4;i += 4)
1297                                         fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
1298                                 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_RGBA, textureflags, NULL);
1299                                 Mem_Free(fogpixels);
1300                         }
1301                 }
1302         }
1303         else if (bitsperpixel == 8)
1304         {
1305                 if (r_shadow_bumpscale_basetexture.value > 0)
1306                 {
1307                         temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1308                         temp2 = temp1 + width * height * 4;
1309                         if (bitsperpixel == 32)
1310                                 Image_HeightmapToNormalmap(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1311                         else
1312                         {
1313                                 // use either a custom palette or the quake palette
1314                                 Image_Copy8bitRGBA(skindata, temp1, width * height, palette ? palette : palette_complete);
1315                                 Image_HeightmapToNormalmap(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1316                         }
1317                         skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_RGBA, textureflags | TEXF_ALPHA, NULL);
1318                         Mem_Free(temp1);
1319                 }
1320                 // use either a custom palette, or the quake palette
1321                 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
1322                 if (!palette && loadglowtexture)
1323                         skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_onlyfullbrights, textureflags, false); // glow
1324                 if (!palette && loadpantsandshirt)
1325                 {
1326                         skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_pantsaswhite, textureflags, false); // pants
1327                         skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_shirtaswhite, textureflags, false); // shirt
1328                 }
1329                 if (skinframe->pants || skinframe->shirt)
1330                         skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename),loadglowtexture ? palette_nocolormapnofullbrights : palette_nocolormap, textureflags, false); // no special colors
1331                 if (textureflags & TEXF_ALPHA)
1332                 {
1333                         // if not using a custom alphapalette, use the quake one
1334                         if (!alphapalette)
1335                                 alphapalette = palette_alpha;
1336                         for (i = 0;i < width * height;i++)
1337                                 if (((unsigned char *)alphapalette)[skindata[i]*4+3] < 255)
1338                                         break;
1339                         if (i < width * height)
1340                                 skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), alphapalette, textureflags, true); // fog mask
1341                 }
1342         }
1343
1344         return skinframe;
1345 }
1346
1347 skinframe_t *R_SkinFrame_LoadMissing(void)
1348 {
1349         skinframe_t *skinframe;
1350
1351         if (cls.state == ca_dedicated)
1352                 return NULL;
1353
1354         skinframe = R_SkinFrame_Find("missing", TEXF_PRECACHE, 0, 0, 0, true);
1355         skinframe->stain = NULL;
1356         skinframe->merged = NULL;
1357         skinframe->base = r_texture_notexture;
1358         skinframe->pants = NULL;
1359         skinframe->shirt = NULL;
1360         skinframe->nmap = r_texture_blanknormalmap;
1361         skinframe->gloss = NULL;
1362         skinframe->glow = NULL;
1363         skinframe->fog = NULL;
1364
1365         return skinframe;
1366 }
1367
1368 void gl_main_start(void)
1369 {
1370         int x;
1371         double r, alpha;
1372
1373         r = (-1.0/256.0) * (FOGMASKTABLEWIDTH * FOGMASKTABLEWIDTH);
1374         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
1375         {
1376                 alpha = 1 - exp(r / ((double)x*(double)x));
1377                 if (x == FOGMASKTABLEWIDTH - 1)
1378                         alpha = 0;
1379                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
1380         }
1381
1382         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1383         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1384
1385         // set up r_skinframe loading system for textures
1386         memset(&r_skinframe, 0, sizeof(r_skinframe));
1387         r_skinframe.loadsequence = 1;
1388         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
1389
1390         r_main_texturepool = R_AllocTexturePool();
1391         R_BuildBlankTextures();
1392         R_BuildNoTexture();
1393         if (gl_texturecubemap)
1394         {
1395                 R_BuildWhiteCube();
1396                 R_BuildNormalizationCube();
1397         }
1398         R_BuildFogTexture();
1399         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1400         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
1401         memset(&r_svbsp, 0, sizeof (r_svbsp));
1402 }
1403
1404 void gl_main_shutdown(void)
1405 {
1406         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1407         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1408
1409         // clear out the r_skinframe state
1410         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
1411         memset(&r_skinframe, 0, sizeof(r_skinframe));
1412
1413         if (r_svbsp.nodes)
1414                 Mem_Free(r_svbsp.nodes);
1415         memset(&r_svbsp, 0, sizeof (r_svbsp));
1416         R_FreeTexturePool(&r_main_texturepool);
1417         r_texture_blanknormalmap = NULL;
1418         r_texture_white = NULL;
1419         r_texture_black = NULL;
1420         r_texture_whitecube = NULL;
1421         r_texture_normalizationcube = NULL;
1422         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1423         R_GLSL_Restart_f();
1424 }
1425
1426 extern void CL_ParseEntityLump(char *entitystring);
1427 void gl_main_newmap(void)
1428 {
1429         // FIXME: move this code to client
1430         int l;
1431         char *entities, entname[MAX_QPATH];
1432         if (cl.worldmodel)
1433         {
1434                 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
1435                 l = (int)strlen(entname) - 4;
1436                 if (l >= 0 && !strcmp(entname + l, ".bsp"))
1437                 {
1438                         memcpy(entname + l, ".ent", 5);
1439                         if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
1440                         {
1441                                 CL_ParseEntityLump(entities);
1442                                 Mem_Free(entities);
1443                                 return;
1444                         }
1445                 }
1446                 if (cl.worldmodel->brush.entities)
1447                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
1448         }
1449 }
1450
1451 void GL_Main_Init(void)
1452 {
1453         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
1454
1455         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
1456         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
1457         if (gamemode == GAME_NEHAHRA)
1458         {
1459                 Cvar_RegisterVariable (&gl_fogenable);
1460                 Cvar_RegisterVariable (&gl_fogdensity);
1461                 Cvar_RegisterVariable (&gl_fogred);
1462                 Cvar_RegisterVariable (&gl_foggreen);
1463                 Cvar_RegisterVariable (&gl_fogblue);
1464                 Cvar_RegisterVariable (&gl_fogstart);
1465                 Cvar_RegisterVariable (&gl_fogend);
1466         }
1467         Cvar_RegisterVariable(&r_depthfirst);
1468         Cvar_RegisterVariable(&r_nearclip);
1469         Cvar_RegisterVariable(&r_showbboxes);
1470         Cvar_RegisterVariable(&r_showsurfaces);
1471         Cvar_RegisterVariable(&r_showtris);
1472         Cvar_RegisterVariable(&r_shownormals);
1473         Cvar_RegisterVariable(&r_showlighting);
1474         Cvar_RegisterVariable(&r_showshadowvolumes);
1475         Cvar_RegisterVariable(&r_showcollisionbrushes);
1476         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
1477         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
1478         Cvar_RegisterVariable(&r_showdisabledepthtest);
1479         Cvar_RegisterVariable(&r_drawportals);
1480         Cvar_RegisterVariable(&r_drawentities);
1481         Cvar_RegisterVariable(&r_cullentities_trace);
1482         Cvar_RegisterVariable(&r_cullentities_trace_samples);
1483         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
1484         Cvar_RegisterVariable(&r_cullentities_trace_delay);
1485         Cvar_RegisterVariable(&r_drawviewmodel);
1486         Cvar_RegisterVariable(&r_speeds);
1487         Cvar_RegisterVariable(&r_fullbrights);
1488         Cvar_RegisterVariable(&r_wateralpha);
1489         Cvar_RegisterVariable(&r_dynamic);
1490         Cvar_RegisterVariable(&r_fullbright);
1491         Cvar_RegisterVariable(&r_shadows);
1492         Cvar_RegisterVariable(&r_shadows_throwdistance);
1493         Cvar_RegisterVariable(&r_q1bsp_skymasking);
1494         Cvar_RegisterVariable(&r_textureunits);
1495         Cvar_RegisterVariable(&r_glsl);
1496         Cvar_RegisterVariable(&r_glsl_offsetmapping);
1497         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
1498         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
1499         Cvar_RegisterVariable(&r_glsl_deluxemapping);
1500         Cvar_RegisterVariable(&r_lerpsprites);
1501         Cvar_RegisterVariable(&r_lerpmodels);
1502         Cvar_RegisterVariable(&r_waterscroll);
1503         Cvar_RegisterVariable(&r_bloom);
1504         Cvar_RegisterVariable(&r_bloom_colorscale);
1505         Cvar_RegisterVariable(&r_bloom_brighten);
1506         Cvar_RegisterVariable(&r_bloom_blur);
1507         Cvar_RegisterVariable(&r_bloom_resolution);
1508         Cvar_RegisterVariable(&r_bloom_colorexponent);
1509         Cvar_RegisterVariable(&r_bloom_colorsubtract);
1510         Cvar_RegisterVariable(&r_hdr);
1511         Cvar_RegisterVariable(&r_hdr_scenebrightness);
1512         Cvar_RegisterVariable(&r_hdr_glowintensity);
1513         Cvar_RegisterVariable(&r_hdr_range);
1514         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
1515         Cvar_RegisterVariable(&developer_texturelogging);
1516         Cvar_RegisterVariable(&gl_lightmaps);
1517         Cvar_RegisterVariable(&r_test);
1518         Cvar_RegisterVariable(&r_batchmode);
1519         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
1520                 Cvar_SetValue("r_fullbrights", 0);
1521         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
1522 }
1523
1524 extern void R_Textures_Init(void);
1525 extern void GL_Draw_Init(void);
1526 extern void GL_Main_Init(void);
1527 extern void R_Shadow_Init(void);
1528 extern void R_Sky_Init(void);
1529 extern void GL_Surf_Init(void);
1530 extern void R_Light_Init(void);
1531 extern void R_Particles_Init(void);
1532 extern void R_Explosion_Init(void);
1533 extern void gl_backend_init(void);
1534 extern void Sbar_Init(void);
1535 extern void R_LightningBeams_Init(void);
1536 extern void Mod_RenderInit(void);
1537
1538 void Render_Init(void)
1539 {
1540         gl_backend_init();
1541         R_Textures_Init();
1542         GL_Main_Init();
1543         GL_Draw_Init();
1544         R_Shadow_Init();
1545         R_Sky_Init();
1546         GL_Surf_Init();
1547         Sbar_Init();
1548         R_Light_Init();
1549         R_Particles_Init();
1550         R_Explosion_Init();
1551         R_LightningBeams_Init();
1552         Mod_RenderInit();
1553 }
1554
1555 /*
1556 ===============
1557 GL_Init
1558 ===============
1559 */
1560 extern char *ENGINE_EXTENSIONS;
1561 void GL_Init (void)
1562 {
1563         VID_CheckExtensions();
1564
1565         // LordHavoc: report supported extensions
1566         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
1567
1568         // clear to black (loading plaque will be seen over this)
1569         CHECKGLERROR
1570         qglClearColor(0,0,0,1);CHECKGLERROR
1571         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
1572 }
1573
1574 int R_CullBox(const vec3_t mins, const vec3_t maxs)
1575 {
1576         int i;
1577         mplane_t *p;
1578         for (i = 0;i < 4;i++)
1579         {
1580                 p = r_view.frustum + i;
1581                 switch(p->signbits)
1582                 {
1583                 default:
1584                 case 0:
1585                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1586                                 return true;
1587                         break;
1588                 case 1:
1589                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1590                                 return true;
1591                         break;
1592                 case 2:
1593                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1594                                 return true;
1595                         break;
1596                 case 3:
1597                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1598                                 return true;
1599                         break;
1600                 case 4:
1601                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1602                                 return true;
1603                         break;
1604                 case 5:
1605                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1606                                 return true;
1607                         break;
1608                 case 6:
1609                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1610                                 return true;
1611                         break;
1612                 case 7:
1613                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1614                                 return true;
1615                         break;
1616                 }
1617         }
1618         return false;
1619 }
1620
1621 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
1622 {
1623         int i;
1624         const mplane_t *p;
1625         for (i = 0;i < numplanes;i++)
1626         {
1627                 p = planes + i;
1628                 switch(p->signbits)
1629                 {
1630                 default:
1631                 case 0:
1632                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1633                                 return true;
1634                         break;
1635                 case 1:
1636                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
1637                                 return true;
1638                         break;
1639                 case 2:
1640                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1641                                 return true;
1642                         break;
1643                 case 3:
1644                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
1645                                 return true;
1646                         break;
1647                 case 4:
1648                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1649                                 return true;
1650                         break;
1651                 case 5:
1652                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
1653                                 return true;
1654                         break;
1655                 case 6:
1656                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1657                                 return true;
1658                         break;
1659                 case 7:
1660                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
1661                                 return true;
1662                         break;
1663                 }
1664         }
1665         return false;
1666 }
1667
1668 //==================================================================================
1669
1670 static void R_UpdateEntityLighting(entity_render_t *ent)
1671 {
1672         vec3_t tempdiffusenormal;
1673
1674         // fetch the lighting from the worldmodel data
1675         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));
1676         VectorClear(ent->modellight_diffuse);
1677         VectorClear(tempdiffusenormal);
1678         if ((ent->flags & RENDER_LIGHT) && r_refdef.worldmodel && r_refdef.worldmodel->brush.LightPoint)
1679         {
1680                 vec3_t org;
1681                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
1682                 r_refdef.worldmodel->brush.LightPoint(r_refdef.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
1683         }
1684         else // highly rare
1685                 VectorSet(ent->modellight_ambient, 1, 1, 1);
1686
1687         // move the light direction into modelspace coordinates for lighting code
1688         Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
1689         if(VectorLength2(ent->modellight_lightdir) > 0)
1690         {
1691                 VectorNormalize(ent->modellight_lightdir);
1692         }
1693         else
1694         {
1695                 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
1696         }
1697
1698         // scale ambient and directional light contributions according to rendering variables
1699         ent->modellight_ambient[0] *= ent->colormod[0] * r_refdef.lightmapintensity;
1700         ent->modellight_ambient[1] *= ent->colormod[1] * r_refdef.lightmapintensity;
1701         ent->modellight_ambient[2] *= ent->colormod[2] * r_refdef.lightmapintensity;
1702         ent->modellight_diffuse[0] *= ent->colormod[0] * r_refdef.lightmapintensity;
1703         ent->modellight_diffuse[1] *= ent->colormod[1] * r_refdef.lightmapintensity;
1704         ent->modellight_diffuse[2] *= ent->colormod[2] * r_refdef.lightmapintensity;
1705 }
1706
1707 static void R_View_UpdateEntityVisible (void)
1708 {
1709         int i, renderimask;
1710         entity_render_t *ent;
1711
1712         if (!r_drawentities.integer)
1713                 return;
1714
1715         renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL) : (chase_active.integer ? 0 : RENDER_EXTERIORMODEL);
1716         if (r_refdef.worldmodel && r_refdef.worldmodel->brush.BoxTouchingVisibleLeafs)
1717         {
1718                 // worldmodel can check visibility
1719                 for (i = 0;i < r_refdef.numentities;i++)
1720                 {
1721                         ent = r_refdef.entities[i];
1722                         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));
1723                 }
1724                 if(r_cullentities_trace.integer)
1725                 {
1726                         for (i = 0;i < r_refdef.numentities;i++)
1727                         {
1728                                 ent = r_refdef.entities[i];
1729                                 if(r_viewcache.entityvisible[i] && !(ent->effects & EF_NODEPTHTEST) && !(ent->flags & RENDER_VIEWMODEL) && !(ent->model && (ent->model->name[0] == '*')))
1730                                 {
1731                                         if(Mod_CanSeeBox_Trace(r_cullentities_trace_samples.integer, r_cullentities_trace_enlarge.value, r_refdef.worldmodel, r_view.origin, ent->mins, ent->maxs))
1732                                                 ent->last_trace_visibility = realtime;
1733                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
1734                                                 r_viewcache.entityvisible[i] = 0;
1735                                 }
1736                         }
1737                 }
1738         }
1739         else
1740         {
1741                 // no worldmodel or it can't check visibility
1742                 for (i = 0;i < r_refdef.numentities;i++)
1743                 {
1744                         ent = r_refdef.entities[i];
1745                         r_viewcache.entityvisible[i] = !(ent->flags & renderimask) && !R_CullBox(ent->mins, ent->maxs);
1746                 }
1747         }
1748
1749         // update entity lighting (even on hidden entities for r_shadows)
1750         for (i = 0;i < r_refdef.numentities;i++)
1751                 R_UpdateEntityLighting(r_refdef.entities[i]);
1752 }
1753
1754 // only used if skyrendermasked, and normally returns false
1755 int R_DrawBrushModelsSky (void)
1756 {
1757         int i, sky;
1758         entity_render_t *ent;
1759
1760         if (!r_drawentities.integer)
1761                 return false;
1762
1763         sky = false;
1764         for (i = 0;i < r_refdef.numentities;i++)
1765         {
1766                 if (!r_viewcache.entityvisible[i])
1767                         continue;
1768                 ent = r_refdef.entities[i];
1769                 if (!ent->model || !ent->model->DrawSky)
1770                         continue;
1771                 ent->model->DrawSky(ent);
1772                 sky = true;
1773         }
1774         return sky;
1775 }
1776
1777 void R_DrawNoModel(entity_render_t *ent);
1778 void R_DrawModels(void)
1779 {
1780         int i;
1781         entity_render_t *ent;
1782
1783         if (!r_drawentities.integer)
1784                 return;
1785
1786         for (i = 0;i < r_refdef.numentities;i++)
1787         {
1788                 if (!r_viewcache.entityvisible[i])
1789                         continue;
1790                 ent = r_refdef.entities[i];
1791                 r_refdef.stats.entities++;
1792                 if (ent->model && ent->model->Draw != NULL)
1793                         ent->model->Draw(ent);
1794                 else
1795                         R_DrawNoModel(ent);
1796         }
1797 }
1798
1799 void R_DrawModelsDepth(void)
1800 {
1801         int i;
1802         entity_render_t *ent;
1803
1804         if (!r_drawentities.integer)
1805                 return;
1806
1807         for (i = 0;i < r_refdef.numentities;i++)
1808         {
1809                 if (!r_viewcache.entityvisible[i])
1810                         continue;
1811                 ent = r_refdef.entities[i];
1812                 r_refdef.stats.entities++;
1813                 if (ent->model && ent->model->DrawDepth != NULL)
1814                         ent->model->DrawDepth(ent);
1815         }
1816 }
1817
1818 static void R_View_SetFrustum(void)
1819 {
1820         double slopex, slopey;
1821
1822         // break apart the view matrix into vectors for various purposes
1823         Matrix4x4_ToVectors(&r_view.matrix, r_view.forward, r_view.left, r_view.up, r_view.origin);
1824         VectorNegate(r_view.left, r_view.right);
1825
1826 #if 0
1827         r_view.frustum[0].normal[0] = 0 - 1.0 / r_view.frustum_x;
1828         r_view.frustum[0].normal[1] = 0 - 0;
1829         r_view.frustum[0].normal[2] = -1 - 0;
1830         r_view.frustum[1].normal[0] = 0 + 1.0 / r_view.frustum_x;
1831         r_view.frustum[1].normal[1] = 0 + 0;
1832         r_view.frustum[1].normal[2] = -1 + 0;
1833         r_view.frustum[2].normal[0] = 0 - 0;
1834         r_view.frustum[2].normal[1] = 0 - 1.0 / r_view.frustum_y;
1835         r_view.frustum[2].normal[2] = -1 - 0;
1836         r_view.frustum[3].normal[0] = 0 + 0;
1837         r_view.frustum[3].normal[1] = 0 + 1.0 / r_view.frustum_y;
1838         r_view.frustum[3].normal[2] = -1 + 0;
1839 #endif
1840
1841 #if 0
1842         zNear = r_refdef.nearclip;
1843         nudge = 1.0 - 1.0 / (1<<23);
1844         r_view.frustum[4].normal[0] = 0 - 0;
1845         r_view.frustum[4].normal[1] = 0 - 0;
1846         r_view.frustum[4].normal[2] = -1 - -nudge;
1847         r_view.frustum[4].dist = 0 - -2 * zNear * nudge;
1848         r_view.frustum[5].normal[0] = 0 + 0;
1849         r_view.frustum[5].normal[1] = 0 + 0;
1850         r_view.frustum[5].normal[2] = -1 + -nudge;
1851         r_view.frustum[5].dist = 0 + -2 * zNear * nudge;
1852 #endif
1853
1854
1855
1856 #if 0
1857         r_view.frustum[0].normal[0] = m[3] - m[0];
1858         r_view.frustum[0].normal[1] = m[7] - m[4];
1859         r_view.frustum[0].normal[2] = m[11] - m[8];
1860         r_view.frustum[0].dist = m[15] - m[12];
1861
1862         r_view.frustum[1].normal[0] = m[3] + m[0];
1863         r_view.frustum[1].normal[1] = m[7] + m[4];
1864         r_view.frustum[1].normal[2] = m[11] + m[8];
1865         r_view.frustum[1].dist = m[15] + m[12];
1866
1867         r_view.frustum[2].normal[0] = m[3] - m[1];
1868         r_view.frustum[2].normal[1] = m[7] - m[5];
1869         r_view.frustum[2].normal[2] = m[11] - m[9];
1870         r_view.frustum[2].dist = m[15] - m[13];
1871
1872         r_view.frustum[3].normal[0] = m[3] + m[1];
1873         r_view.frustum[3].normal[1] = m[7] + m[5];
1874         r_view.frustum[3].normal[2] = m[11] + m[9];
1875         r_view.frustum[3].dist = m[15] + m[13];
1876
1877         r_view.frustum[4].normal[0] = m[3] - m[2];
1878         r_view.frustum[4].normal[1] = m[7] - m[6];
1879         r_view.frustum[4].normal[2] = m[11] - m[10];
1880         r_view.frustum[4].dist = m[15] - m[14];
1881
1882         r_view.frustum[5].normal[0] = m[3] + m[2];
1883         r_view.frustum[5].normal[1] = m[7] + m[6];
1884         r_view.frustum[5].normal[2] = m[11] + m[10];
1885         r_view.frustum[5].dist = m[15] + m[14];
1886 #endif
1887
1888
1889
1890         slopex = 1.0 / r_view.frustum_x;
1891         slopey = 1.0 / r_view.frustum_y;
1892         VectorMA(r_view.forward, -slopex, r_view.left, r_view.frustum[0].normal);
1893         VectorMA(r_view.forward,  slopex, r_view.left, r_view.frustum[1].normal);
1894         VectorMA(r_view.forward, -slopey, r_view.up  , r_view.frustum[2].normal);
1895         VectorMA(r_view.forward,  slopey, r_view.up  , r_view.frustum[3].normal);
1896         VectorCopy(r_view.forward, r_view.frustum[4].normal);
1897         VectorNormalize(r_view.frustum[0].normal);
1898         VectorNormalize(r_view.frustum[1].normal);
1899         VectorNormalize(r_view.frustum[2].normal);
1900         VectorNormalize(r_view.frustum[3].normal);
1901         r_view.frustum[0].dist = DotProduct (r_view.origin, r_view.frustum[0].normal);
1902         r_view.frustum[1].dist = DotProduct (r_view.origin, r_view.frustum[1].normal);
1903         r_view.frustum[2].dist = DotProduct (r_view.origin, r_view.frustum[2].normal);
1904         r_view.frustum[3].dist = DotProduct (r_view.origin, r_view.frustum[3].normal);
1905         r_view.frustum[4].dist = DotProduct (r_view.origin, r_view.frustum[4].normal) + r_refdef.nearclip;
1906         PlaneClassify(&r_view.frustum[0]);
1907         PlaneClassify(&r_view.frustum[1]);
1908         PlaneClassify(&r_view.frustum[2]);
1909         PlaneClassify(&r_view.frustum[3]);
1910         PlaneClassify(&r_view.frustum[4]);
1911
1912         // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
1913         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward, -1024 * slopex, r_view.left, -1024 * slopey, r_view.up, r_view.frustumcorner[0]);
1914         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward,  1024 * slopex, r_view.left, -1024 * slopey, r_view.up, r_view.frustumcorner[1]);
1915         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward, -1024 * slopex, r_view.left,  1024 * slopey, r_view.up, r_view.frustumcorner[2]);
1916         VectorMAMAMAM(1, r_view.origin, 1024, r_view.forward,  1024 * slopex, r_view.left,  1024 * slopey, r_view.up, r_view.frustumcorner[3]);
1917
1918         // LordHavoc: note to all quake engine coders, Quake had a special case
1919         // for 90 degrees which assumed a square view (wrong), so I removed it,
1920         // Quake2 has it disabled as well.
1921
1922         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
1923         //RotatePointAroundVector( r_view.frustum[0].normal, r_view.up, r_view.forward, -(90 - r_refdef.fov_x / 2));
1924         //r_view.frustum[0].dist = DotProduct (r_view.origin, frustum[0].normal);
1925         //PlaneClassify(&frustum[0]);
1926
1927         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
1928         //RotatePointAroundVector( r_view.frustum[1].normal, r_view.up, r_view.forward, (90 - r_refdef.fov_x / 2));
1929         //r_view.frustum[1].dist = DotProduct (r_view.origin, frustum[1].normal);
1930         //PlaneClassify(&frustum[1]);
1931
1932         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
1933         //RotatePointAroundVector( r_view.frustum[2].normal, r_view.left, r_view.forward, -(90 - r_refdef.fov_y / 2));
1934         //r_view.frustum[2].dist = DotProduct (r_view.origin, frustum[2].normal);
1935         //PlaneClassify(&frustum[2]);
1936
1937         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
1938         //RotatePointAroundVector( r_view.frustum[3].normal, r_view.left, r_view.forward, (90 - r_refdef.fov_y / 2));
1939         //r_view.frustum[3].dist = DotProduct (r_view.origin, frustum[3].normal);
1940         //PlaneClassify(&frustum[3]);
1941
1942         // nearclip plane
1943         //VectorCopy(r_view.forward, r_view.frustum[4].normal);
1944         //r_view.frustum[4].dist = DotProduct (r_view.origin, frustum[4].normal) + r_nearclip.value;
1945         //PlaneClassify(&frustum[4]);
1946 }
1947
1948 void R_View_Update(void)
1949 {
1950         R_View_SetFrustum();
1951         R_View_WorldVisibility();
1952         R_View_UpdateEntityVisible();
1953 }
1954
1955 void R_SetupView(const matrix4x4_t *matrix)
1956 {
1957         if (r_refdef.rtworldshadows || r_refdef.rtdlightshadows)
1958                 GL_SetupView_Mode_PerspectiveInfiniteFarClip(r_view.frustum_x, r_view.frustum_y, r_refdef.nearclip);
1959         else
1960                 GL_SetupView_Mode_Perspective(r_view.frustum_x, r_view.frustum_y, r_refdef.nearclip, r_refdef.farclip);
1961
1962         GL_SetupView_Orientation_FromEntity(matrix);
1963 }
1964
1965 void R_ResetViewRendering2D(void)
1966 {
1967         if (gl_support_fragment_shader)
1968         {
1969                 qglUseProgramObjectARB(0);CHECKGLERROR
1970         }
1971
1972         DrawQ_Finish();
1973
1974         // GL is weird because it's bottom to top, r_view.y is top to bottom
1975         qglViewport(r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
1976         GL_SetupView_Mode_Ortho(0, 0, 1, 1, -10, 100);
1977         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
1978         GL_Color(1, 1, 1, 1);
1979         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
1980         GL_BlendFunc(GL_ONE, GL_ZERO);
1981         GL_AlphaTest(false);
1982         GL_ScissorTest(false);
1983         GL_DepthMask(false);
1984         GL_DepthRange(0, 1);
1985         GL_DepthTest(false);
1986         R_Mesh_Matrix(&identitymatrix);
1987         R_Mesh_ResetTextureState();
1988         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
1989         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
1990         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
1991         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
1992         qglStencilMask(~0);CHECKGLERROR
1993         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
1994         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
1995         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
1996 }
1997
1998 void R_ResetViewRendering3D(void)
1999 {
2000         if (gl_support_fragment_shader)
2001         {
2002                 qglUseProgramObjectARB(0);CHECKGLERROR
2003         }
2004
2005         DrawQ_Finish();
2006
2007         // GL is weird because it's bottom to top, r_view.y is top to bottom
2008         qglViewport(r_view.x, vid.height - (r_view.y + r_view.height), r_view.width, r_view.height);CHECKGLERROR
2009         R_SetupView(&r_view.matrix);
2010         GL_Scissor(r_view.x, r_view.y, r_view.width, r_view.height);
2011         GL_Color(1, 1, 1, 1);
2012         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
2013         GL_BlendFunc(GL_ONE, GL_ZERO);
2014         GL_AlphaTest(false);
2015         GL_ScissorTest(true);
2016         GL_DepthMask(true);
2017         GL_DepthRange(0, 1);
2018         GL_DepthTest(true);
2019         R_Mesh_Matrix(&identitymatrix);
2020         R_Mesh_ResetTextureState();
2021         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
2022         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
2023         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2024         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2025         qglStencilMask(~0);CHECKGLERROR
2026         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
2027         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
2028         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
2029 }
2030
2031 /*
2032         R_Bloom_SetupShader(
2033 "// bloom shader\n"
2034 "// written by Forest 'LordHavoc' Hale\n"
2035 "\n"
2036 "// common definitions between vertex shader and fragment shader:\n"
2037 "\n"
2038 "#ifdef __GLSL_CG_DATA_TYPES\n"
2039 "#define myhalf half\n"
2040 "#define myhvec2 hvec2\n"
2041 "#define myhvec3 hvec3\n"
2042 "#define myhvec4 hvec4\n"
2043 "#else\n"
2044 "#define myhalf float\n"
2045 "#define myhvec2 vec2\n"
2046 "#define myhvec3 vec3\n"
2047 "#define myhvec4 vec4\n"
2048 "#endif\n"
2049 "\n"
2050 "varying vec2 ScreenTexCoord;\n"
2051 "varying vec2 BloomTexCoord;\n"
2052 "\n"
2053 "\n"
2054 "\n"
2055 "\n"
2056 "// vertex shader specific:\n"
2057 "#ifdef VERTEX_SHADER\n"
2058 "\n"
2059 "void main(void)\n"
2060 "{\n"
2061 "       ScreenTexCoord = vec2(gl_MultiTexCoord0);\n"
2062 "       BloomTexCoord = vec2(gl_MultiTexCoord1);\n"
2063 "       // transform vertex to camera space, using ftransform to match non-VS\n"
2064 "       // rendering\n"
2065 "       gl_Position = ftransform();\n"
2066 "}\n"
2067 "\n"
2068 "#endif // VERTEX_SHADER\n"
2069 "\n"
2070 "\n"
2071 "\n"
2072 "\n"
2073 "// fragment shader specific:\n"
2074 "#ifdef FRAGMENT_SHADER\n"
2075 "\n"
2076 "void main(void)\n"
2077 "{\n"
2078 "       int x, y;
2079 "       myhvec3 color = myhvec3(texture2D(Texture_Screen, ScreenTexCoord));\n"
2080 "       for (x = -BLUR_X;x <= BLUR_X;x++)
2081 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2082 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2083 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2084 "       color.rgb += myhvec3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2085
2086 "       gl_FragColor = vec4(color);\n"
2087 "}\n"
2088 "\n"
2089 "#endif // FRAGMENT_SHADER\n"
2090 */
2091
2092 void R_RenderScene(void);
2093
2094 void R_Bloom_StartFrame(void)
2095 {
2096         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
2097
2098         // set bloomwidth and bloomheight to the bloom resolution that will be
2099         // used (often less than the screen resolution for faster rendering)
2100         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_view.width);
2101         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_view.height / r_view.width;
2102         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_view.height);
2103
2104         // calculate desired texture sizes
2105         if (gl_support_arb_texture_non_power_of_two)
2106         {
2107                 screentexturewidth = r_view.width;
2108                 screentextureheight = r_view.height;
2109                 bloomtexturewidth = r_bloomstate.bloomwidth;
2110                 bloomtextureheight = r_bloomstate.bloomheight;
2111         }
2112         else
2113         {
2114                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
2115                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
2116                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
2117                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
2118         }
2119
2120         if (r_hdr.integer)
2121         {
2122                 screentexturewidth = screentextureheight = 0;
2123         }
2124         else if (r_bloom.integer)
2125         {
2126         }
2127         else
2128         {
2129                 screentexturewidth = screentextureheight = 0;
2130                 bloomtexturewidth = bloomtextureheight = 0;
2131         }
2132
2133         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)
2134         {
2135                 // can't use bloom if the parameters are too weird
2136                 // can't use bloom if the card does not support the texture size
2137                 if (r_bloomstate.texture_screen)
2138                         R_FreeTexture(r_bloomstate.texture_screen);
2139                 if (r_bloomstate.texture_bloom)
2140                         R_FreeTexture(r_bloomstate.texture_bloom);
2141                 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
2142                 return;
2143         }
2144
2145         r_bloomstate.enabled = true;
2146         r_bloomstate.hdr = r_hdr.integer != 0;
2147
2148         // allocate textures as needed
2149         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
2150         {
2151                 if (r_bloomstate.texture_screen)
2152                         R_FreeTexture(r_bloomstate.texture_screen);
2153                 r_bloomstate.texture_screen = NULL;
2154                 r_bloomstate.screentexturewidth = screentexturewidth;
2155                 r_bloomstate.screentextureheight = screentextureheight;
2156                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
2157                         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);
2158         }
2159         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
2160         {
2161                 if (r_bloomstate.texture_bloom)
2162                         R_FreeTexture(r_bloomstate.texture_bloom);
2163                 r_bloomstate.texture_bloom = NULL;
2164                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
2165                 r_bloomstate.bloomtextureheight = bloomtextureheight;
2166                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
2167                         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);
2168         }
2169
2170         // set up a texcoord array for the full resolution screen image
2171         // (we have to keep this around to copy back during final render)
2172         r_bloomstate.screentexcoord2f[0] = 0;
2173         r_bloomstate.screentexcoord2f[1] = (float)r_view.height / (float)r_bloomstate.screentextureheight;
2174         r_bloomstate.screentexcoord2f[2] = (float)r_view.width / (float)r_bloomstate.screentexturewidth;
2175         r_bloomstate.screentexcoord2f[3] = (float)r_view.height / (float)r_bloomstate.screentextureheight;
2176         r_bloomstate.screentexcoord2f[4] = (float)r_view.width / (float)r_bloomstate.screentexturewidth;
2177         r_bloomstate.screentexcoord2f[5] = 0;
2178         r_bloomstate.screentexcoord2f[6] = 0;
2179         r_bloomstate.screentexcoord2f[7] = 0;
2180
2181         // set up a texcoord array for the reduced resolution bloom image
2182         // (which will be additive blended over the screen image)
2183         r_bloomstate.bloomtexcoord2f[0] = 0;
2184         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2185         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2186         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2187         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2188         r_bloomstate.bloomtexcoord2f[5] = 0;
2189         r_bloomstate.bloomtexcoord2f[6] = 0;
2190         r_bloomstate.bloomtexcoord2f[7] = 0;
2191 }
2192
2193 void R_Bloom_CopyScreenTexture(float colorscale)
2194 {
2195         r_refdef.stats.bloom++;
2196
2197         R_ResetViewRendering2D();
2198         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2199         R_Mesh_ColorPointer(NULL, 0, 0);
2200         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
2201         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
2202
2203         // copy view into the screen texture
2204         GL_ActiveTexture(0);
2205         CHECKGLERROR
2206         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
2207         r_refdef.stats.bloom_copypixels += r_view.width * r_view.height;
2208
2209         // now scale it down to the bloom texture size
2210         CHECKGLERROR
2211         qglViewport(r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2212         GL_BlendFunc(GL_ONE, GL_ZERO);
2213         GL_Color(colorscale, colorscale, colorscale, 1);
2214         // TODO: optimize with multitexture or GLSL
2215         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2216         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2217
2218         // we now have a bloom image in the framebuffer
2219         // copy it into the bloom image texture for later processing
2220         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2221         GL_ActiveTexture(0);
2222         CHECKGLERROR
2223         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
2224         r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2225 }
2226
2227 void R_Bloom_CopyHDRTexture(void)
2228 {
2229         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2230         GL_ActiveTexture(0);
2231         CHECKGLERROR
2232         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
2233         r_refdef.stats.bloom_copypixels += r_view.width * r_view.height;
2234 }
2235
2236 void R_Bloom_MakeTexture(void)
2237 {
2238         int x, range, dir;
2239         float xoffset, yoffset, r, brighten;
2240
2241         r_refdef.stats.bloom++;
2242
2243         R_ResetViewRendering2D();
2244         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2245         R_Mesh_ColorPointer(NULL, 0, 0);
2246
2247         // we have a bloom image in the framebuffer
2248         CHECKGLERROR
2249         qglViewport(r_view.x, vid.height - (r_view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
2250
2251         for (x = 1;x < r_bloom_colorexponent.value;)
2252         {
2253                 x *= 2;
2254                 r = bound(0, r_bloom_colorexponent.value / x, 1);
2255                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
2256                 GL_Color(r, r, r, 1);
2257                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2258                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2259                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2260                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2261
2262                 // copy the vertically blurred bloom view to a texture
2263                 GL_ActiveTexture(0);
2264                 CHECKGLERROR
2265                 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
2266                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2267         }
2268
2269         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
2270         brighten = r_bloom_brighten.value;
2271         if (r_hdr.integer)
2272                 brighten *= r_hdr_range.value;
2273         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2274         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.offsettexcoord2f, 0, 0);
2275
2276         for (dir = 0;dir < 2;dir++)
2277         {
2278                 // blend on at multiple vertical offsets to achieve a vertical blur
2279                 // TODO: do offset blends using GLSL
2280                 GL_BlendFunc(GL_ONE, GL_ZERO);
2281                 for (x = -range;x <= range;x++)
2282                 {
2283                         if (!dir){xoffset = 0;yoffset = x;}
2284                         else {xoffset = x;yoffset = 0;}
2285                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
2286                         yoffset /= (float)r_bloomstate.bloomtextureheight;
2287                         // compute a texcoord array with the specified x and y offset
2288                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
2289                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2290                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2291                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
2292                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
2293                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
2294                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
2295                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
2296                         // this r value looks like a 'dot' particle, fading sharply to
2297                         // black at the edges
2298                         // (probably not realistic but looks good enough)
2299                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
2300                         //r = (dir ? 1.0f : brighten)/(range*2+1);
2301                         r = (dir ? 1.0f : brighten)/(range*2+1)*(1 - x*x/(float)(range*range));
2302                         GL_Color(r, r, r, 1);
2303                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2304                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2305                         GL_BlendFunc(GL_ONE, GL_ONE);
2306                 }
2307
2308                 // copy the vertically blurred bloom view to a texture
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         // apply subtract last
2316         // (just like it would be in a GLSL shader)
2317         if (r_bloom_colorsubtract.value > 0 && gl_support_ext_blend_subtract)
2318         {
2319                 GL_BlendFunc(GL_ONE, GL_ZERO);
2320                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2321                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2322                 GL_Color(1, 1, 1, 1);
2323                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2324                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2325
2326                 GL_BlendFunc(GL_ONE, GL_ONE);
2327                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
2328                 R_Mesh_TexBind(0, R_GetTexture(r_texture_white));
2329                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2330                 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
2331                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2332                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2333                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
2334
2335                 // copy the darkened bloom view to a texture
2336                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2337                 GL_ActiveTexture(0);
2338                 CHECKGLERROR
2339                 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
2340                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
2341         }
2342 }
2343
2344 void R_HDR_RenderBloomTexture(void)
2345 {
2346         int oldwidth, oldheight;
2347
2348         oldwidth = r_view.width;
2349         oldheight = r_view.height;
2350         r_view.width = r_bloomstate.bloomwidth;
2351         r_view.height = r_bloomstate.bloomheight;
2352
2353         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
2354         // TODO: add exposure compensation features
2355         // TODO: add fp16 framebuffer support
2356
2357         r_view.colorscale = r_bloom_colorscale.value * r_hdr_scenebrightness.value;
2358         if (r_hdr.integer)
2359                 r_view.colorscale /= r_hdr_range.value;
2360         R_RenderScene();
2361
2362         R_ResetViewRendering2D();
2363
2364         R_Bloom_CopyHDRTexture();
2365         R_Bloom_MakeTexture();
2366
2367         R_ResetViewRendering3D();
2368
2369         R_ClearScreen();
2370         if (r_timereport_active)
2371                 R_TimeReport("clear");
2372
2373
2374         // restore the view settings
2375         r_view.width = oldwidth;
2376         r_view.height = oldheight;
2377 }
2378
2379 static void R_BlendView(void)
2380 {
2381         if (r_bloomstate.enabled && r_bloomstate.hdr)
2382         {
2383                 // render high dynamic range bloom effect
2384                 // the bloom texture was made earlier this render, so we just need to
2385                 // blend it onto the screen...
2386                 R_ResetViewRendering2D();
2387                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2388                 R_Mesh_ColorPointer(NULL, 0, 0);
2389                 GL_Color(1, 1, 1, 1);
2390                 GL_BlendFunc(GL_ONE, GL_ONE);
2391                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2392                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2393                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2394                 r_refdef.stats.bloom_drawpixels += r_view.width * r_view.height;
2395         }
2396         else if (r_bloomstate.enabled)
2397         {
2398                 // render simple bloom effect
2399                 // copy the screen and shrink it and darken it for the bloom process
2400                 R_Bloom_CopyScreenTexture(r_bloom_colorscale.value);
2401                 // make the bloom texture
2402                 R_Bloom_MakeTexture();
2403                 // put the original screen image back in place and blend the bloom
2404                 // texture on it
2405                 R_ResetViewRendering2D();
2406                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2407                 R_Mesh_ColorPointer(NULL, 0, 0);
2408                 GL_Color(1, 1, 1, 1);
2409                 GL_BlendFunc(GL_ONE, GL_ZERO);
2410                 // do both in one pass if possible
2411                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
2412                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
2413                 if (r_textureunits.integer >= 2 && gl_combine.integer)
2414                 {
2415                         R_Mesh_TexCombine(1, GL_ADD, GL_ADD, 1, 1);
2416                         R_Mesh_TexBind(1, R_GetTexture(r_bloomstate.texture_screen));
2417                         R_Mesh_TexCoordPointer(1, 2, r_bloomstate.screentexcoord2f, 0, 0);
2418                 }
2419                 else
2420                 {
2421                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2422                         r_refdef.stats.bloom_drawpixels += r_view.width * r_view.height;
2423                         // now blend on the bloom texture
2424                         GL_BlendFunc(GL_ONE, GL_ONE);
2425                         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
2426                         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
2427                 }
2428                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2429                 r_refdef.stats.bloom_drawpixels += r_view.width * r_view.height;
2430         }
2431         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
2432         {
2433                 // apply a color tint to the whole view
2434                 R_ResetViewRendering2D();
2435                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
2436                 R_Mesh_ColorPointer(NULL, 0, 0);
2437                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2438                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
2439                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2440         }
2441 }
2442
2443 void R_RenderScene(void);
2444
2445 matrix4x4_t r_waterscrollmatrix;
2446
2447 void R_UpdateVariables(void)
2448 {
2449         R_Textures_Frame();
2450
2451         r_refdef.farclip = 4096;
2452         if (r_refdef.worldmodel)
2453                 r_refdef.farclip += VectorDistance(r_refdef.worldmodel->normalmins, r_refdef.worldmodel->normalmaxs);
2454         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
2455
2456         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
2457                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
2458         r_refdef.polygonfactor = 0;
2459         r_refdef.polygonoffset = 0;
2460         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
2461         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
2462
2463         r_refdef.rtworld = r_shadow_realtime_world.integer;
2464         r_refdef.rtworldshadows = r_shadow_realtime_world_shadows.integer && gl_stencil;
2465         r_refdef.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
2466         r_refdef.rtdlightshadows = r_refdef.rtdlight && r_shadow_realtime_dlight_shadows.integer && gl_stencil;
2467         r_refdef.lightmapintensity = r_refdef.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
2468         if (r_showsurfaces.integer)
2469         {
2470                 r_refdef.rtworld = false;
2471                 r_refdef.rtworldshadows = false;
2472                 r_refdef.rtdlight = false;
2473                 r_refdef.rtdlightshadows = false;
2474                 r_refdef.lightmapintensity = 0;
2475         }
2476
2477         if (gamemode == GAME_NEHAHRA)
2478         {
2479                 if (gl_fogenable.integer)
2480                 {
2481                         r_refdef.oldgl_fogenable = true;
2482                         r_refdef.fog_density = gl_fogdensity.value;
2483                         r_refdef.fog_red = gl_fogred.value;
2484                         r_refdef.fog_green = gl_foggreen.value;
2485                         r_refdef.fog_blue = gl_fogblue.value;
2486                 }
2487                 else if (r_refdef.oldgl_fogenable)
2488                 {
2489                         r_refdef.oldgl_fogenable = false;
2490                         r_refdef.fog_density = 0;
2491                         r_refdef.fog_red = 0;
2492                         r_refdef.fog_green = 0;
2493                         r_refdef.fog_blue = 0;
2494                 }
2495         }
2496         if (r_refdef.fog_density)
2497         {
2498                 r_refdef.fogcolor[0] = bound(0.0f, r_refdef.fog_red  , 1.0f);
2499                 r_refdef.fogcolor[1] = bound(0.0f, r_refdef.fog_green, 1.0f);
2500                 r_refdef.fogcolor[2] = bound(0.0f, r_refdef.fog_blue , 1.0f);
2501         }
2502         if (r_refdef.fog_density)
2503         {
2504                 r_refdef.fogenabled = true;
2505                 // this is the point where the fog reaches 0.9986 alpha, which we
2506                 // consider a good enough cutoff point for the texture
2507                 // (0.9986 * 256 == 255.6)
2508                 r_refdef.fogrange = 400 / r_refdef.fog_density;
2509                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
2510                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
2511                 // fog color was already set
2512         }
2513         else
2514                 r_refdef.fogenabled = false;
2515 }
2516
2517 /*
2518 ================
2519 R_RenderView
2520 ================
2521 */
2522 void R_RenderView(void)
2523 {
2524         if (!r_refdef.entities/* || !r_refdef.worldmodel*/)
2525                 return; //Host_Error ("R_RenderView: NULL worldmodel");
2526
2527         R_Shadow_UpdateWorldLightSelection();
2528
2529         CHECKGLERROR
2530         if (r_timereport_active)
2531                 R_TimeReport("setup");
2532
2533         R_View_Update();
2534         if (r_timereport_active)
2535                 R_TimeReport("visibility");
2536
2537         R_ResetViewRendering3D();
2538
2539         R_ClearScreen();
2540         if (r_timereport_active)
2541                 R_TimeReport("clear");
2542
2543         R_Bloom_StartFrame();
2544
2545         // this produces a bloom texture to be used in R_BlendView() later
2546         if (r_hdr.integer)
2547                 R_HDR_RenderBloomTexture();
2548
2549         r_view.colorscale = r_hdr_scenebrightness.value;
2550         R_RenderScene();
2551
2552         R_BlendView();
2553         if (r_timereport_active)
2554                 R_TimeReport("blendview");
2555
2556         GL_Scissor(0, 0, vid.width, vid.height);
2557         GL_ScissorTest(false);
2558         CHECKGLERROR
2559 }
2560
2561 extern void R_DrawLightningBeams (void);
2562 extern void VM_CL_AddPolygonsToMeshQueue (void);
2563 extern void R_DrawPortals (void);
2564 extern cvar_t cl_locs_show;
2565 static void R_DrawLocs(void);
2566 static void R_DrawEntityBBoxes(void);
2567 void R_RenderScene(void)
2568 {
2569         // don't let sound skip if going slow
2570         if (r_refdef.extraupdate)
2571                 S_ExtraUpdate ();
2572
2573         R_ResetViewRendering3D();
2574
2575         R_MeshQueue_BeginScene();
2576
2577         R_SkyStartFrame();
2578
2579         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);
2580
2581         if (cl.csqc_vidvars.drawworld)
2582         {
2583                 // don't let sound skip if going slow
2584                 if (r_refdef.extraupdate)
2585                         S_ExtraUpdate ();
2586
2587                 if (r_refdef.worldmodel && r_refdef.worldmodel->DrawSky)
2588                 {
2589                         r_refdef.worldmodel->DrawSky(r_refdef.worldentity);
2590                         if (r_timereport_active)
2591                                 R_TimeReport("worldsky");
2592                 }
2593
2594                 if (R_DrawBrushModelsSky() && r_timereport_active)
2595                         R_TimeReport("bmodelsky");
2596         }
2597
2598         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.worldmodel && r_refdef.worldmodel->DrawDepth)
2599         {
2600                 r_refdef.worldmodel->DrawDepth(r_refdef.worldentity);
2601                 if (r_timereport_active)
2602                         R_TimeReport("worlddepth");
2603         }
2604         if (r_depthfirst.integer >= 2)
2605         {
2606                 R_DrawModelsDepth();
2607                 if (r_timereport_active)
2608                         R_TimeReport("modeldepth");
2609         }
2610
2611         if (cl.csqc_vidvars.drawworld && r_refdef.worldmodel && r_refdef.worldmodel->Draw)
2612         {
2613                 r_refdef.worldmodel->Draw(r_refdef.worldentity);
2614                 if (r_timereport_active)
2615                         R_TimeReport("world");
2616         }
2617
2618         // don't let sound skip if going slow
2619         if (r_refdef.extraupdate)
2620                 S_ExtraUpdate ();
2621
2622         R_DrawModels();
2623         if (r_timereport_active)
2624                 R_TimeReport("models");
2625
2626         // don't let sound skip if going slow
2627         if (r_refdef.extraupdate)
2628                 S_ExtraUpdate ();
2629
2630         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
2631         {
2632                 R_DrawModelShadows();
2633
2634                 R_ResetViewRendering3D();
2635
2636                 // don't let sound skip if going slow
2637                 if (r_refdef.extraupdate)
2638                         S_ExtraUpdate ();
2639         }
2640
2641         R_ShadowVolumeLighting(false);
2642         if (r_timereport_active)
2643                 R_TimeReport("rtlights");
2644
2645         // don't let sound skip if going slow
2646         if (r_refdef.extraupdate)
2647                 S_ExtraUpdate ();
2648
2649         if (cl.csqc_vidvars.drawworld)
2650         {
2651                 R_DrawLightningBeams();
2652                 if (r_timereport_active)
2653                         R_TimeReport("lightning");
2654
2655                 R_DrawParticles();
2656                 if (r_timereport_active)
2657                         R_TimeReport("particles");
2658
2659                 R_DrawExplosions();
2660                 if (r_timereport_active)
2661                         R_TimeReport("explosions");
2662         }
2663
2664         if (gl_support_fragment_shader)
2665         {
2666                 qglUseProgramObjectARB(0);CHECKGLERROR
2667         }
2668         VM_CL_AddPolygonsToMeshQueue();
2669
2670         if (cl_locs_show.integer)
2671         {
2672                 R_DrawLocs();
2673                 if (r_timereport_active)
2674                         R_TimeReport("showlocs");
2675         }
2676
2677         if (r_drawportals.integer)
2678         {
2679                 R_DrawPortals();
2680                 if (r_timereport_active)
2681                         R_TimeReport("portals");
2682         }
2683
2684         if (r_showbboxes.value > 0)
2685         {
2686                 R_DrawEntityBBoxes();
2687                 if (r_timereport_active)
2688                         R_TimeReport("bboxes");
2689         }
2690
2691         if (gl_support_fragment_shader)
2692         {
2693                 qglUseProgramObjectARB(0);CHECKGLERROR
2694         }
2695         R_MeshQueue_RenderTransparent();
2696         if (r_timereport_active)
2697                 R_TimeReport("drawtrans");
2698
2699         if (gl_support_fragment_shader)
2700         {
2701                 qglUseProgramObjectARB(0);CHECKGLERROR
2702         }
2703
2704         if (cl.csqc_vidvars.drawworld)
2705         {
2706                 R_DrawCoronas();
2707                 if (r_timereport_active)
2708                         R_TimeReport("coronas");
2709         }
2710
2711         // don't let sound skip if going slow
2712         if (r_refdef.extraupdate)
2713                 S_ExtraUpdate ();
2714
2715         R_ResetViewRendering2D();
2716 }
2717
2718 static const int bboxelements[36] =
2719 {
2720         5, 1, 3, 5, 3, 7,
2721         6, 2, 0, 6, 0, 4,
2722         7, 3, 2, 7, 2, 6,
2723         4, 0, 1, 4, 1, 5,
2724         4, 5, 7, 4, 7, 6,
2725         1, 0, 2, 1, 2, 3,
2726 };
2727
2728 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
2729 {
2730         int i;
2731         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
2732         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2733         GL_DepthMask(false);
2734         GL_DepthRange(0, 1);
2735         R_Mesh_Matrix(&identitymatrix);
2736         R_Mesh_ResetTextureState();
2737
2738         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
2739         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
2740         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
2741         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
2742         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
2743         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
2744         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
2745         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
2746         R_FillColors(color4f, 8, cr, cg, cb, ca);
2747         if (r_refdef.fogenabled)
2748         {
2749                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
2750                 {
2751                         f1 = FogPoint_World(v);
2752                         f2 = 1 - f1;
2753                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
2754                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
2755                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
2756                 }
2757         }
2758         R_Mesh_VertexPointer(vertex3f, 0, 0);
2759         R_Mesh_ColorPointer(color4f, 0, 0);
2760         R_Mesh_ResetTextureState();
2761         R_Mesh_Draw(0, 8, 12, bboxelements, 0, 0);
2762 }
2763
2764 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2765 {
2766         int i;
2767         float color[4];
2768         prvm_edict_t *edict;
2769         // this function draws bounding boxes of server entities
2770         if (!sv.active)
2771                 return;
2772         SV_VM_Begin();
2773         for (i = 0;i < numsurfaces;i++)
2774         {
2775                 edict = PRVM_EDICT_NUM(surfacelist[i]);
2776                 switch ((int)edict->fields.server->solid)
2777                 {
2778                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
2779                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
2780                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
2781                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
2782                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
2783                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
2784                 }
2785                 color[3] *= r_showbboxes.value;
2786                 color[3] = bound(0, color[3], 1);
2787                 GL_DepthTest(!r_showdisabledepthtest.integer);
2788                 GL_CullFace(GL_BACK);
2789                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
2790         }
2791         SV_VM_End();
2792 }
2793
2794 static void R_DrawEntityBBoxes(void)
2795 {
2796         int i;
2797         prvm_edict_t *edict;
2798         vec3_t center;
2799         // this function draws bounding boxes of server entities
2800         if (!sv.active)
2801                 return;
2802         SV_VM_Begin();
2803         for (i = 0;i < prog->num_edicts;i++)
2804         {
2805                 edict = PRVM_EDICT_NUM(i);
2806                 if (edict->priv.server->free)
2807                         continue;
2808                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
2809                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
2810         }
2811         SV_VM_End();
2812 }
2813
2814 int nomodelelements[24] =
2815 {
2816         5, 2, 0,
2817         5, 1, 2,
2818         5, 0, 3,
2819         5, 3, 1,
2820         0, 2, 4,
2821         2, 1, 4,
2822         3, 0, 4,
2823         1, 3, 4
2824 };
2825
2826 float nomodelvertex3f[6*3] =
2827 {
2828         -16,   0,   0,
2829          16,   0,   0,
2830           0, -16,   0,
2831           0,  16,   0,
2832           0,   0, -16,
2833           0,   0,  16
2834 };
2835
2836 float nomodelcolor4f[6*4] =
2837 {
2838         0.0f, 0.0f, 0.5f, 1.0f,
2839         0.0f, 0.0f, 0.5f, 1.0f,
2840         0.0f, 0.5f, 0.0f, 1.0f,
2841         0.0f, 0.5f, 0.0f, 1.0f,
2842         0.5f, 0.0f, 0.0f, 1.0f,
2843         0.5f, 0.0f, 0.0f, 1.0f
2844 };
2845
2846 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2847 {
2848         int i;
2849         float f1, f2, *c;
2850         float color4f[6*4];
2851         // this is only called once per entity so numsurfaces is always 1, and
2852         // surfacelist is always {0}, so this code does not handle batches
2853         R_Mesh_Matrix(&ent->matrix);
2854
2855         if (ent->flags & EF_ADDITIVE)
2856         {
2857                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2858                 GL_DepthMask(false);
2859         }
2860         else if (ent->alpha < 1)
2861         {
2862                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2863                 GL_DepthMask(false);
2864         }
2865         else
2866         {
2867                 GL_BlendFunc(GL_ONE, GL_ZERO);
2868                 GL_DepthMask(true);
2869         }
2870         GL_DepthRange(0, (ent->flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
2871         GL_DepthTest(!(ent->effects & EF_NODEPTHTEST));
2872         GL_CullFace((ent->effects & EF_DOUBLESIDED) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
2873         R_Mesh_VertexPointer(nomodelvertex3f, 0, 0);
2874         if (r_refdef.fogenabled)
2875         {
2876                 vec3_t org;
2877                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
2878                 R_Mesh_ColorPointer(color4f, 0, 0);
2879                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
2880                 f1 = FogPoint_World(org);
2881                 f2 = 1 - f1;
2882                 for (i = 0, c = color4f;i < 6;i++, c += 4)
2883                 {
2884                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
2885                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
2886                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
2887                         c[3] *= ent->alpha;
2888                 }
2889         }
2890         else if (ent->alpha != 1)
2891         {
2892                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
2893                 R_Mesh_ColorPointer(color4f, 0, 0);
2894                 for (i = 0, c = color4f;i < 6;i++, c += 4)
2895                         c[3] *= ent->alpha;
2896         }
2897         else
2898                 R_Mesh_ColorPointer(nomodelcolor4f, 0, 0);
2899         R_Mesh_ResetTextureState();
2900         R_Mesh_Draw(0, 6, 8, nomodelelements, 0, 0);
2901 }
2902
2903 void R_DrawNoModel(entity_render_t *ent)
2904 {
2905         vec3_t org;
2906         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
2907         //if ((ent->effects & EF_ADDITIVE) || (ent->alpha < 1))
2908                 R_MeshQueue_AddTransparent(ent->effects & EF_NODEPTHTEST ? r_view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, r_shadow_rtlight);
2909         //else
2910         //      R_DrawNoModelCallback(ent, 0);
2911 }
2912
2913 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
2914 {
2915         vec3_t right1, right2, diff, normal;
2916
2917         VectorSubtract (org2, org1, normal);
2918
2919         // calculate 'right' vector for start
2920         VectorSubtract (r_view.origin, org1, diff);
2921         CrossProduct (normal, diff, right1);
2922         VectorNormalize (right1);
2923
2924         // calculate 'right' vector for end
2925         VectorSubtract (r_view.origin, org2, diff);
2926         CrossProduct (normal, diff, right2);
2927         VectorNormalize (right2);
2928
2929         vert[ 0] = org1[0] + width * right1[0];
2930         vert[ 1] = org1[1] + width * right1[1];
2931         vert[ 2] = org1[2] + width * right1[2];
2932         vert[ 3] = org1[0] - width * right1[0];
2933         vert[ 4] = org1[1] - width * right1[1];
2934         vert[ 5] = org1[2] - width * right1[2];
2935         vert[ 6] = org2[0] - width * right2[0];
2936         vert[ 7] = org2[1] - width * right2[1];
2937         vert[ 8] = org2[2] - width * right2[2];
2938         vert[ 9] = org2[0] + width * right2[0];
2939         vert[10] = org2[1] + width * right2[1];
2940         vert[11] = org2[2] + width * right2[2];
2941 }
2942
2943 float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
2944
2945 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)
2946 {
2947         float fog = 1.0f;
2948         float vertex3f[12];
2949
2950         if (r_refdef.fogenabled)
2951                 fog = FogPoint_World(origin);
2952
2953         R_Mesh_Matrix(&identitymatrix);
2954         GL_BlendFunc(blendfunc1, blendfunc2);
2955         GL_DepthMask(false);
2956         GL_DepthRange(0, depthshort ? 0.0625 : 1);
2957         GL_DepthTest(!depthdisable);
2958
2959         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
2960         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
2961         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
2962         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
2963         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
2964         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
2965         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
2966         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
2967         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
2968         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
2969         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
2970         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
2971
2972         R_Mesh_VertexPointer(vertex3f, 0, 0);
2973         R_Mesh_ColorPointer(NULL, 0, 0);
2974         R_Mesh_ResetTextureState();
2975         R_Mesh_TexBind(0, R_GetTexture(texture));
2976         R_Mesh_TexCoordPointer(0, 2, spritetexcoord2f, 0, 0);
2977         // FIXME: fixed function path can't properly handle r_view.colorscale > 1
2978         GL_Color(cr * fog * r_view.colorscale, cg * fog * r_view.colorscale, cb * fog * r_view.colorscale, ca);
2979         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2980
2981         if (blendfunc2 == GL_ONE_MINUS_SRC_ALPHA)
2982         {
2983                 R_Mesh_TexBind(0, R_GetTexture(fogtexture));
2984                 GL_BlendFunc(blendfunc1, GL_ONE);
2985                 fog = 1 - fog;
2986                 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);
2987                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
2988         }
2989 }
2990
2991 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
2992 {
2993         int i;
2994         float *vertex3f;
2995         float v[3];
2996         VectorSet(v, x, y, z);
2997         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
2998                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
2999                         break;
3000         if (i == mesh->numvertices)
3001         {
3002                 if (mesh->numvertices < mesh->maxvertices)
3003                 {
3004                         VectorCopy(v, vertex3f);
3005                         mesh->numvertices++;
3006                 }
3007                 return mesh->numvertices;
3008         }
3009         else
3010                 return i;
3011 }
3012
3013 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
3014 {
3015         int i;
3016         int *e, element[3];
3017         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
3018         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
3019         e = mesh->element3i + mesh->numtriangles * 3;
3020         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
3021         {
3022                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
3023                 if (mesh->numtriangles < mesh->maxtriangles)
3024                 {
3025                         *e++ = element[0];
3026                         *e++ = element[1];
3027                         *e++ = element[2];
3028                         mesh->numtriangles++;
3029                 }
3030                 element[1] = element[2];
3031         }
3032 }
3033
3034 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
3035 {
3036         int i;
3037         int *e, element[3];
3038         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
3039         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
3040         e = mesh->element3i + mesh->numtriangles * 3;
3041         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
3042         {
3043                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
3044                 if (mesh->numtriangles < mesh->maxtriangles)
3045                 {
3046                         *e++ = element[0];
3047                         *e++ = element[1];
3048                         *e++ = element[2];
3049                         mesh->numtriangles++;
3050                 }
3051                 element[1] = element[2];
3052         }
3053 }
3054
3055 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
3056 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
3057 {
3058         int planenum, planenum2;
3059         int w;
3060         int tempnumpoints;
3061         mplane_t *plane, *plane2;
3062         double maxdist;
3063         double temppoints[2][256*3];
3064         // figure out how large a bounding box we need to properly compute this brush
3065         maxdist = 0;
3066         for (w = 0;w < numplanes;w++)
3067                 maxdist = max(maxdist, planes[w].dist);
3068         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
3069         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
3070         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
3071         {
3072                 w = 0;
3073                 tempnumpoints = 4;
3074                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
3075                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
3076                 {
3077                         if (planenum2 == planenum)
3078                                 continue;
3079                         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);
3080                         w = !w;
3081                 }
3082                 if (tempnumpoints < 3)
3083                         continue;
3084                 // generate elements forming a triangle fan for this polygon
3085                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
3086         }
3087 }
3088
3089 static void R_DrawCollisionBrush(const colbrushf_t *brush)
3090 {
3091         int i;
3092         R_Mesh_VertexPointer(brush->points->v, 0, 0);
3093         i = (int)(((size_t)brush) / sizeof(colbrushf_t));
3094         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);
3095         GL_LockArrays(0, brush->numpoints);
3096         R_Mesh_Draw(0, brush->numpoints, brush->numtriangles, brush->elements, 0, 0);
3097         GL_LockArrays(0, 0);
3098 }
3099
3100 static void R_DrawCollisionSurface(const entity_render_t *ent, const msurface_t *surface)
3101 {
3102         int i;
3103         if (!surface->num_collisiontriangles)
3104                 return;
3105         R_Mesh_VertexPointer(surface->data_collisionvertex3f, 0, 0);
3106         i = (int)(((size_t)surface) / sizeof(msurface_t));
3107         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);
3108         GL_LockArrays(0, surface->num_collisionvertices);
3109         R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i, 0, 0);
3110         GL_LockArrays(0, 0);
3111 }
3112
3113 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)
3114 {
3115         texturelayer_t *layer;
3116         layer = t->currentlayers + t->currentnumlayers++;
3117         layer->type = type;
3118         layer->depthmask = depthmask;
3119         layer->blendfunc1 = blendfunc1;
3120         layer->blendfunc2 = blendfunc2;
3121         layer->texture = texture;
3122         layer->texmatrix = *matrix;
3123         layer->color[0] = r * r_view.colorscale;
3124         layer->color[1] = g * r_view.colorscale;
3125         layer->color[2] = b * r_view.colorscale;
3126         layer->color[3] = a;
3127 }
3128
3129 void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
3130 {
3131         int i;
3132         model_t *model = ent->model;
3133
3134         // switch to an alternate material if this is a q1bsp animated material
3135         {
3136                 texture_t *texture = t;
3137                 int s = ent->skinnum;
3138                 if ((unsigned int)s >= (unsigned int)model->numskins)
3139                         s = 0;
3140                 if (model->skinscenes)
3141                 {
3142                         if (model->skinscenes[s].framecount > 1)
3143                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
3144                         else
3145                                 s = model->skinscenes[s].firstframe;
3146                 }
3147                 if (s > 0)
3148                         t = t + s * model->num_surfaces;
3149                 if (t->animated)
3150                 {
3151                         // use an alternate animation if the entity's frame is not 0,
3152                         // and only if the texture has an alternate animation
3153                         if (ent->frame != 0 && t->anim_total[1])
3154                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.time * 5.0f) % t->anim_total[1]) : 0];
3155                         else
3156                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.time * 5.0f) % t->anim_total[0]) : 0];
3157                 }
3158                 texture->currentframe = t;
3159         }
3160
3161         // update currentskinframe to be a qw skin or animation frame
3162         if ((i = ent->entitynumber - 1) >= 0 && i < cl.maxclients)
3163         {
3164                 if (strcmp(r_qwskincache[i], cl.scores[i].qw_skin))
3165                 {
3166                         strlcpy(r_qwskincache[i], cl.scores[i].qw_skin, sizeof(r_qwskincache[i]));
3167                         Con_DPrintf("loading skins/%s\n", r_qwskincache[i]);
3168                         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);
3169                 }
3170                 t->currentskinframe = r_qwskincache_skinframe[i];
3171                 if (t->currentskinframe == NULL)
3172                         t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
3173         }
3174         else if (t->numskinframes >= 2)
3175                 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
3176         if (t->backgroundnumskinframes >= 2)
3177                 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - ent->frame2time)) % t->backgroundnumskinframes];
3178
3179         t->currentmaterialflags = t->basematerialflags;
3180         t->currentalpha = ent->alpha;
3181         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
3182                 t->currentalpha *= r_wateralpha.value;
3183         if (!(ent->flags & RENDER_LIGHT))
3184                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
3185         if (ent->effects & EF_ADDITIVE)
3186                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
3187         else if (t->currentalpha < 1)
3188                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
3189         if (ent->effects & EF_DOUBLESIDED)
3190                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
3191         if (ent->effects & EF_NODEPTHTEST)
3192                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
3193         if (ent->flags & RENDER_VIEWMODEL)
3194                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
3195         if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
3196                 t->currenttexmatrix = r_waterscrollmatrix;
3197         else
3198                 t->currenttexmatrix = identitymatrix;
3199         if (t->backgroundnumskinframes && !(t->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
3200                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
3201
3202         t->colormapping = VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f);
3203         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
3204         t->glosstexture = r_texture_white;
3205         t->backgroundbasetexture = t->backgroundnumskinframes ? ((!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base) : r_texture_white;
3206         t->backgroundglosstexture = r_texture_white;
3207         t->specularpower = r_shadow_glossexponent.value;
3208         // TODO: store reference values for these in the texture?
3209         t->specularscale = 0;
3210         if (r_shadow_gloss.integer > 0)
3211         {
3212                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
3213                 {
3214                         if (r_shadow_glossintensity.value > 0)
3215                         {
3216                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_black;
3217                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_black;
3218                                 t->specularscale = r_shadow_glossintensity.value;
3219                         }
3220                 }
3221                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
3222                         t->specularscale = r_shadow_gloss2intensity.value;
3223         }
3224
3225         t->currentnumlayers = 0;
3226         if (!(t->currentmaterialflags & MATERIALFLAG_NODRAW))
3227         {
3228                 if (!(t->currentmaterialflags & MATERIALFLAG_SKY))
3229                 {
3230                         int blendfunc1, blendfunc2, depthmask;
3231                         if (t->currentmaterialflags & MATERIALFLAG_ADD)
3232                         {
3233                                 blendfunc1 = GL_SRC_ALPHA;
3234                                 blendfunc2 = GL_ONE;
3235                         }
3236                         else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
3237                         {
3238                                 blendfunc1 = GL_SRC_ALPHA;
3239                                 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
3240                         }
3241                         else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
3242                         {
3243                                 blendfunc1 = t->customblendfunc[0];
3244                                 blendfunc2 = t->customblendfunc[1];
3245                         }
3246                         else
3247                         {
3248                                 blendfunc1 = GL_ONE;
3249                                 blendfunc2 = GL_ZERO;
3250                         }
3251                         depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
3252                         if (t->currentmaterialflags & (MATERIALFLAG_WATER | MATERIALFLAG_WALL))
3253                         {
3254                                 rtexture_t *currentbasetexture;
3255                                 int layerflags = 0;
3256                                 if (r_refdef.fogenabled && (t->currentmaterialflags & MATERIALFLAG_BLENDED))
3257                                         layerflags |= TEXTURELAYERFLAG_FOGDARKEN;
3258                                 currentbasetexture = (VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) < (1.0f / 1048576.0f) && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
3259                                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
3260                                 {
3261                                         // fullbright is not affected by r_refdef.lightmapintensity
3262                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, ent->colormod[0], ent->colormod[1], ent->colormod[2], t->currentalpha);
3263                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
3264                                                 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);
3265                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
3266                                                 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);
3267                                 }
3268                                 else
3269                                 {
3270                                         float colorscale;
3271                                         colorscale = 2;
3272                                         // q3bsp has no lightmap updates, so the lightstylevalue that
3273                                         // would normally be baked into the lightmap must be
3274                                         // applied to the color
3275                                         if (ent->model->type == mod_brushq3)
3276                                                 colorscale *= r_refdef.lightstylevalue[0] * (1.0f / 256.0f);
3277                                         colorscale *= r_refdef.lightmapintensity;
3278                                         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);
3279                                         if (r_ambient.value >= (1.0f/64.0f))
3280                                                 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);
3281                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
3282                                         {
3283                                                 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);
3284                                                 if (r_ambient.value >= (1.0f/64.0f))
3285                                                         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);
3286                                         }
3287                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
3288                                         {
3289                                                 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);
3290                                                 if (r_ambient.value >= (1.0f/64.0f))
3291                                                         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);
3292                                         }
3293                                 }
3294                                 if (t->currentskinframe->glow != NULL)
3295                                         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);
3296                                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
3297                                 {
3298                                         // if this is opaque use alpha blend which will darken the earlier
3299                                         // passes cheaply.
3300                                         //
3301                                         // if this is an alpha blended material, all the earlier passes
3302                                         // were darkened by fog already, so we only need to add the fog
3303                                         // color ontop through the fog mask texture
3304                                         //
3305                                         // if this is an additive blended material, all the earlier passes
3306                                         // were darkened by fog already, and we should not add fog color
3307                                         // (because the background was not darkened, there is no fog color
3308                                         // that was lost behind it).
3309                                         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);
3310                                 }
3311                         }
3312                 }
3313         }
3314 }
3315
3316 void R_UpdateAllTextureInfo(entity_render_t *ent)
3317 {
3318         int i;
3319         if (ent->model)
3320                 for (i = 0;i < ent->model->num_texturesperskin;i++)
3321                         R_UpdateTextureInfo(ent, ent->model->data_textures + i);
3322 }
3323
3324 int rsurface_array_size = 0;
3325 float *rsurface_array_modelvertex3f = NULL;
3326 float *rsurface_array_modelsvector3f = NULL;
3327 float *rsurface_array_modeltvector3f = NULL;
3328 float *rsurface_array_modelnormal3f = NULL;
3329 float *rsurface_array_deformedvertex3f = NULL;
3330 float *rsurface_array_deformedsvector3f = NULL;
3331 float *rsurface_array_deformedtvector3f = NULL;
3332 float *rsurface_array_deformednormal3f = NULL;
3333 float *rsurface_array_color4f = NULL;
3334 float *rsurface_array_texcoord3f = NULL;
3335
3336 void R_Mesh_ResizeArrays(int newvertices)
3337 {
3338         float *base;
3339         if (rsurface_array_size >= newvertices)
3340                 return;
3341         if (rsurface_array_modelvertex3f)
3342                 Mem_Free(rsurface_array_modelvertex3f);
3343         rsurface_array_size = (newvertices + 1023) & ~1023;
3344         base = (float *)Mem_Alloc(r_main_mempool, rsurface_array_size * sizeof(float[31]));
3345         rsurface_array_modelvertex3f     = base + rsurface_array_size * 0;
3346         rsurface_array_modelsvector3f    = base + rsurface_array_size * 3;
3347         rsurface_array_modeltvector3f    = base + rsurface_array_size * 6;
3348         rsurface_array_modelnormal3f     = base + rsurface_array_size * 9;
3349         rsurface_array_deformedvertex3f  = base + rsurface_array_size * 12;
3350         rsurface_array_deformedsvector3f = base + rsurface_array_size * 15;
3351         rsurface_array_deformedtvector3f = base + rsurface_array_size * 18;
3352         rsurface_array_deformednormal3f  = base + rsurface_array_size * 21;
3353         rsurface_array_texcoord3f        = base + rsurface_array_size * 24;
3354         rsurface_array_color4f           = base + rsurface_array_size * 27;
3355 }
3356
3357 float *rsurface_modelvertex3f;
3358 int rsurface_modelvertex3f_bufferobject;
3359 size_t rsurface_modelvertex3f_bufferoffset;
3360 float *rsurface_modelsvector3f;
3361 int rsurface_modelsvector3f_bufferobject;
3362 size_t rsurface_modelsvector3f_bufferoffset;
3363 float *rsurface_modeltvector3f;
3364 int rsurface_modeltvector3f_bufferobject;
3365 size_t rsurface_modeltvector3f_bufferoffset;
3366 float *rsurface_modelnormal3f;
3367 int rsurface_modelnormal3f_bufferobject;
3368 size_t rsurface_modelnormal3f_bufferoffset;
3369 float *rsurface_vertex3f;
3370 int rsurface_vertex3f_bufferobject;
3371 size_t rsurface_vertex3f_bufferoffset;
3372 float *rsurface_svector3f;
3373 int rsurface_svector3f_bufferobject;
3374 size_t rsurface_svector3f_bufferoffset;
3375 float *rsurface_tvector3f;
3376 int rsurface_tvector3f_bufferobject;
3377 size_t rsurface_tvector3f_bufferoffset;
3378 float *rsurface_normal3f;
3379 int rsurface_normal3f_bufferobject;
3380 size_t rsurface_normal3f_bufferoffset;
3381 float *rsurface_lightmapcolor4f;
3382 int rsurface_lightmapcolor4f_bufferobject;
3383 size_t rsurface_lightmapcolor4f_bufferoffset;
3384 vec3_t rsurface_modelorg;
3385 qboolean rsurface_generatedvertex;
3386 const entity_render_t *rsurface_entity;
3387 const model_t *rsurface_model;
3388 texture_t *rsurface_texture;
3389 qboolean rsurface_uselightmaptexture;
3390 rsurfmode_t rsurface_mode;
3391 int rsurface_lightmode; // 0 = lightmap or fullbright, 1 = color array from q3bsp, 2 = vertex shaded model
3392
3393 void RSurf_CleanUp(void)
3394 {
3395         CHECKGLERROR
3396         if (rsurface_mode == RSURFMODE_GLSL)
3397         {
3398                 qglUseProgramObjectARB(0);CHECKGLERROR
3399         }
3400         GL_AlphaTest(false);
3401         rsurface_mode = RSURFMODE_NONE;
3402         rsurface_uselightmaptexture = false;
3403         rsurface_texture = NULL;
3404 }
3405
3406 void RSurf_ActiveWorldEntity(void)
3407 {
3408         RSurf_CleanUp();
3409         rsurface_entity = r_refdef.worldentity;
3410         rsurface_model = r_refdef.worldmodel;
3411         if (rsurface_array_size < rsurface_model->surfmesh.num_vertices)
3412                 R_Mesh_ResizeArrays(rsurface_model->surfmesh.num_vertices);
3413         R_Mesh_Matrix(&identitymatrix);
3414         VectorCopy(r_view.origin, rsurface_modelorg);
3415         rsurface_modelvertex3f  = rsurface_model->surfmesh.data_vertex3f;
3416         rsurface_modelvertex3f_bufferobject = rsurface_model->surfmesh.vbo;
3417         rsurface_modelvertex3f_bufferoffset = rsurface_model->surfmesh.vbooffset_vertex3f;
3418         rsurface_modelsvector3f = rsurface_model->surfmesh.data_svector3f;
3419         rsurface_modelsvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3420         rsurface_modelsvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_svector3f;
3421         rsurface_modeltvector3f = rsurface_model->surfmesh.data_tvector3f;
3422         rsurface_modeltvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3423         rsurface_modeltvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_tvector3f;
3424         rsurface_modelnormal3f  = rsurface_model->surfmesh.data_normal3f;
3425         rsurface_modelnormal3f_bufferobject = rsurface_model->surfmesh.vbo;
3426         rsurface_modelnormal3f_bufferoffset = rsurface_model->surfmesh.vbooffset_normal3f;
3427         rsurface_generatedvertex = false;
3428         rsurface_vertex3f  = rsurface_modelvertex3f;
3429         rsurface_vertex3f_bufferobject = rsurface_modelvertex3f_bufferobject;
3430         rsurface_vertex3f_bufferoffset = rsurface_modelvertex3f_bufferoffset;
3431         rsurface_svector3f = rsurface_modelsvector3f;
3432         rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject;
3433         rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset;
3434         rsurface_tvector3f = rsurface_modeltvector3f;
3435         rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject;
3436         rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset;
3437         rsurface_normal3f  = rsurface_modelnormal3f;
3438         rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject;
3439         rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset;
3440 }
3441
3442 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
3443 {
3444         RSurf_CleanUp();
3445         rsurface_entity = ent;
3446         rsurface_model = ent->model;
3447         if (rsurface_array_size < rsurface_model->surfmesh.num_vertices)
3448                 R_Mesh_ResizeArrays(rsurface_model->surfmesh.num_vertices);
3449         R_Mesh_Matrix(&ent->matrix);
3450         Matrix4x4_Transform(&ent->inversematrix, r_view.origin, rsurface_modelorg);
3451         if (rsurface_model->surfmesh.isanimated && (rsurface_entity->frameblend[0].lerp != 1 || rsurface_entity->frameblend[0].frame != 0))
3452         {
3453                 if (wanttangents)
3454                 {
3455                         rsurface_modelvertex3f = rsurface_array_modelvertex3f;
3456                         rsurface_modelsvector3f = rsurface_array_modelsvector3f;
3457                         rsurface_modeltvector3f = rsurface_array_modeltvector3f;
3458                         rsurface_modelnormal3f = rsurface_array_modelnormal3f;
3459                         Mod_Alias_GetMesh_Vertices(rsurface_model, rsurface_entity->frameblend, rsurface_array_modelvertex3f, rsurface_array_modelnormal3f, rsurface_array_modelsvector3f, rsurface_array_modeltvector3f);
3460                 }
3461                 else if (wantnormals)
3462                 {
3463                         rsurface_modelvertex3f = rsurface_array_modelvertex3f;
3464                         rsurface_modelsvector3f = NULL;
3465                         rsurface_modeltvector3f = NULL;
3466                         rsurface_modelnormal3f = rsurface_array_modelnormal3f;
3467                         Mod_Alias_GetMesh_Vertices(rsurface_model, rsurface_entity->frameblend, rsurface_array_modelvertex3f, rsurface_array_modelnormal3f, NULL, NULL);
3468                 }
3469                 else
3470                 {
3471                         rsurface_modelvertex3f = rsurface_array_modelvertex3f;
3472                         rsurface_modelsvector3f = NULL;
3473                         rsurface_modeltvector3f = NULL;
3474                         rsurface_modelnormal3f = NULL;
3475                         Mod_Alias_GetMesh_Vertices(rsurface_model, rsurface_entity->frameblend, rsurface_array_modelvertex3f, NULL, NULL, NULL);
3476                 }
3477                 rsurface_modelvertex3f_bufferobject = 0;
3478                 rsurface_modelvertex3f_bufferoffset = 0;
3479                 rsurface_modelsvector3f_bufferobject = 0;
3480                 rsurface_modelsvector3f_bufferoffset = 0;
3481                 rsurface_modeltvector3f_bufferobject = 0;
3482                 rsurface_modeltvector3f_bufferoffset = 0;
3483                 rsurface_modelnormal3f_bufferobject = 0;
3484                 rsurface_modelnormal3f_bufferoffset = 0;
3485                 rsurface_generatedvertex = true;
3486         }
3487         else
3488         {
3489                 rsurface_modelvertex3f  = rsurface_model->surfmesh.data_vertex3f;
3490                 rsurface_modelvertex3f_bufferobject = rsurface_model->surfmesh.vbo;
3491                 rsurface_modelvertex3f_bufferoffset = rsurface_model->surfmesh.vbooffset_vertex3f;
3492                 rsurface_modelsvector3f = rsurface_model->surfmesh.data_svector3f;
3493                 rsurface_modelsvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3494                 rsurface_modelsvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_svector3f;
3495                 rsurface_modeltvector3f = rsurface_model->surfmesh.data_tvector3f;
3496                 rsurface_modeltvector3f_bufferobject = rsurface_model->surfmesh.vbo;
3497                 rsurface_modeltvector3f_bufferoffset = rsurface_model->surfmesh.vbooffset_tvector3f;
3498                 rsurface_modelnormal3f  = rsurface_model->surfmesh.data_normal3f;
3499                 rsurface_modelnormal3f_bufferobject = rsurface_model->surfmesh.vbo;
3500                 rsurface_modelnormal3f_bufferoffset = rsurface_model->surfmesh.vbooffset_normal3f;
3501                 rsurface_generatedvertex = false;
3502         }
3503         rsurface_vertex3f  = rsurface_modelvertex3f;
3504         rsurface_vertex3f_bufferobject = rsurface_modelvertex3f_bufferobject;
3505         rsurface_vertex3f_bufferoffset = rsurface_modelvertex3f_bufferoffset;
3506         rsurface_svector3f = rsurface_modelsvector3f;
3507         rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject;
3508         rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset;
3509         rsurface_tvector3f = rsurface_modeltvector3f;
3510         rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject;
3511         rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset;
3512         rsurface_normal3f  = rsurface_modelnormal3f;
3513         rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject;
3514         rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset;
3515 }
3516
3517 void RSurf_PrepareVerticesForBatch(qboolean generatenormals, qboolean generatetangents, int texturenumsurfaces, msurface_t **texturesurfacelist)
3518 {
3519         // 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
3520         if (rsurface_generatedvertex)
3521         {
3522                 if (rsurface_texture->textureflags & (Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
3523                         generatetangents = true;
3524                 if (generatetangents)
3525                         generatenormals = true;
3526                 if (generatenormals && !rsurface_modelnormal3f)
3527                 {
3528                         rsurface_normal3f = rsurface_modelnormal3f = rsurface_array_modelnormal3f;
3529                         rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject = 0;
3530                         rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset = 0;
3531                         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);
3532                 }
3533                 if (generatetangents && !rsurface_modelsvector3f)
3534                 {
3535                         rsurface_svector3f = rsurface_modelsvector3f = rsurface_array_modelsvector3f;
3536                         rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject = 0;
3537                         rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset = 0;
3538                         rsurface_tvector3f = rsurface_modeltvector3f = rsurface_array_modeltvector3f;
3539                         rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject = 0;
3540                         rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset = 0;
3541                         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);
3542                 }
3543         }
3544         // 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)
3545         if (rsurface_texture->textureflags & (Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
3546         {
3547                 int texturesurfaceindex;
3548                 float center[3], forward[3], right[3], up[3], v[4][3];
3549                 matrix4x4_t matrix1, imatrix1;
3550                 Matrix4x4_Transform(&rsurface_entity->inversematrix, r_view.forward, forward);
3551                 Matrix4x4_Transform(&rsurface_entity->inversematrix, r_view.right, right);
3552                 Matrix4x4_Transform(&rsurface_entity->inversematrix, r_view.up, up);
3553                 // make deformed versions of only the model vertices used by the specified surfaces
3554                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3555                 {
3556                         int i, j;
3557                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3558                         // a single autosprite surface can contain multiple sprites...
3559                         for (j = 0;j < surface->num_vertices - 3;j += 4)
3560                         {
3561                                 VectorClear(center);
3562                                 for (i = 0;i < 4;i++)
3563                                         VectorAdd(center, (rsurface_modelvertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
3564                                 VectorScale(center, 0.25f, center);
3565                                 if (rsurface_texture->textureflags & Q3TEXTUREFLAG_AUTOSPRITE2)
3566                                 {
3567                                         forward[0] = rsurface_modelorg[0] - center[0];
3568                                         forward[1] = rsurface_modelorg[1] - center[1];
3569                                         forward[2] = 0;
3570                                         VectorNormalize(forward);
3571                                         right[0] = forward[1];
3572                                         right[1] = -forward[0];
3573                                         right[2] = 0;
3574                                         VectorSet(up, 0, 0, 1);
3575                                 }
3576                                 // FIXME: calculate vectors from triangle edges instead of using texture vectors as an easy way out?
3577                                 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);
3578                                 Matrix4x4_Invert_Simple(&imatrix1, &matrix1);
3579                                 for (i = 0;i < 4;i++)
3580                                         Matrix4x4_Transform(&imatrix1, (rsurface_modelvertex3f + 3 * surface->num_firstvertex) + (j+i)*3, v[i]);
3581                                 for (i = 0;i < 4;i++)
3582                                         VectorMAMAMAM(1, center, v[i][0], forward, v[i][1], right, v[i][2], up, rsurface_array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
3583                         }
3584                         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);
3585                         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);
3586                 }
3587                 rsurface_vertex3f = rsurface_array_deformedvertex3f;
3588                 rsurface_vertex3f_bufferobject = 0;
3589                 rsurface_vertex3f_bufferoffset = 0;
3590                 rsurface_svector3f = rsurface_array_deformedsvector3f;
3591                 rsurface_svector3f_bufferobject = 0;
3592                 rsurface_svector3f_bufferoffset = 0;
3593                 rsurface_tvector3f = rsurface_array_deformedtvector3f;
3594                 rsurface_tvector3f_bufferobject = 0;
3595                 rsurface_tvector3f_bufferoffset = 0;
3596                 rsurface_normal3f = rsurface_array_deformednormal3f;
3597                 rsurface_normal3f_bufferobject = 0;
3598                 rsurface_normal3f_bufferoffset = 0;
3599         }
3600         else
3601         {
3602                 rsurface_vertex3f  = rsurface_modelvertex3f;
3603                 rsurface_vertex3f_bufferobject = rsurface_modelvertex3f_bufferobject;
3604                 rsurface_vertex3f_bufferoffset = rsurface_modelvertex3f_bufferoffset;
3605                 rsurface_svector3f = rsurface_modelsvector3f;
3606                 rsurface_svector3f_bufferobject = rsurface_modelsvector3f_bufferobject;
3607                 rsurface_svector3f_bufferoffset = rsurface_modelsvector3f_bufferoffset;
3608                 rsurface_tvector3f = rsurface_modeltvector3f;
3609                 rsurface_tvector3f_bufferobject = rsurface_modeltvector3f_bufferobject;
3610                 rsurface_tvector3f_bufferoffset = rsurface_modeltvector3f_bufferoffset;
3611                 rsurface_normal3f  = rsurface_modelnormal3f;
3612                 rsurface_normal3f_bufferobject = rsurface_modelnormal3f_bufferobject;
3613                 rsurface_normal3f_bufferoffset = rsurface_modelnormal3f_bufferoffset;
3614         }
3615         R_Mesh_VertexPointer(rsurface_vertex3f, rsurface_vertex3f_bufferobject, rsurface_vertex3f_bufferoffset);
3616 }
3617
3618 void RSurf_DrawBatch_Simple(int texturenumsurfaces, msurface_t **texturesurfacelist)
3619 {
3620         int i, j;
3621         const msurface_t *surface = texturesurfacelist[0];
3622         const msurface_t *surface2;
3623         int firstvertex;
3624         int endvertex;
3625         int numvertices;
3626         int numtriangles;
3627         // TODO: lock all array ranges before render, rather than on each surface
3628         if (texturenumsurfaces == 1)
3629         {
3630                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
3631                 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));
3632         }
3633         else if (r_batchmode.integer == 2)
3634         {
3635                 #define MAXBATCHTRIANGLES 4096
3636                 int batchtriangles = 0;
3637                 int batchelements[MAXBATCHTRIANGLES*3];
3638                 for (i = 0;i < texturenumsurfaces;i = j)
3639                 {
3640                         surface = texturesurfacelist[i];
3641                         j = i + 1;
3642                         if (surface->num_triangles > MAXBATCHTRIANGLES)
3643                         {
3644                                 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));
3645                                 continue;
3646                         }
3647                         memcpy(batchelements, rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
3648                         batchtriangles = surface->num_triangles;
3649                         firstvertex = surface->num_firstvertex;
3650                         endvertex = surface->num_firstvertex + surface->num_vertices;
3651                         for (;j < texturenumsurfaces;j++)
3652                         {
3653                                 surface2 = texturesurfacelist[j];
3654                                 if (batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
3655                                         break;
3656                                 memcpy(batchelements + batchtriangles * 3, rsurface_model->surfmesh.data_element3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
3657                                 batchtriangles += surface2->num_triangles;
3658                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
3659                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
3660                         }
3661                         surface2 = texturesurfacelist[j-1];
3662                         numvertices = endvertex - firstvertex;
3663                         R_Mesh_Draw(firstvertex, numvertices, batchtriangles, batchelements, 0, 0);
3664                 }
3665         }
3666         else if (r_batchmode.integer == 1)
3667         {
3668                 for (i = 0;i < texturenumsurfaces;i = j)
3669                 {
3670                         surface = texturesurfacelist[i];
3671                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
3672                                 if (texturesurfacelist[j] != surface2)
3673                                         break;
3674                         surface2 = texturesurfacelist[j-1];
3675                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
3676                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
3677                         GL_LockArrays(surface->num_firstvertex, numvertices);
3678                         R_Mesh_Draw(surface->num_firstvertex, numvertices, numtriangles, (rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle), rsurface_model->surfmesh.ebo, (sizeof(int[3]) * surface->num_firsttriangle));
3679                 }
3680         }
3681         else
3682         {
3683                 for (i = 0;i < texturenumsurfaces;i++)
3684                 {
3685                         surface = texturesurfacelist[i];
3686                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
3687                         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));
3688                 }
3689         }
3690 }
3691
3692 static void RSurf_DrawBatch_WithLightmapSwitching(int texturenumsurfaces, msurface_t **texturesurfacelist, int lightmaptexunit, int deluxemaptexunit)
3693 {
3694         int i;
3695         int j;
3696         const msurface_t *surface = texturesurfacelist[0];
3697         const msurface_t *surface2;
3698         int firstvertex;
3699         int endvertex;
3700         int numvertices;
3701         int numtriangles;
3702         // TODO: lock all array ranges before render, rather than on each surface
3703         if (texturenumsurfaces == 1)
3704         {
3705                 R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
3706                 if (deluxemaptexunit >= 0)
3707                         R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
3708                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
3709                 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));
3710         }
3711         else if (r_batchmode.integer == 2)
3712         {
3713                 #define MAXBATCHTRIANGLES 4096
3714                 int batchtriangles = 0;
3715                 int batchelements[MAXBATCHTRIANGLES*3];
3716                 for (i = 0;i < texturenumsurfaces;i = j)
3717                 {
3718                         surface = texturesurfacelist[i];
3719                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
3720                         if (deluxemaptexunit >= 0)
3721                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
3722                         j = i + 1;
3723                         if (surface->num_triangles > MAXBATCHTRIANGLES)
3724                         {
3725                                 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));
3726                                 continue;
3727                         }
3728                         memcpy(batchelements, rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
3729                         batchtriangles = surface->num_triangles;
3730                         firstvertex = surface->num_firstvertex;
3731                         endvertex = surface->num_firstvertex + surface->num_vertices;
3732                         for (;j < texturenumsurfaces;j++)
3733                         {
3734                                 surface2 = texturesurfacelist[j];
3735                                 if (surface2->lightmaptexture != surface->lightmaptexture || batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
3736                                         break;
3737                                 memcpy(batchelements + batchtriangles * 3, rsurface_model->surfmesh.data_element3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
3738                                 batchtriangles += surface2->num_triangles;
3739                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
3740                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
3741                         }
3742                         surface2 = texturesurfacelist[j-1];
3743                         numvertices = endvertex - firstvertex;
3744                         R_Mesh_Draw(firstvertex, numvertices, batchtriangles, batchelements, 0, 0);
3745                 }
3746         }
3747         else if (r_batchmode.integer == 1)
3748         {
3749 #if 0
3750                 Con_Printf("%s batch sizes ignoring lightmap:", rsurface_texture->name);
3751                 for (i = 0;i < texturenumsurfaces;i = j)
3752                 {
3753                         surface = texturesurfacelist[i];
3754                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
3755                                 if (texturesurfacelist[j] != surface2)
3756                                         break;
3757                         Con_Printf(" %i", j - i);
3758                 }
3759                 Con_Printf("\n");
3760                 Con_Printf("%s batch sizes honoring lightmap:", rsurface_texture->name);
3761 #endif
3762                 for (i = 0;i < texturenumsurfaces;i = j)
3763                 {
3764                         surface = texturesurfacelist[i];
3765                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
3766                         if (deluxemaptexunit >= 0)
3767                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
3768                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
3769                                 if (texturesurfacelist[j] != surface2 || texturesurfacelist[j]->lightmaptexture != surface->lightmaptexture)
3770                                         break;
3771 #if 0
3772                         Con_Printf(" %i", j - i);
3773 #endif
3774                         surface2 = texturesurfacelist[j-1];
3775                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
3776                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
3777                         GL_LockArrays(surface->num_firstvertex, numvertices);
3778                         R_Mesh_Draw(surface->num_firstvertex, numvertices, numtriangles, (rsurface_model->surfmesh.data_element3i + 3 * surface->num_firsttriangle), rsurface_model->surfmesh.ebo, (sizeof(int[3]) * surface->num_firsttriangle));
3779                 }
3780 #if 0
3781                 Con_Printf("\n");
3782 #endif
3783         }
3784         else
3785         {
3786                 for (i = 0;i < texturenumsurfaces;i++)
3787                 {
3788                         surface = texturesurfacelist[i];
3789                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
3790                         if (deluxemaptexunit >= 0)
3791                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
3792                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
3793                         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));
3794                 }
3795         }
3796 }
3797
3798 static void RSurf_DrawBatch_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
3799 {
3800         int j;
3801         int texturesurfaceindex;
3802         if (r_showsurfaces.integer == 2)
3803         {
3804                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3805                 {
3806                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3807                         for (j = 0;j < surface->num_triangles;j++)
3808                         {
3809                                 float f = ((j + surface->num_firsttriangle) & 31) * (1.0f / 31.0f) * r_view.colorscale;
3810                                 GL_Color(f, f, f, 1);
3811                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, 1, (rsurface_model->surfmesh.data_element3i + 3 * (j + surface->num_firsttriangle)), rsurface_model->surfmesh.ebo, (sizeof(int[3]) * (j + surface->num_firsttriangle)));
3812                         }
3813                 }
3814         }
3815         else
3816         {
3817                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3818                 {
3819                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3820                         int k = (int)(((size_t)surface) / sizeof(msurface_t));
3821                         GL_Color((k & 15) * (1.0f / 16.0f) * r_view.colorscale, ((k >> 4) & 15) * (1.0f / 16.0f) * r_view.colorscale, ((k >> 8) & 15) * (1.0f / 16.0f) * r_view.colorscale, 1);
3822                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
3823                         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));
3824                 }
3825         }
3826 }
3827
3828 static void RSurf_DrawBatch_GL11_ApplyFog(int texturenumsurfaces, msurface_t **texturesurfacelist)
3829 {
3830         int texturesurfaceindex;
3831         int i;
3832         float f;
3833         float *v, *c, *c2;
3834         if (rsurface_lightmapcolor4f)
3835         {
3836                 // generate color arrays for the surfaces in this list
3837                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3838                 {
3839                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3840                         for (i = 0, v = (rsurface_vertex3f + 3 * surface->num_firstvertex), c = (rsurface_lightmapcolor4f + 4 * surface->num_firstvertex), c2 = (rsurface_array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c += 4, c2 += 4)
3841                         {
3842                                 f = FogPoint_Model(v);
3843                                 c2[0] = c[0] * f;
3844                                 c2[1] = c[1] * f;
3845                                 c2[2] = c[2] * f;
3846                                 c2[3] = c[3];
3847                         }
3848                 }
3849         }
3850         else
3851         {
3852                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3853                 {
3854                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3855                         for (i = 0, v = (rsurface_vertex3f + 3 * surface->num_firstvertex), c2 = (rsurface_array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c2 += 4)
3856                         {
3857                                 f = FogPoint_Model(v);
3858                                 c2[0] = f;
3859                                 c2[1] = f;
3860                                 c2[2] = f;
3861                                 c2[3] = 1;
3862                         }
3863                 }
3864         }
3865         rsurface_lightmapcolor4f = rsurface_array_color4f;
3866         rsurface_lightmapcolor4f_bufferobject = 0;
3867         rsurface_lightmapcolor4f_bufferoffset = 0;
3868 }
3869
3870 static void RSurf_DrawBatch_GL11_ApplyColor(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a)
3871 {
3872         int texturesurfaceindex;
3873         int i;
3874         float *c, *c2;
3875         if (!rsurface_lightmapcolor4f)
3876                 return;
3877         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3878         {
3879                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3880                 for (i = 0, c = (rsurface_lightmapcolor4f + 4 * surface->num_firstvertex), c2 = (rsurface_array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, c += 4, c2 += 4)
3881                 {
3882                         c2[0] = c[0] * r;
3883                         c2[1] = c[1] * g;
3884                         c2[2] = c[2] * b;
3885                         c2[3] = c[3] * a;
3886                 }
3887         }
3888         rsurface_lightmapcolor4f = rsurface_array_color4f;
3889         rsurface_lightmapcolor4f_bufferobject = 0;
3890         rsurface_lightmapcolor4f_bufferoffset = 0;
3891 }
3892
3893 static void RSurf_DrawBatch_GL11_Lightmap(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
3894 {
3895         // TODO: optimize
3896         rsurface_lightmapcolor4f = NULL;
3897         rsurface_lightmapcolor4f_bufferobject = 0;
3898         rsurface_lightmapcolor4f_bufferoffset = 0;
3899         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
3900         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
3901         R_Mesh_ColorPointer(rsurface_lightmapcolor4f, rsurface_lightmapcolor4f_bufferobject, rsurface_lightmapcolor4f_bufferoffset);
3902         GL_Color(r, g, b, a);
3903         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist, 0, -1);
3904 }
3905
3906 static void RSurf_DrawBatch_GL11_Unlit(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
3907 {
3908         // TODO: optimize applyfog && applycolor case
3909         // just apply fog if necessary, and tint the fog color array if necessary
3910         rsurface_lightmapcolor4f = NULL;
3911         rsurface_lightmapcolor4f_bufferobject = 0;
3912         rsurface_lightmapcolor4f_bufferoffset = 0;
3913         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
3914         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
3915         R_Mesh_ColorPointer(rsurface_lightmapcolor4f, rsurface_lightmapcolor4f_bufferobject, rsurface_lightmapcolor4f_bufferoffset);
3916         GL_Color(r, g, b, a);
3917         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
3918 }
3919
3920 static void RSurf_DrawBatch_GL11_VertexColor(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
3921 {
3922         int texturesurfaceindex;
3923         int i;
3924         float *c;
3925         // TODO: optimize
3926         if (texturesurfacelist[0]->lightmapinfo && texturesurfacelist[0]->lightmapinfo->stainsamples)
3927         {
3928                 // generate color arrays for the surfaces in this list
3929                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
3930                 {
3931                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
3932                         for (i = 0, c = rsurface_array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
3933                         {
3934                                 if (surface->lightmapinfo->samples)
3935                                 {
3936                                         const unsigned char *lm = surface->lightmapinfo->samples + (rsurface_model->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i];
3937                                         float scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[0]] * (1.0f / 32768.0f);
3938                                         VectorScale(lm, scale, c);
3939                                         if (surface->lightmapinfo->styles[1] != 255)
3940                                         {
3941                                                 int size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
3942                                                 lm += size3;
3943                                                 scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[1]] * (1.0f / 32768.0f);
3944                                                 VectorMA(c, scale, lm, c);
3945                                                 if (surface->lightmapinfo->styles[2] != 255)
3946                                                 {
3947                                                         lm += size3;
3948                                                         scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[2]] * (1.0f / 32768.0f);
3949                                                         VectorMA(c, scale, lm, c);
3950                                                         if (surface->lightmapinfo->styles[3] != 255)
3951                                                         {
3952                                                                 lm += size3;
3953                                                                 scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[3]] * (1.0f / 32768.0f);
3954                                                                 VectorMA(c, scale, lm, c);
3955                                                         }
3956                                                 }
3957                                         }
3958                                 }
3959                                 else
3960                                         VectorClear(c);
3961                                 c[3] = 1;
3962                         }
3963                 }
3964                 rsurface_lightmapcolor4f = rsurface_array_color4f;
3965                 rsurface_lightmapcolor4f_bufferobject = 0;
3966                 rsurface_lightmapcolor4f_bufferoffset = 0;
3967         }
3968         else
3969         {
3970                 rsurface_lightmapcolor4f = rsurface_model->surfmesh.data_lightmapcolor4f;
3971                 rsurface_lightmapcolor4f_bufferobject = rsurface_model->surfmesh.vbo;
3972                 rsurface_lightmapcolor4f_bufferoffset = rsurface_model->surfmesh.vbooffset_lightmapcolor4f;
3973         }
3974         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
3975         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
3976         R_Mesh_ColorPointer(rsurface_lightmapcolor4f, rsurface_lightmapcolor4f_bufferobject, rsurface_lightmapcolor4f_bufferoffset);
3977         GL_Color(r, g, b, a);
3978         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
3979 }
3980
3981 static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
3982 {
3983         int texturesurfaceindex;
3984         int i;
3985         float f;
3986         float *v, *c, *c2;
3987         vec3_t ambientcolor;
3988         vec3_t diffusecolor;
3989         vec3_t lightdir;
3990         // TODO: optimize
3991         // model lighting
3992         VectorCopy(rsurface_entity->modellight_lightdir, lightdir);
3993         ambientcolor[0] = rsurface_entity->modellight_ambient[0] * r * 0.5f;
3994         ambientcolor[1] = rsurface_entity->modellight_ambient[1] * g * 0.5f;
3995         ambientcolor[2] = rsurface_entity->modellight_ambient[2] * b * 0.5f;
3996         diffusecolor[0] = rsurface_entity->modellight_diffuse[0] * r * 0.5f;
3997         diffusecolor[1] = rsurface_entity->modellight_diffuse[1] * g * 0.5f;
3998         diffusecolor[2] = rsurface_entity->modellight_diffuse[2] * b * 0.5f;
3999         if (VectorLength2(diffusecolor) > 0)
4000         {
4001                 // generate color arrays for the surfaces in this list
4002                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4003                 {
4004                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4005                         int numverts = surface->num_vertices;
4006                         v = rsurface_vertex3f + 3 * surface->num_firstvertex;
4007                         c2 = rsurface_normal3f + 3 * surface->num_firstvertex;
4008                         c = rsurface_array_color4f + 4 * surface->num_firstvertex;
4009                         // q3-style directional shading
4010                         for (i = 0;i < numverts;i++, v += 3, c2 += 3, c += 4)
4011                         {
4012                                 if ((f = DotProduct(c2, lightdir)) > 0)
4013                                         VectorMA(ambientcolor, f, diffusecolor, c);
4014                                 else
4015                                         VectorCopy(ambientcolor, c);
4016                                 c[3] = a;
4017                         }
4018                 }
4019                 r = 1;
4020                 g = 1;
4021                 b = 1;
4022                 a = 1;
4023                 applycolor = false;
4024                 rsurface_lightmapcolor4f = rsurface_array_color4f;
4025                 rsurface_lightmapcolor4f_bufferobject = 0;
4026                 rsurface_lightmapcolor4f_bufferoffset = 0;
4027         }
4028         else
4029         {
4030                 r = ambientcolor[0];
4031                 g = ambientcolor[1];
4032                 b = ambientcolor[2];
4033                 rsurface_lightmapcolor4f = NULL;
4034                 rsurface_lightmapcolor4f_bufferobject = 0;
4035                 rsurface_lightmapcolor4f_bufferoffset = 0;
4036         }
4037         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
4038         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
4039         R_Mesh_ColorPointer(rsurface_lightmapcolor4f, rsurface_lightmapcolor4f_bufferobject, rsurface_lightmapcolor4f_bufferoffset);
4040         GL_Color(r, g, b, a);
4041         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
4042 }
4043
4044 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
4045 {
4046         GL_DepthRange(0, (rsurface_texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
4047         GL_DepthTest(!(rsurface_texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
4048         GL_CullFace((rsurface_texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
4049         if (rsurface_mode != RSURFMODE_SHOWSURFACES)
4050         {
4051                 rsurface_mode = RSURFMODE_SHOWSURFACES;
4052                 GL_DepthMask(true);
4053                 GL_BlendFunc(GL_ONE, GL_ZERO);
4054                 R_Mesh_ColorPointer(NULL, 0, 0);
4055                 R_Mesh_ResetTextureState();
4056         }
4057         RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
4058         RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
4059 }
4060
4061 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, msurface_t **texturesurfacelist)
4062 {
4063         // transparent sky would be ridiculous
4064         if ((rsurface_texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
4065                 return;
4066         if (rsurface_mode != RSURFMODE_SKY)
4067         {
4068                 if (rsurface_mode == RSURFMODE_GLSL)
4069                 {
4070                         qglUseProgramObjectARB(0);CHECKGLERROR
4071                 }
4072                 rsurface_mode = RSURFMODE_SKY;
4073         }
4074         if (skyrendernow)
4075         {
4076                 skyrendernow = false;
4077                 R_Sky();
4078                 // restore entity matrix
4079                 R_Mesh_Matrix(&rsurface_entity->matrix);
4080         }
4081         GL_DepthRange(0, (rsurface_texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
4082         GL_DepthTest(!(rsurface_texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
4083         GL_CullFace((rsurface_texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
4084         GL_DepthMask(true);
4085         // LordHavoc: HalfLife maps have freaky skypolys so don't use
4086         // skymasking on them, and Quake3 never did sky masking (unlike
4087         // software Quake and software Quake2), so disable the sky masking
4088         // in Quake3 maps as it causes problems with q3map2 sky tricks,
4089         // and skymasking also looks very bad when noclipping outside the
4090         // level, so don't use it then either.
4091         if (rsurface_model->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_viewcache.world_novis)
4092         {
4093                 GL_Color(r_refdef.fogcolor[0] * r_view.colorscale, r_refdef.fogcolor[1] * r_view.colorscale, r_refdef.fogcolor[2] * r_view.colorscale, 1);
4094                 R_Mesh_ColorPointer(NULL, 0, 0);
4095                 R_Mesh_ResetTextureState();
4096                 if (skyrendermasked)
4097                 {
4098                         // depth-only (masking)
4099                         GL_ColorMask(0,0,0,0);
4100                         // just to make sure that braindead drivers don't draw
4101                         // anything despite that colormask...
4102                         GL_BlendFunc(GL_ZERO, GL_ONE);
4103                 }
4104                 else
4105                 {
4106                         // fog sky
4107                         GL_BlendFunc(GL_ONE, GL_ZERO);
4108                 }
4109                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
4110                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
4111                 if (skyrendermasked)
4112                         GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
4113         }
4114 }
4115
4116 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, msurface_t **texturesurfacelist)
4117 {
4118         if (rsurface_mode != RSURFMODE_GLSL)
4119         {
4120                 rsurface_mode = RSURFMODE_GLSL;
4121                 R_Mesh_ResetTextureState();
4122         }
4123
4124         R_SetupSurfaceShader(vec3_origin, rsurface_lightmode == 2, 1, 1, rsurface_texture->specularscale);
4125         if (!r_glsl_permutation)
4126                 return;
4127
4128         if (rsurface_lightmode == 2)
4129                 RSurf_PrepareVerticesForBatch(true, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
4130         else
4131                 RSurf_PrepareVerticesForBatch(r_glsl_permutation->loc_Texture_Normal >= 0, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
4132         R_Mesh_TexCoordPointer(0, 2, rsurface_model->surfmesh.data_texcoordtexture2f, rsurface_model->surfmesh.vbo, rsurface_model->surfmesh.vbooffset_texcoordtexture2f);
4133         R_Mesh_TexCoordPointer(1, 3, rsurface_svector3f, rsurface_svector3f_bufferobject, rsurface_svector3f_bufferoffset);
4134         R_Mesh_TexCoordPointer(2, 3, rsurface_tvector3f, rsurface_tvector3f_bufferobject, rsurface_tvector3f_bufferoffset);
4135         R_Mesh_TexCoordPointer(3, 3, rsurface_normal3f, rsurface_normal3f_bufferobject, rsurface_normal3f_bufferoffset);
4136         R_Mesh_TexCoordPointer(4, 2, rsurface_model->surfmesh.data_texcoordlightmap2f, rsurface_model->surfmesh.vbo, rsurface_model->surfmesh.vbooffset_texcoordlightmap2f);
4137
4138         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4139         {
4140                 R_Mesh_TexBind(7, R_GetTexture(r_texture_white));
4141                 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0)
4142                         R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
4143                 R_Mesh_ColorPointer(NULL, 0, 0);
4144         }
4145         else if (rsurface_uselightmaptexture)
4146         {
4147                 R_Mesh_TexBind(7, R_GetTexture(texturesurfacelist[0]->lightmaptexture));
4148                 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0)
4149                         R_Mesh_TexBind(8, R_GetTexture(texturesurfacelist[0]->deluxemaptexture));
4150                 R_Mesh_ColorPointer(NULL, 0, 0);
4151         }
4152         else
4153         {
4154                 R_Mesh_TexBind(7, R_GetTexture(r_texture_white));
4155                 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0)
4156                         R_Mesh_TexBind(8, R_GetTexture(r_texture_blanknormalmap));
4157                 R_Mesh_ColorPointer(rsurface_model->surfmesh.data_lightmapcolor4f, rsurface_model->surfmesh.vbo, rsurface_model->surfmesh.vbooffset_lightmapcolor4f);
4158         }
4159
4160         if (rsurface_uselightmaptexture && !(rsurface_texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
4161                 RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist, 7, r_glsl_permutation->loc_Texture_Deluxemap >= 0 ? 8 : -1);
4162         else
4163                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
4164         if (rsurface_texture->backgroundnumskinframes && !(rsurface_texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED))
4165         {
4166         }
4167 }
4168
4169 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, msurface_t **texturesurfacelist)
4170 {
4171         // OpenGL 1.3 path - anything not completely ancient
4172         int texturesurfaceindex;
4173         qboolean applycolor;
4174         qboolean applyfog;
4175         rmeshstate_t m;
4176         int layerindex;
4177         const texturelayer_t *layer;
4178         if (rsurface_mode != RSURFMODE_MULTIPASS)
4179                 rsurface_mode = RSURFMODE_MULTIPASS;
4180         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
4181         for (layerindex = 0, layer = rsurface_texture->currentlayers;layerindex < rsurface_texture->currentnumlayers;layerindex++, layer++)
4182         {
4183                 vec4_t layercolor;
4184                 int layertexrgbscale;
4185                 if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4186                 {
4187                         if (layerindex == 0)
4188                                 GL_AlphaTest(true);
4189                         else
4190                         {
4191                                 GL_AlphaTest(false);
4192                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
4193                         }
4194                 }
4195                 GL_DepthMask(layer->depthmask);
4196                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
4197                 if ((layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2) && (gl_combine.integer || layer->depthmask))
4198                 {
4199                         layertexrgbscale = 4;
4200                         VectorScale(layer->color, 0.25f, layercolor);
4201                 }
4202                 else if ((layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1) && (gl_combine.integer || layer->depthmask))
4203                 {
4204                         layertexrgbscale = 2;
4205                         VectorScale(layer->color, 0.5f, layercolor);
4206                 }
4207                 else
4208                 {
4209                         layertexrgbscale = 1;
4210                         VectorScale(layer->color, 1.0f, layercolor);
4211                 }
4212                 layercolor[3] = layer->color[3];
4213                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
4214                 R_Mesh_ColorPointer(NULL, 0, 0);
4215                 applyfog = (layer->flags & TEXTURELAYERFLAG_FOGDARKEN) != 0;
4216                 switch (layer->type)
4217                 {
4218                 case TEXTURELAYERTYPE_LITTEXTURE:
4219                         memset(&m, 0, sizeof(m));
4220                         m.tex[0] = R_GetTexture(r_texture_white);
4221                         m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordlightmap2f;
4222                         m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4223                         m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordlightmap2f;
4224                         m.tex[1] = R_GetTexture(layer->texture);
4225                         m.texmatrix[1] = layer->texmatrix;
4226                         m.texrgbscale[1] = layertexrgbscale;
4227                         m.pointer_texcoord[1] = rsurface_model->surfmesh.data_texcoordtexture2f;
4228                         m.pointer_texcoord_bufferobject[1] = rsurface_model->surfmesh.vbo;
4229                         m.pointer_texcoord_bufferoffset[1] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4230                         R_Mesh_TextureState(&m);
4231                         if (rsurface_lightmode == 2)
4232                                 RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
4233                         else if (rsurface_uselightmaptexture)
4234                                 RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
4235                         else
4236                                 RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
4237                         break;
4238                 case TEXTURELAYERTYPE_TEXTURE:
4239                         memset(&m, 0, sizeof(m));
4240                         m.tex[0] = R_GetTexture(layer->texture);
4241                         m.texmatrix[0] = layer->texmatrix;
4242                         m.texrgbscale[0] = layertexrgbscale;
4243                         m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
4244                         m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4245                         m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4246                         R_Mesh_TextureState(&m);
4247                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
4248                         break;
4249                 case TEXTURELAYERTYPE_FOG:
4250                         memset(&m, 0, sizeof(m));
4251                         m.texrgbscale[0] = layertexrgbscale;
4252                         if (layer->texture)
4253                         {
4254                                 m.tex[0] = R_GetTexture(layer->texture);
4255                                 m.texmatrix[0] = layer->texmatrix;
4256                                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
4257                                 m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4258                                 m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4259                         }
4260                         R_Mesh_TextureState(&m);
4261                         // generate a color array for the fog pass
4262                         R_Mesh_ColorPointer(rsurface_array_color4f, 0, 0);
4263                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4264                         {
4265                                 int i;
4266                                 float f, *v, *c;
4267                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4268                                 for (i = 0, v = (rsurface_vertex3f + 3 * surface->num_firstvertex), c = (rsurface_array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c += 4)
4269                                 {
4270                                         f = 1 - FogPoint_Model(v);
4271                                         c[0] = layercolor[0];
4272                                         c[1] = layercolor[1];
4273                                         c[2] = layercolor[2];
4274                                         c[3] = f * layercolor[3];
4275                                 }
4276                         }
4277                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
4278                         break;
4279                 default:
4280                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
4281                 }
4282                 GL_LockArrays(0, 0);
4283         }
4284         CHECKGLERROR
4285         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4286         {
4287                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
4288                 GL_AlphaTest(false);
4289         }
4290 }
4291
4292 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, msurface_t **texturesurfacelist)
4293 {
4294         // OpenGL 1.1 - crusty old voodoo path
4295         int texturesurfaceindex;
4296         qboolean applyfog;
4297         rmeshstate_t m;
4298         int layerindex;
4299         const texturelayer_t *layer;
4300         if (rsurface_mode != RSURFMODE_MULTIPASS)
4301                 rsurface_mode = RSURFMODE_MULTIPASS;
4302         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
4303         for (layerindex = 0, layer = rsurface_texture->currentlayers;layerindex < rsurface_texture->currentnumlayers;layerindex++, layer++)
4304         {
4305                 if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4306                 {
4307                         if (layerindex == 0)
4308                                 GL_AlphaTest(true);
4309                         else
4310                         {
4311                                 GL_AlphaTest(false);
4312                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
4313                         }
4314                 }
4315                 GL_DepthMask(layer->depthmask);
4316                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
4317                 R_Mesh_ColorPointer(NULL, 0, 0);
4318                 applyfog = (layer->flags & TEXTURELAYERFLAG_FOGDARKEN) != 0;
4319                 switch (layer->type)
4320                 {
4321                 case TEXTURELAYERTYPE_LITTEXTURE:
4322                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
4323                         {
4324                                 // two-pass lit texture with 2x rgbscale
4325                                 // first the lightmap pass
4326                                 memset(&m, 0, sizeof(m));
4327                                 m.tex[0] = R_GetTexture(r_texture_white);
4328                                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordlightmap2f;
4329                                 m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4330                                 m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordlightmap2f;
4331                                 R_Mesh_TextureState(&m);
4332                                 if (rsurface_lightmode == 2)
4333                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
4334                                 else if (rsurface_uselightmaptexture)
4335                                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
4336                                 else
4337                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
4338                                 GL_LockArrays(0, 0);
4339                                 // then apply the texture to it
4340                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
4341                                 memset(&m, 0, sizeof(m));
4342                                 m.tex[0] = R_GetTexture(layer->texture);
4343                                 m.texmatrix[0] = layer->texmatrix;
4344                                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
4345                                 m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4346                                 m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4347                                 R_Mesh_TextureState(&m);
4348                                 RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layer->color[0] * 0.5f, layer->color[1] * 0.5f, layer->color[2] * 0.5f, layer->color[3], layer->color[0] != 2 || layer->color[1] != 2 || layer->color[2] != 2 || layer->color[3] != 1, false);
4349                         }
4350                         else
4351                         {
4352                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
4353                                 memset(&m, 0, sizeof(m));
4354                                 m.tex[0] = R_GetTexture(layer->texture);
4355                                 m.texmatrix[0] = layer->texmatrix;
4356                                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
4357                                 m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4358                                 m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4359                                 R_Mesh_TextureState(&m);
4360                                 if (rsurface_lightmode == 2)
4361                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
4362                                 else
4363                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
4364                         }
4365                         break;
4366                 case TEXTURELAYERTYPE_TEXTURE:
4367                         // singletexture unlit texture with transparency support
4368                         memset(&m, 0, sizeof(m));
4369                         m.tex[0] = R_GetTexture(layer->texture);
4370                         m.texmatrix[0] = layer->texmatrix;
4371                         m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
4372                         m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4373                         m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4374                         R_Mesh_TextureState(&m);
4375                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
4376                         break;
4377                 case TEXTURELAYERTYPE_FOG:
4378                         // singletexture fogging
4379                         R_Mesh_ColorPointer(rsurface_array_color4f, 0, 0);
4380                         if (layer->texture)
4381                         {
4382                                 memset(&m, 0, sizeof(m));
4383                                 m.tex[0] = R_GetTexture(layer->texture);
4384                                 m.texmatrix[0] = layer->texmatrix;
4385                                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordtexture2f;
4386                                 m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4387                                 m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordtexture2f;
4388                                 R_Mesh_TextureState(&m);
4389                         }
4390                         else
4391                                 R_Mesh_ResetTextureState();
4392                         // generate a color array for the fog pass
4393                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4394                         {
4395                                 int i;
4396                                 float f, *v, *c;
4397                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4398                                 for (i = 0, v = (rsurface_vertex3f + 3 * surface->num_firstvertex), c = (rsurface_array_color4f + 4 * surface->num_firstvertex);i < surface->num_vertices;i++, v += 3, c += 4)
4399                                 {
4400                                         f = 1 - FogPoint_Model(v);
4401                                         c[0] = layer->color[0];
4402                                         c[1] = layer->color[1];
4403                                         c[2] = layer->color[2];
4404                                         c[3] = f * layer->color[3];
4405                                 }
4406                         }
4407                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
4408                         break;
4409                 default:
4410                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
4411                 }
4412                 GL_LockArrays(0, 0);
4413         }
4414         CHECKGLERROR
4415         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4416         {
4417                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
4418                 GL_AlphaTest(false);
4419         }
4420 }
4421
4422 static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly)
4423 {
4424         if (rsurface_texture->currentmaterialflags & MATERIALFLAG_NODRAW)
4425                 return;
4426         r_shadow_rtlight = NULL;
4427         CHECKGLERROR
4428         if (depthonly)
4429         {
4430                 if ((rsurface_texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
4431                         return;
4432                 if (rsurface_mode != RSURFMODE_MULTIPASS)
4433                         rsurface_mode = RSURFMODE_MULTIPASS;
4434                 if (r_depthfirst.integer == 3)
4435                 {
4436                         int i = (int)(texturesurfacelist[0] - rsurface_model->data_surfaces);
4437                         GL_Color(((i >> 6) & 7) / 7.0f, ((i >> 3) & 7) / 7.0f, (i & 7) / 7.0f,1);
4438                 }
4439                 else
4440                 {
4441                         GL_ColorMask(0,0,0,0);
4442                         GL_Color(1,1,1,1);
4443                 }
4444                 GL_DepthRange(0, (rsurface_texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
4445                 GL_CullFace((rsurface_texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
4446                 GL_DepthTest(true);
4447                 GL_BlendFunc(GL_ONE, GL_ZERO);
4448                 GL_DepthMask(true);
4449                 GL_AlphaTest(false);
4450                 R_Mesh_ColorPointer(NULL, 0, 0);
4451                 R_Mesh_ResetTextureState();
4452                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
4453                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
4454                 GL_ColorMask(r_view.colormask[0], r_view.colormask[1], r_view.colormask[2], 1);
4455                 r_refdef.stats.entities_surfaces += texturenumsurfaces;
4456         }
4457         else if (r_depthfirst.integer == 3)
4458                 return;
4459         else if (r_showsurfaces.integer)
4460         {
4461                 if (rsurface_mode != RSURFMODE_MULTIPASS)
4462                         rsurface_mode = RSURFMODE_MULTIPASS;
4463                 GL_DepthRange(0, (rsurface_texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
4464                 GL_DepthTest(true);
4465                 GL_CullFace((rsurface_texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
4466                 GL_BlendFunc(GL_ONE, GL_ZERO);
4467                 GL_DepthMask(writedepth);
4468                 GL_Color(1,1,1,1);
4469                 GL_AlphaTest(false);
4470                 R_Mesh_ColorPointer(NULL, 0, 0);
4471                 R_Mesh_ResetTextureState();
4472                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
4473                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
4474                 r_refdef.stats.entities_surfaces += texturenumsurfaces;
4475         }
4476         else if (gl_lightmaps.integer)
4477         {
4478                 rmeshstate_t m;
4479                 if (rsurface_mode != RSURFMODE_MULTIPASS)
4480                         rsurface_mode = RSURFMODE_MULTIPASS;
4481                 GL_DepthRange(0, (rsurface_texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
4482                 GL_DepthTest(true);
4483                 GL_CullFace((rsurface_texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
4484                 GL_BlendFunc(GL_ONE, GL_ZERO);
4485                 GL_DepthMask(writedepth);
4486                 GL_Color(1,1,1,1);
4487                 GL_AlphaTest(false);
4488                 R_Mesh_ColorPointer(NULL, 0, 0);
4489                 memset(&m, 0, sizeof(m));
4490                 m.tex[0] = R_GetTexture(r_texture_white);
4491                 m.pointer_texcoord[0] = rsurface_model->surfmesh.data_texcoordlightmap2f;
4492                 m.pointer_texcoord_bufferobject[0] = rsurface_model->surfmesh.vbo;
4493                 m.pointer_texcoord_bufferoffset[0] = rsurface_model->surfmesh.vbooffset_texcoordlightmap2f;
4494                 R_Mesh_TextureState(&m);
4495                 RSurf_PrepareVerticesForBatch(rsurface_lightmode == 2, false, texturenumsurfaces, texturesurfacelist);
4496                 if (rsurface_lightmode == 2)
4497                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
4498                 else if (rsurface_uselightmaptexture)
4499                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
4500                 else
4501                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
4502                 r_refdef.stats.entities_surfaces += texturenumsurfaces;
4503         }
4504         else if (rsurface_texture->currentmaterialflags & MATERIALFLAG_SKY)
4505         {
4506                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
4507                 r_refdef.stats.entities_surfaces += texturenumsurfaces;
4508         }
4509         else if (rsurface_texture->currentnumlayers)
4510         {
4511                 // write depth for anything we skipped on the depth-only pass earlier
4512                 if (!writedepth && (rsurface_texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
4513                         writedepth = true;
4514                 GL_DepthRange(0, (rsurface_texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
4515                 GL_DepthTest(!(rsurface_texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
4516                 GL_CullFace((rsurface_texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : GL_FRONT); // quake is backwards, this culls back faces
4517                 GL_BlendFunc(rsurface_texture->currentlayers[0].blendfunc1, rsurface_texture->currentlayers[0].blendfunc2);
4518                 GL_DepthMask(writedepth && !(rsurface_texture->currentmaterialflags & MATERIALFLAG_BLENDED));
4519                 GL_Color(rsurface_entity->colormod[0], rsurface_entity->colormod[1], rsurface_entity->colormod[2], rsurface_texture->currentalpha);
4520                 GL_AlphaTest((rsurface_texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4521                 // FIXME: identify models using a better check than rsurface_model->brush.shadowmesh
4522                 rsurface_lightmode = ((rsurface_texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT) || rsurface_model->brush.shadowmesh) ? 0 : 2;
4523                 if (r_glsl.integer && gl_support_fragment_shader)
4524                         R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist);
4525                 else if (gl_combine.integer && r_textureunits.integer >= 2)
4526                         R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist);
4527                 else
4528                         R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist);
4529                 r_refdef.stats.entities_surfaces += texturenumsurfaces;
4530         }
4531         CHECKGLERROR
4532         GL_LockArrays(0, 0);
4533 }
4534
4535 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
4536 {
4537         int i, j;
4538         int texturenumsurfaces, endsurface;
4539         texture_t *texture;
4540         msurface_t *surface;
4541         msurface_t *texturesurfacelist[1024];
4542
4543         // if the model is static it doesn't matter what value we give for
4544         // wantnormals and wanttangents, so this logic uses only rules applicable
4545         // to a model, knowing that they are meaningless otherwise
4546         if (ent == r_refdef.worldentity)
4547                 RSurf_ActiveWorldEntity();
4548         else if ((ent->effects & EF_FULLBRIGHT) || r_showsurfaces.integer || VectorLength2(ent->modellight_diffuse) < (1.0f / 256.0f))
4549                 RSurf_ActiveModelEntity(ent, false, false);
4550         else
4551                 RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader);
4552
4553         for (i = 0;i < numsurfaces;i = j)
4554         {
4555                 j = i + 1;
4556                 surface = rsurface_model->data_surfaces + surfacelist[i];
4557                 texture = surface->texture;
4558                 R_UpdateTextureInfo(ent, texture);
4559                 rsurface_texture = texture->currentframe;
4560                 rsurface_uselightmaptexture = surface->lightmaptexture != NULL;
4561                 // scan ahead until we find a different texture
4562                 endsurface = min(i + 1024, numsurfaces);
4563                 texturenumsurfaces = 0;
4564                 texturesurfacelist[texturenumsurfaces++] = surface;
4565                 for (;j < endsurface;j++)
4566                 {
4567                         surface = rsurface_model->data_surfaces + surfacelist[j];
4568                         if (texture != surface->texture || rsurface_uselightmaptexture != (surface->lightmaptexture != NULL))
4569                                 break;
4570                         texturesurfacelist[texturenumsurfaces++] = surface;
4571                 }
4572                 // render the range of surfaces
4573                 R_DrawTextureSurfaceList(texturenumsurfaces, texturesurfacelist, true, false);
4574         }
4575
4576         RSurf_CleanUp();
4577 }
4578
4579 void R_QueueSurfaceList(int numsurfaces, msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly)
4580 {
4581         int i, j;
4582         vec3_t tempcenter, center;
4583         texture_t *texture;
4584         // break the surface list down into batches by texture and use of lightmapping
4585         for (i = 0;i < numsurfaces;i = j)
4586         {
4587                 j = i + 1;
4588                 // texture is the base texture pointer, rsurface_texture is the
4589                 // current frame/skin the texture is directing us to use (for example
4590                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
4591                 // use skin 1 instead)
4592                 texture = surfacelist[i]->texture;
4593                 rsurface_texture = texture->currentframe;
4594                 rsurface_uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
4595                 if (!(rsurface_texture->currentmaterialflags & flagsmask))
4596                 {
4597                         // if this texture is not the kind we want, skip ahead to the next one
4598                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
4599                                 ;
4600                         continue;
4601                 }
4602                 if (rsurface_texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
4603                 {
4604                         // transparent surfaces get pushed off into the transparent queue
4605                         const msurface_t *surface = surfacelist[i];
4606                         if (depthonly)
4607                                 continue;
4608                         tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
4609                         tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
4610                         tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
4611                         Matrix4x4_Transform(&rsurface_entity->matrix, tempcenter, center);
4612                         R_MeshQueue_AddTransparent(rsurface_texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_view.origin : center, R_DrawSurface_TransparentCallback, rsurface_entity, surface - rsurface_model->data_surfaces, r_shadow_rtlight);
4613                 }
4614                 else
4615                 {
4616                         // simply scan ahead until we find a different texture or lightmap state
4617                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface_uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
4618                                 ;
4619                         // render the range of surfaces
4620                         R_DrawTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly);
4621                 }
4622         }
4623 }
4624
4625 float locboxvertex3f[6*4*3] =
4626 {
4627         1,0,1, 1,0,0, 1,1,0, 1,1,1,
4628         0,1,1, 0,1,0, 0,0,0, 0,0,1,
4629         1,1,1, 1,1,0, 0,1,0, 0,1,1,
4630         0,0,1, 0,0,0, 1,0,0, 1,0,1,
4631         0,0,1, 1,0,1, 1,1,1, 0,1,1,
4632         1,0,0, 0,0,0, 0,1,0, 1,1,0
4633 };
4634
4635 int locboxelement3i[6*2*3] =
4636 {
4637          0, 1, 2, 0, 2, 3,
4638          4, 5, 6, 4, 6, 7,
4639          8, 9,10, 8,10,11,
4640         12,13,14, 12,14,15,
4641         16,17,18, 16,18,19,
4642         20,21,22, 20,22,23
4643 };
4644
4645 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
4646 {
4647         int i, j;
4648         cl_locnode_t *loc = (cl_locnode_t *)ent;
4649         vec3_t mins, size;
4650         float vertex3f[6*4*3];
4651         CHECKGLERROR
4652         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4653         GL_DepthMask(false);
4654         GL_DepthRange(0, 1);
4655         GL_DepthTest(true);
4656         GL_CullFace(GL_NONE);
4657         R_Mesh_Matrix(&identitymatrix);
4658
4659         R_Mesh_VertexPointer(vertex3f, 0, 0);
4660         R_Mesh_ColorPointer(NULL, 0, 0);
4661         R_Mesh_ResetTextureState();
4662
4663         i = surfacelist[0];
4664         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_view.colorscale,
4665                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_view.colorscale,
4666                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_view.colorscale,
4667                         surfacelist[0] < 0 ? 0.5f : 0.125f);
4668
4669         if (VectorCompare(loc->mins, loc->maxs))
4670         {
4671                 VectorSet(size, 2, 2, 2);
4672                 VectorMA(loc->mins, -0.5f, size, mins);
4673         }
4674         else
4675         {
4676                 VectorCopy(loc->mins, mins);
4677                 VectorSubtract(loc->maxs, loc->mins, size);
4678         }
4679
4680         for (i = 0;i < 6*4*3;)
4681                 for (j = 0;j < 3;j++, i++)
4682                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
4683
4684         R_Mesh_Draw(0, 6*4, 6*2, locboxelement3i, 0, 0);
4685 }
4686
4687 void R_DrawLocs(void)
4688 {
4689         int index;
4690         cl_locnode_t *loc, *nearestloc;
4691         vec3_t center;
4692         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
4693         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
4694         {
4695                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
4696                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
4697         }
4698 }
4699
4700 void R_DrawCollisionBrushes(entity_render_t *ent)
4701 {
4702         int i;
4703         q3mbrush_t *brush;
4704         msurface_t *surface;
4705         model_t *model = ent->model;
4706         if (!model->brush.num_brushes)
4707                 return;
4708         CHECKGLERROR
4709         R_Mesh_ColorPointer(NULL, 0, 0);
4710         R_Mesh_ResetTextureState();
4711         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
4712         GL_DepthMask(false);
4713         GL_DepthRange(0, 1);
4714         GL_DepthTest(!r_showdisabledepthtest.integer);
4715         qglPolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);CHECKGLERROR
4716         for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
4717                 if (brush->colbrushf && brush->colbrushf->numtriangles)
4718                         R_DrawCollisionBrush(brush->colbrushf);
4719         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
4720                 if (surface->num_collisiontriangles)
4721                         R_DrawCollisionSurface(ent, surface);
4722         qglPolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR
4723 }
4724
4725 void R_DrawTrianglesAndNormals(entity_render_t *ent, qboolean drawtris, qboolean drawnormals, int flagsmask)
4726 {
4727         int i, j, k, l;
4728         const int *elements;
4729         msurface_t *surface;
4730         model_t *model = ent->model;
4731         vec3_t v;
4732         CHECKGLERROR
4733         GL_DepthRange(0, 1);
4734         GL_DepthTest(!r_showdisabledepthtest.integer);
4735         GL_DepthMask(true);
4736         GL_BlendFunc(GL_ONE, GL_ZERO);
4737         R_Mesh_ColorPointer(NULL, 0, 0);
4738         R_Mesh_ResetTextureState();
4739         for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
4740         {
4741                 if (ent == r_refdef.worldentity && !r_viewcache.world_surfacevisible[j])
4742                         continue;
4743                 rsurface_texture = surface->texture->currentframe;
4744                 if ((rsurface_texture->currentmaterialflags & flagsmask) && surface->num_triangles)
4745                 {
4746                         RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
4747                         if (drawtris)
4748                         {
4749                                 if (!rsurface_texture->currentlayers->depthmask)
4750                                         GL_Color(r_showtris.value * r_view.colorscale, 0, 0, 1);
4751                                 else if (ent == r_refdef.worldentity)
4752                                         GL_Color(r_showtris.value * r_view.colorscale, r_showtris.value * r_view.colorscale, r_showtris.value * r_view.colorscale, 1);
4753                                 else
4754                                         GL_Color(0, r_showtris.value * r_view.colorscale, 0, 1);
4755                                 elements = (ent->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);
4756                                 CHECKGLERROR
4757                                 qglBegin(GL_LINES);
4758                                 for (k = 0;k < surface->num_triangles;k++, elements += 3)
4759                                 {
4760 #define GLVERTEXELEMENT(n) qglVertex3f(rsurface_vertex3f[elements[n]*3+0], rsurface_vertex3f[elements[n]*3+1], rsurface_vertex3f[elements[n]*3+2])
4761                                         GLVERTEXELEMENT(0);GLVERTEXELEMENT(1);
4762                                         GLVERTEXELEMENT(1);GLVERTEXELEMENT(2);
4763                                         GLVERTEXELEMENT(2);GLVERTEXELEMENT(0);
4764                                 }
4765                                 qglEnd();
4766                                 CHECKGLERROR
4767                         }
4768                         if (drawnormals)
4769                         {
4770                                 GL_Color(r_shownormals.value * r_view.colorscale, 0, 0, 1);
4771                                 qglBegin(GL_LINES);
4772                                 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
4773                                 {
4774                                         VectorCopy(rsurface_vertex3f + l * 3, v);
4775                                         qglVertex3f(v[0], v[1], v[2]);
4776                                         VectorMA(v, 8, rsurface_svector3f + l * 3, v);
4777                                         qglVertex3f(v[0], v[1], v[2]);
4778                                 }
4779                                 qglEnd();
4780                                 CHECKGLERROR
4781                                 GL_Color(0, 0, r_shownormals.value * r_view.colorscale, 1);
4782                                 qglBegin(GL_LINES);
4783                                 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
4784                                 {
4785                                         VectorCopy(rsurface_vertex3f + l * 3, v);
4786                                         qglVertex3f(v[0], v[1], v[2]);
4787                                         VectorMA(v, 8, rsurface_tvector3f + l * 3, v);
4788                                         qglVertex3f(v[0], v[1], v[2]);
4789                                 }
4790                                 qglEnd();
4791                                 CHECKGLERROR
4792                                 GL_Color(0, r_shownormals.value * r_view.colorscale, 0, 1);
4793                                 qglBegin(GL_LINES);
4794                                 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
4795                                 {
4796                                         VectorCopy(rsurface_vertex3f + l * 3, v);
4797                                         qglVertex3f(v[0], v[1], v[2]);
4798                                         VectorMA(v, 8, rsurface_normal3f + l * 3, v);
4799                                         qglVertex3f(v[0], v[1], v[2]);
4800                                 }
4801                                 qglEnd();
4802                                 CHECKGLERROR
4803                         }
4804                 }
4805         }
4806         rsurface_texture = NULL;
4807 }
4808
4809 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
4810 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly)
4811 {
4812         int i, j, endj, f, flagsmask;
4813         int counttriangles = 0;
4814         msurface_t *surface, **surfacechain;
4815         texture_t *t;
4816         model_t *model = r_refdef.worldmodel;
4817         const int maxsurfacelist = 1024;
4818         int numsurfacelist = 0;
4819         msurface_t *surfacelist[1024];
4820         if (model == NULL)
4821                 return;
4822
4823         RSurf_ActiveWorldEntity();
4824
4825         // update light styles
4826         if (!skysurfaces && !depthonly && model->brushq1.light_styleupdatechains)
4827         {
4828                 for (i = 0;i < model->brushq1.light_styles;i++)
4829                 {
4830                         if (model->brushq1.light_stylevalue[i] != r_refdef.lightstylevalue[model->brushq1.light_style[i]])
4831                         {
4832                                 model->brushq1.light_stylevalue[i] = r_refdef.lightstylevalue[model->brushq1.light_style[i]];
4833                                 if ((surfacechain = model->brushq1.light_styleupdatechains[i]))
4834                                         for (;(surface = *surfacechain);surfacechain++)
4835                                                 surface->cached_dlight = true;
4836                         }
4837                 }
4838         }
4839
4840         R_UpdateAllTextureInfo(r_refdef.worldentity);
4841         flagsmask = skysurfaces ? MATERIALFLAG_SKY : (MATERIALFLAG_WATER | MATERIALFLAG_WALL);
4842         f = 0;
4843         t = NULL;
4844         rsurface_uselightmaptexture = false;
4845         rsurface_texture = NULL;
4846         numsurfacelist = 0;
4847         j = model->firstmodelsurface;
4848         endj = j + model->nummodelsurfaces;
4849         while (j < endj)
4850         {
4851                 // quickly skip over non-visible surfaces
4852                 for (;j < endj && !r_viewcache.world_surfacevisible[j];j++)
4853                         ;
4854                 // quickly iterate over visible surfaces
4855                 for (;j < endj && r_viewcache.world_surfacevisible[j];j++)
4856                 {
4857                         // process this surface
4858                         surface = model->data_surfaces + j;
4859                         // if this surface fits the criteria, add it to the list
4860                         if (surface->num_triangles)
4861                         {
4862                                 // if lightmap parameters changed, rebuild lightmap texture
4863                                 if (surface->cached_dlight)
4864                                         R_BuildLightMap(r_refdef.worldentity, surface);
4865                                 // add face to draw list
4866                                 surfacelist[numsurfacelist++] = surface;
4867                                 counttriangles += surface->num_triangles;
4868                                 if (numsurfacelist >= maxsurfacelist)
4869                                 {
4870                                         R_QueueSurfaceList(numsurfacelist, surfacelist, flagsmask, writedepth, depthonly);
4871                                         numsurfacelist = 0;
4872                                 }
4873                         }
4874                 }
4875         }
4876         if (numsurfacelist)
4877                 R_QueueSurfaceList(numsurfacelist, surfacelist, flagsmask, writedepth, depthonly);
4878         r_refdef.stats.entities_triangles += counttriangles;
4879         RSurf_CleanUp();
4880
4881         if (r_showcollisionbrushes.integer && !skysurfaces && !depthonly)
4882                 R_DrawCollisionBrushes(r_refdef.worldentity);
4883
4884         if ((r_showtris.integer || r_shownormals.integer) && !depthonly)
4885                 R_DrawTrianglesAndNormals(r_refdef.worldentity, r_showtris.integer, r_shownormals.integer, flagsmask);
4886 }
4887
4888 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly)
4889 {
4890         int i, f, flagsmask;
4891         int counttriangles = 0;
4892         msurface_t *surface, *endsurface, **surfacechain;
4893         texture_t *t;
4894         model_t *model = ent->model;
4895         const int maxsurfacelist = 1024;
4896         int numsurfacelist = 0;
4897         msurface_t *surfacelist[1024];
4898         if (model == NULL)
4899                 return;
4900
4901         // if the model is static it doesn't matter what value we give for
4902         // wantnormals and wanttangents, so this logic uses only rules applicable
4903         // to a model, knowing that they are meaningless otherwise
4904         if (ent == r_refdef.worldentity)
4905                 RSurf_ActiveWorldEntity();
4906         else if ((ent->effects & EF_FULLBRIGHT) || r_showsurfaces.integer || VectorLength2(ent->modellight_diffuse) < (1.0f / 256.0f))
4907                 RSurf_ActiveModelEntity(ent, false, false);
4908         else
4909                 RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader && !depthonly);
4910
4911         // update light styles
4912         if (!skysurfaces && !depthonly && model->brushq1.light_styleupdatechains)
4913         {
4914                 for (i = 0;i < model->brushq1.light_styles;i++)
4915                 {
4916                         if (model->brushq1.light_stylevalue[i] != r_refdef.lightstylevalue[model->brushq1.light_style[i]])
4917                         {
4918                                 model->brushq1.light_stylevalue[i] = r_refdef.lightstylevalue[model->brushq1.light_style[i]];
4919                                 if ((surfacechain = model->brushq1.light_styleupdatechains[i]))
4920                                         for (;(surface = *surfacechain);surfacechain++)
4921                                                 surface->cached_dlight = true;
4922                         }
4923                 }
4924         }
4925
4926         R_UpdateAllTextureInfo(ent);
4927         flagsmask = skysurfaces ? MATERIALFLAG_SKY : (MATERIALFLAG_WATER | MATERIALFLAG_WALL);
4928         f = 0;
4929         t = NULL;
4930         rsurface_uselightmaptexture = false;
4931         rsurface_texture = NULL;
4932         numsurfacelist = 0;
4933         surface = model->data_surfaces + model->firstmodelsurface;
4934         endsurface = surface + model->nummodelsurfaces;
4935         for (;surface < endsurface;surface++)
4936         {
4937                 // if this surface fits the criteria, add it to the list
4938                 if (surface->num_triangles)
4939                 {
4940                         // if lightmap parameters changed, rebuild lightmap texture
4941                         if (surface->cached_dlight)
4942                                 R_BuildLightMap(ent, surface);
4943                         // add face to draw list
4944                         surfacelist[numsurfacelist++] = surface;
4945                         counttriangles += surface->num_triangles;
4946                         if (numsurfacelist >= maxsurfacelist)
4947                         {
4948                                 R_QueueSurfaceList(numsurfacelist, surfacelist, flagsmask, writedepth, depthonly);
4949                                 numsurfacelist = 0;
4950                         }
4951                 }
4952         }
4953         if (numsurfacelist)
4954                 R_QueueSurfaceList(numsurfacelist, surfacelist, flagsmask, writedepth, depthonly);
4955         r_refdef.stats.entities_triangles += counttriangles;
4956         RSurf_CleanUp();
4957
4958         if (r_showcollisionbrushes.integer && !skysurfaces && !depthonly)
4959                 R_DrawCollisionBrushes(ent);
4960
4961         if ((r_showtris.integer || r_shownormals.integer) && !depthonly)
4962                 R_DrawTrianglesAndNormals(ent, r_showtris.integer, r_shownormals.integer, flagsmask);
4963 }