]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rmain.c
Add R_SelectScene and R_GetScenePointer that encapsulate access to an array of r_refd...
[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 "cl_dyntexture.h"
24 #include "r_shadow.h"
25 #include "polygon.h"
26 #include "image.h"
27
28 mempool_t *r_main_mempool;
29 rtexturepool_t *r_main_texturepool;
30
31 //
32 // screen size info
33 //
34 r_refdef_t r_refdef;
35
36 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"};
37 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
38 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
39 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
40 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
41 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
42 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
43 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
44 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
45 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
46 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
47 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
48 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
49 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
50 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
51 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
52 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling"};
53 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
54 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
55 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
56 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
57 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
58 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
59 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
60 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this)"};
61 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
62 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
63 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
64 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "2", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
65 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
66
67 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
68 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
69 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
70 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
71 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
72 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
73 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
74 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
75
76 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)"};
77
78 cvar_t r_glsl = {CVAR_SAVE, "r_glsl", "1", "enables use of OpenGL 2.0 pixel shaders for lighting"};
79 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
80 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
81 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
82 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)"};
83 cvar_t r_glsl_contrastboost = {CVAR_SAVE, "r_glsl_contrastboost", "1", "by how much to multiply the contrast in dark areas (1 is no change)"};
84
85 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
86 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
87 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
88 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
89 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
90
91 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "1", "enables animation smoothing on sprites (requires r_lerpmodels 1)"};
92 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
93 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
94 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
95
96 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
97 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
98 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
99 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
100 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
101 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
102 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
103
104 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
105 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
106 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
107 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)"};
108
109 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"};
110
111 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"};
112
113 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
114
115 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
116 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
117 cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
118 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
119 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
120 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
121
122 extern qboolean v_flipped_state;
123
124 typedef struct r_glsl_bloomshader_s
125 {
126         int program;
127         int loc_Texture_Bloom;
128 }
129 r_glsl_bloomshader_t;
130
131 static struct r_bloomstate_s
132 {
133         qboolean enabled;
134         qboolean hdr;
135
136         int bloomwidth, bloomheight;
137
138         int screentexturewidth, screentextureheight;
139         rtexture_t *texture_screen;
140
141         int bloomtexturewidth, bloomtextureheight;
142         rtexture_t *texture_bloom;
143
144         r_glsl_bloomshader_t *shader;
145
146         // arrays for rendering the screen passes
147         float screentexcoord2f[8];
148         float bloomtexcoord2f[8];
149         float offsettexcoord2f[8];
150 }
151 r_bloomstate;
152
153 typedef struct r_waterstate_waterplane_s
154 {
155         rtexture_t *texture_refraction;
156         rtexture_t *texture_reflection;
157         mplane_t plane;
158         int materialflags; // combined flags of all water surfaces on this plane
159         unsigned char pvsbits[(32768+7)>>3]; // FIXME: buffer overflow on huge maps
160         qboolean pvsvalid;
161 }
162 r_waterstate_waterplane_t;
163
164 #define MAX_WATERPLANES 16
165
166 static struct r_waterstate_s
167 {
168         qboolean enabled;
169
170         qboolean renderingscene; // true while rendering a refraction or reflection texture, disables water surfaces
171
172         int waterwidth, waterheight;
173         int texturewidth, textureheight;
174
175         int maxwaterplanes; // same as MAX_WATERPLANES
176         int numwaterplanes;
177         r_waterstate_waterplane_t waterplanes[MAX_WATERPLANES];
178
179         float screenscale[2];
180         float screencenter[2];
181 }
182 r_waterstate;
183
184 // shadow volume bsp struct with automatically growing nodes buffer
185 svbsp_t r_svbsp;
186
187 rtexture_t *r_texture_blanknormalmap;
188 rtexture_t *r_texture_white;
189 rtexture_t *r_texture_grey128;
190 rtexture_t *r_texture_black;
191 rtexture_t *r_texture_notexture;
192 rtexture_t *r_texture_whitecube;
193 rtexture_t *r_texture_normalizationcube;
194 rtexture_t *r_texture_fogattenuation;
195 //rtexture_t *r_texture_fogintensity;
196
197 char r_qwskincache[MAX_SCOREBOARD][MAX_QPATH];
198 skinframe_t *r_qwskincache_skinframe[MAX_SCOREBOARD];
199
200 // vertex coordinates for a quad that covers the screen exactly
201 const static float r_screenvertex3f[12] =
202 {
203         0, 0, 0,
204         1, 0, 0,
205         1, 1, 0,
206         0, 1, 0
207 };
208
209 extern void R_DrawModelShadows(void);
210
211 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
212 {
213         int i;
214         for (i = 0;i < verts;i++)
215         {
216                 out[0] = in[0] * r;
217                 out[1] = in[1] * g;
218                 out[2] = in[2] * b;
219                 out[3] = in[3];
220                 in += 4;
221                 out += 4;
222         }
223 }
224
225 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
226 {
227         int i;
228         for (i = 0;i < verts;i++)
229         {
230                 out[0] = r;
231                 out[1] = g;
232                 out[2] = b;
233                 out[3] = a;
234                 out += 4;
235         }
236 }
237
238 // FIXME: move this to client?
239 void FOG_clear(void)
240 {
241         if (gamemode == GAME_NEHAHRA)
242         {
243                 Cvar_Set("gl_fogenable", "0");
244                 Cvar_Set("gl_fogdensity", "0.2");
245                 Cvar_Set("gl_fogred", "0.3");
246                 Cvar_Set("gl_foggreen", "0.3");
247                 Cvar_Set("gl_fogblue", "0.3");
248         }
249         r_refdef.fog_density = 0;
250         r_refdef.fog_red = 0;
251         r_refdef.fog_green = 0;
252         r_refdef.fog_blue = 0;
253         r_refdef.fog_alpha = 1;
254         r_refdef.fog_start = 0;
255         r_refdef.fog_end = 0;
256 }
257
258 float FogForDistance(vec_t dist)
259 {
260         unsigned int fogmasktableindex = (unsigned int)(dist * r_refdef.fogmasktabledistmultiplier);
261         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
262 }
263
264 float FogPoint_World(const vec3_t p)
265 {
266         return FogForDistance(VectorDistance((p), r_refdef.view.origin));
267 }
268
269 float FogPoint_Model(const vec3_t p)
270 {
271         return FogForDistance(VectorDistance((p), rsurface.modelorg));
272 }
273
274 static void R_BuildBlankTextures(void)
275 {
276         unsigned char data[4];
277         data[2] = 128; // normal X
278         data[1] = 128; // normal Y
279         data[0] = 255; // normal Z
280         data[3] = 128; // height
281         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
282         data[0] = 255;
283         data[1] = 255;
284         data[2] = 255;
285         data[3] = 255;
286         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
287         data[0] = 128;
288         data[1] = 128;
289         data[2] = 128;
290         data[3] = 255;
291         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
292         data[0] = 0;
293         data[1] = 0;
294         data[2] = 0;
295         data[3] = 255;
296         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_PERSISTENT, NULL);
297 }
298
299 static void R_BuildNoTexture(void)
300 {
301         int x, y;
302         unsigned char pix[16][16][4];
303         // this makes a light grey/dark grey checkerboard texture
304         for (y = 0;y < 16;y++)
305         {
306                 for (x = 0;x < 16;x++)
307                 {
308                         if ((y < 8) ^ (x < 8))
309                         {
310                                 pix[y][x][0] = 128;
311                                 pix[y][x][1] = 128;
312                                 pix[y][x][2] = 128;
313                                 pix[y][x][3] = 255;
314                         }
315                         else
316                         {
317                                 pix[y][x][0] = 64;
318                                 pix[y][x][1] = 64;
319                                 pix[y][x][2] = 64;
320                                 pix[y][x][3] = 255;
321                         }
322                 }
323         }
324         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
325 }
326
327 static void R_BuildWhiteCube(void)
328 {
329         unsigned char data[6*1*1*4];
330         memset(data, 255, sizeof(data));
331         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
332 }
333
334 static void R_BuildNormalizationCube(void)
335 {
336         int x, y, side;
337         vec3_t v;
338         vec_t s, t, intensity;
339 #define NORMSIZE 64
340         unsigned char data[6][NORMSIZE][NORMSIZE][4];
341         for (side = 0;side < 6;side++)
342         {
343                 for (y = 0;y < NORMSIZE;y++)
344                 {
345                         for (x = 0;x < NORMSIZE;x++)
346                         {
347                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
348                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
349                                 switch(side)
350                                 {
351                                 default:
352                                 case 0:
353                                         v[0] = 1;
354                                         v[1] = -t;
355                                         v[2] = -s;
356                                         break;
357                                 case 1:
358                                         v[0] = -1;
359                                         v[1] = -t;
360                                         v[2] = s;
361                                         break;
362                                 case 2:
363                                         v[0] = s;
364                                         v[1] = 1;
365                                         v[2] = t;
366                                         break;
367                                 case 3:
368                                         v[0] = s;
369                                         v[1] = -1;
370                                         v[2] = -t;
371                                         break;
372                                 case 4:
373                                         v[0] = s;
374                                         v[1] = -t;
375                                         v[2] = 1;
376                                         break;
377                                 case 5:
378                                         v[0] = -s;
379                                         v[1] = -t;
380                                         v[2] = -1;
381                                         break;
382                                 }
383                                 intensity = 127.0f / sqrt(DotProduct(v, v));
384                                 data[side][y][x][2] = (unsigned char)(128.0f + intensity * v[0]);
385                                 data[side][y][x][1] = (unsigned char)(128.0f + intensity * v[1]);
386                                 data[side][y][x][0] = (unsigned char)(128.0f + intensity * v[2]);
387                                 data[side][y][x][3] = 255;
388                         }
389                 }
390         }
391         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, &data[0][0][0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
392 }
393
394 static void R_BuildFogTexture(void)
395 {
396         int x, b;
397 #define FOGWIDTH 256
398         unsigned char data1[FOGWIDTH][4];
399         //unsigned char data2[FOGWIDTH][4];
400         double d, r, alpha;
401
402         r_refdef.fogmasktable_start = r_refdef.fog_start;
403         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
404         r_refdef.fogmasktable_range = r_refdef.fogrange;
405         r_refdef.fogmasktable_density = r_refdef.fog_density;
406
407         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
408         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
409         {
410                 d = (x * r - r_refdef.fogmasktable_start);
411                 if(developer.integer >= 100)
412                         Con_Printf("%f ", d);
413                 d = max(0, d);
414                 if (r_fog_exp2.integer)
415                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
416                 else
417                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
418                 if(developer.integer >= 100)
419                         Con_Printf(" : %f ", alpha);
420                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
421                 if(developer.integer >= 100)
422                         Con_Printf(" = %f\n", alpha);
423                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
424         }
425
426         for (x = 0;x < FOGWIDTH;x++)
427         {
428                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
429                 data1[x][0] = b;
430                 data1[x][1] = b;
431                 data1[x][2] = b;
432                 data1[x][3] = 255;
433                 //data2[x][0] = 255 - b;
434                 //data2[x][1] = 255 - b;
435                 //data2[x][2] = 255 - b;
436                 //data2[x][3] = 255;
437         }
438         if (r_texture_fogattenuation)
439         {
440                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
441                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
442         }
443         else
444         {
445                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, NULL);
446                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
447         }
448 }
449
450 static const char *builtinshaderstring =
451 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
452 "// written by Forest 'LordHavoc' Hale\n"
453 "\n"
454 "// common definitions between vertex shader and fragment shader:\n"
455 "\n"
456 "#ifdef __GLSL_CG_DATA_TYPES\n"
457 "# define myhalf half\n"
458 "# define myhalf2 half2\n"
459 "# define myhalf3 half3\n"
460 "# define myhalf4 half4\n"
461 "#else\n"
462 "# define myhalf float\n"
463 "# define myhalf2 vec2\n"
464 "# define myhalf3 vec3\n"
465 "# define myhalf4 vec4\n"
466 "#endif\n"
467 "\n"
468 "varying vec2 TexCoord;\n"
469 "varying vec2 TexCoordLightmap;\n"
470 "\n"
471 "//#ifdef MODE_LIGHTSOURCE\n"
472 "varying vec3 CubeVector;\n"
473 "//#endif\n"
474 "\n"
475 "//#ifdef MODE_LIGHTSOURCE\n"
476 "varying vec3 LightVector;\n"
477 "//#else\n"
478 "//# ifdef MODE_LIGHTDIRECTION\n"
479 "//varying vec3 LightVector;\n"
480 "//# endif\n"
481 "//#endif\n"
482 "\n"
483 "varying vec3 EyeVector;\n"
484 "//#ifdef USEFOG\n"
485 "varying vec3 EyeVectorModelSpace;\n"
486 "//#endif\n"
487 "\n"
488 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
489 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
490 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
491 "\n"
492 "//#ifdef MODE_WATER\n"
493 "varying vec4 ModelViewProjectionPosition;\n"
494 "//#else\n"
495 "//# ifdef MODE_REFRACTION\n"
496 "//varying vec4 ModelViewProjectionPosition;\n"
497 "//# else\n"
498 "//#  ifdef USEREFLECTION\n"
499 "//varying vec4 ModelViewProjectionPosition;\n"
500 "//#  endif\n"
501 "//# endif\n"
502 "//#endif\n"
503 "\n"
504 "\n"
505 "\n"
506 "\n"
507 "\n"
508 "// vertex shader specific:\n"
509 "#ifdef VERTEX_SHADER\n"
510 "\n"
511 "uniform vec3 LightPosition;\n"
512 "uniform vec3 EyePosition;\n"
513 "uniform vec3 LightDir;\n"
514 "\n"
515 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3)\n"
516 "\n"
517 "void main(void)\n"
518 "{\n"
519 "       gl_FrontColor = gl_Color;\n"
520 "       // copy the surface texcoord\n"
521 "       TexCoord = vec2(gl_TextureMatrix[0] * gl_MultiTexCoord0);\n"
522 "#ifndef MODE_LIGHTSOURCE\n"
523 "# ifndef MODE_LIGHTDIRECTION\n"
524 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
525 "# endif\n"
526 "#endif\n"
527 "\n"
528 "#ifdef MODE_LIGHTSOURCE\n"
529 "       // transform vertex position into light attenuation/cubemap space\n"
530 "       // (-1 to +1 across the light box)\n"
531 "       CubeVector = vec3(gl_TextureMatrix[3] * gl_Vertex);\n"
532 "\n"
533 "       // transform unnormalized light direction into tangent space\n"
534 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
535 "       //  normalize it per pixel)\n"
536 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
537 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
538 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
539 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
540 "#endif\n"
541 "\n"
542 "#ifdef MODE_LIGHTDIRECTION\n"
543 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
544 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
545 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
546 "#endif\n"
547 "\n"
548 "       // transform unnormalized eye direction into tangent space\n"
549 "#ifndef USEFOG\n"
550 "       vec3 EyeVectorModelSpace;\n"
551 "#endif\n"
552 "       EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
553 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
554 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
555 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
556 "\n"
557 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
558 "       VectorS = gl_MultiTexCoord1.xyz;\n"
559 "       VectorT = gl_MultiTexCoord2.xyz;\n"
560 "       VectorR = gl_MultiTexCoord3.xyz;\n"
561 "#endif\n"
562 "\n"
563 "//#if defined(MODE_WATER) || defined(MODE_REFRACTION) || defined(USEREFLECTION)\n"
564 "//     ModelViewProjectionPosition = gl_Vertex * gl_ModelViewProjectionMatrix;\n"
565 "//     //ModelViewProjectionPosition_svector = (gl_Vertex + vec4(gl_MultiTexCoord1.xyz, 0)) * gl_ModelViewProjectionMatrix - ModelViewProjectionPosition;\n"
566 "//     //ModelViewProjectionPosition_tvector = (gl_Vertex + vec4(gl_MultiTexCoord2.xyz, 0)) * gl_ModelViewProjectionMatrix - ModelViewProjectionPosition;\n"
567 "//#endif\n"
568 "\n"
569 "// transform vertex to camera space, using ftransform to match non-VS\n"
570 "       // rendering\n"
571 "       gl_Position = ftransform();\n"
572 "\n"
573 "#ifdef MODE_WATER\n"
574 "       ModelViewProjectionPosition = gl_Position;\n"
575 "#endif\n"
576 "#ifdef MODE_REFRACTION\n"
577 "       ModelViewProjectionPosition = gl_Position;\n"
578 "#endif\n"
579 "#ifdef USEREFLECTION\n"
580 "       ModelViewProjectionPosition = gl_Position;\n"
581 "#endif\n"
582 "}\n"
583 "\n"
584 "#endif // VERTEX_SHADER\n"
585 "\n"
586 "\n"
587 "\n"
588 "\n"
589 "// fragment shader specific:\n"
590 "#ifdef FRAGMENT_SHADER\n"
591 "\n"
592 "// 13 textures, we can only use up to 16 on DX9-class hardware\n"
593 "uniform sampler2D Texture_Normal;\n"
594 "uniform sampler2D Texture_Color;\n"
595 "uniform sampler2D Texture_Gloss;\n"
596 "uniform sampler2D Texture_Glow;\n"
597 "uniform sampler2D Texture_SecondaryNormal;\n"
598 "uniform sampler2D Texture_SecondaryColor;\n"
599 "uniform sampler2D Texture_SecondaryGloss;\n"
600 "uniform sampler2D Texture_SecondaryGlow;\n"
601 "uniform sampler2D Texture_Pants;\n"
602 "uniform sampler2D Texture_Shirt;\n"
603 "uniform sampler2D Texture_FogMask;\n"
604 "uniform sampler2D Texture_Lightmap;\n"
605 "uniform sampler2D Texture_Deluxemap;\n"
606 "uniform sampler2D Texture_Refraction;\n"
607 "uniform sampler2D Texture_Reflection;\n"
608 "uniform sampler2D Texture_Attenuation;\n"
609 "uniform samplerCube Texture_Cube;\n"
610 "\n"
611 "uniform myhalf3 LightColor;\n"
612 "uniform myhalf3 AmbientColor;\n"
613 "uniform myhalf3 DiffuseColor;\n"
614 "uniform myhalf3 SpecularColor;\n"
615 "uniform myhalf3 Color_Pants;\n"
616 "uniform myhalf3 Color_Shirt;\n"
617 "uniform myhalf3 FogColor;\n"
618 "\n"
619 "uniform myhalf4 TintColor;\n"
620 "\n"
621 "\n"
622 "//#ifdef MODE_WATER\n"
623 "uniform vec4 DistortScaleRefractReflect;\n"
624 "uniform vec4 ScreenScaleRefractReflect;\n"
625 "uniform vec4 ScreenCenterRefractReflect;\n"
626 "uniform myhalf4 RefractColor;\n"
627 "uniform myhalf4 ReflectColor;\n"
628 "uniform myhalf ReflectFactor;\n"
629 "uniform myhalf ReflectOffset;\n"
630 "//#else\n"
631 "//# ifdef MODE_REFRACTION\n"
632 "//uniform vec4 DistortScaleRefractReflect;\n"
633 "//uniform vec4 ScreenScaleRefractReflect;\n"
634 "//uniform vec4 ScreenCenterRefractReflect;\n"
635 "//uniform myhalf4 RefractColor;\n"
636 "//#  ifdef USEREFLECTION\n"
637 "//uniform myhalf4 ReflectColor;\n"
638 "//#  endif\n"
639 "//# else\n"
640 "//#  ifdef USEREFLECTION\n"
641 "//uniform vec4 DistortScaleRefractReflect;\n"
642 "//uniform vec4 ScreenScaleRefractReflect;\n"
643 "//uniform vec4 ScreenCenterRefractReflect;\n"
644 "//uniform myhalf4 ReflectColor;\n"
645 "//#  endif\n"
646 "//# endif\n"
647 "//#endif\n"
648 "\n"
649 "uniform myhalf GlowScale;\n"
650 "uniform myhalf SceneBrightness;\n"
651 "#ifdef USECONTRASTBOOST\n"
652 "uniform myhalf ContrastBoostCoeff;\n"
653 "#endif\n"
654 "\n"
655 "uniform float OffsetMapping_Scale;\n"
656 "uniform float OffsetMapping_Bias;\n"
657 "uniform float FogRangeRecip;\n"
658 "\n"
659 "uniform myhalf AmbientScale;\n"
660 "uniform myhalf DiffuseScale;\n"
661 "uniform myhalf SpecularScale;\n"
662 "uniform myhalf SpecularPower;\n"
663 "\n"
664 "#ifdef USEOFFSETMAPPING\n"
665 "vec2 OffsetMapping(vec2 TexCoord)\n"
666 "{\n"
667 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
668 "       // 14 sample relief mapping: linear search and then binary search\n"
669 "       // this basically steps forward a small amount repeatedly until it finds\n"
670 "       // itself inside solid, then jitters forward and back using decreasing\n"
671 "       // amounts to find the impact\n"
672 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
673 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
674 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
675 "       vec3 RT = vec3(TexCoord, 1);\n"
676 "       OffsetVector *= 0.1;\n"
677 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
678 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
679 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
680 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
681 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
682 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
683 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
684 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
685 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
686 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
687 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
688 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
689 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
690 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
691 "       return RT.xy;\n"
692 "#else\n"
693 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
694 "       // this basically moves forward the full distance, and then backs up based\n"
695 "       // on height of samples\n"
696 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
697 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
698 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
699 "       TexCoord += OffsetVector;\n"
700 "       OffsetVector *= 0.333;\n"
701 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
702 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
703 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
704 "       return TexCoord;\n"
705 "#endif\n"
706 "}\n"
707 "#endif // USEOFFSETMAPPING\n"
708 "\n"
709 "#ifdef MODE_WATER\n"
710 "\n"
711 "// water pass\n"
712 "void main(void)\n"
713 "{\n"
714 "#ifdef USEOFFSETMAPPING\n"
715 "       // apply offsetmapping\n"
716 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
717 "#define TexCoord TexCoordOffset\n"
718 "#endif\n"
719 "\n"
720 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
721 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
722 "       vec4 ScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect + vec2(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xyxy * DistortScaleRefractReflect;\n"
723 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
724 "       gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
725 "}\n"
726 "\n"
727 "#else // MODE_WATER\n"
728 "#ifdef MODE_REFRACTION\n"
729 "\n"
730 "// refraction pass\n"
731 "void main(void)\n"
732 "{\n"
733 "#ifdef USEOFFSETMAPPING\n"
734 "       // apply offsetmapping\n"
735 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
736 "#define TexCoord TexCoordOffset\n"
737 "#endif\n"
738 "\n"
739 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
740 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
741 "       vec2 ScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy + vec2(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
742 "       gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
743 "}\n"
744 "\n"
745 "#else // MODE_REFRACTION\n"
746 "void main(void)\n"
747 "{\n"
748 "#ifdef USEOFFSETMAPPING\n"
749 "       // apply offsetmapping\n"
750 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
751 "#define TexCoord TexCoordOffset\n"
752 "#endif\n"
753 "\n"
754 "       // combine the diffuse textures (base, pants, shirt)\n"
755 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
756 "#ifdef USECOLORMAPPING\n"
757 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
758 "#endif\n"
759 "#ifdef USEVERTEXTEXTUREBLEND\n"
760 "       myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
761 "       //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
762 "       //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
763 "       color = mix(myhalf4(texture2D(Texture_SecondaryColor, TexCoord)), color, terrainblend);\n"
764 "       //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
765 "#endif\n"
766 "\n"
767 "#ifdef USEDIFFUSE\n"
768 "       // get the surface normal and the gloss color\n"
769 "# ifdef USEVERTEXTEXTUREBLEND\n"
770 "       myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
771 "#  ifdef USESPECULAR\n"
772 "       myhalf3 glosscolor = mix(myhalf3(texture2D(Texture_SecondaryGloss, TexCoord)), myhalf3(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
773 "#  endif\n"
774 "# else\n"
775 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5));\n"
776 "#  ifdef USESPECULAR\n"
777 "       myhalf3 glosscolor = myhalf3(texture2D(Texture_Gloss, TexCoord));\n"
778 "#  endif\n"
779 "# endif\n"
780 "#endif\n"
781 "\n"
782 "\n"
783 "\n"
784 "#ifdef MODE_LIGHTSOURCE\n"
785 "       // light source\n"
786 "\n"
787 "       // calculate surface normal, light normal, and specular normal\n"
788 "       // compute color intensity for the two textures (colormap and glossmap)\n"
789 "       // scale by light color and attenuation as efficiently as possible\n"
790 "       // (do as much scalar math as possible rather than vector math)\n"
791 "# ifdef USEDIFFUSE\n"
792 "       // get the light normal\n"
793 "       myhalf3 diffusenormal = myhalf3(normalize(LightVector));\n"
794 "# endif\n"
795 "# ifdef USESPECULAR\n"
796 "       myhalf3 specularnormal = normalize(diffusenormal + myhalf3(normalize(EyeVector)));\n"
797 "\n"
798 "       // calculate directional shading\n"
799 "       color.rgb = 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)) * glosscolor);\n"
800 "# else\n"
801 "#  ifdef USEDIFFUSE\n"
802 "       // calculate directional shading\n"
803 "       color.rgb = color.rgb * (myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0))) * (AmbientScale + DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0))));\n"
804 "#  else\n"
805 "       // calculate directionless shading\n"
806 "       color.rgb = color.rgb * myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
807 "#  endif\n"
808 "# endif\n"
809 "\n"
810 "# ifdef USECUBEFILTER\n"
811 "       // apply light cubemap filter\n"
812 "       //color.rgb *= normalize(CubeVector) * 0.5 + 0.5;//vec3(textureCube(Texture_Cube, CubeVector));\n"
813 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
814 "# endif\n"
815 "#endif // MODE_LIGHTSOURCE\n"
816 "\n"
817 "\n"
818 "\n"
819 "\n"
820 "#ifdef MODE_LIGHTDIRECTION\n"
821 "       // directional model lighting\n"
822 "# ifdef USEDIFFUSE\n"
823 "       // get the light normal\n"
824 "       myhalf3 diffusenormal = myhalf3(LightVector);\n"
825 "# endif\n"
826 "# ifdef USESPECULAR\n"
827 "       // calculate directional shading\n"
828 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
829 "       myhalf3 specularnormal = normalize(diffusenormal + myhalf3(normalize(EyeVector)));\n"
830 "       color.rgb += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularColor * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
831 "# else\n"
832 "#  ifdef USEDIFFUSE\n"
833 "\n"
834 "       // calculate directional shading\n"
835 "       color.rgb *= AmbientColor + DiffuseColor * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0));\n"
836 "#  else\n"
837 "       color.rgb *= AmbientColor;\n"
838 "#  endif\n"
839 "# endif\n"
840 "#endif // MODE_LIGHTDIRECTION\n"
841 "\n"
842 "\n"
843 "\n"
844 "\n"
845 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
846 "       // deluxemap lightmapping using light vectors in modelspace (evil q3map2)\n"
847 "\n"
848 "       // get the light normal\n"
849 "       myhalf3 diffusenormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhalf3(0.5);\n"
850 "       myhalf3 diffusenormal = normalize(myhalf3(dot(diffusenormal_modelspace, myhalf3(VectorS)), dot(diffusenormal_modelspace, myhalf3(VectorT)), dot(diffusenormal_modelspace, myhalf3(VectorR))));\n"
851 "       // calculate directional shading\n"
852 "       myhalf3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0)));\n"
853 "# ifdef USESPECULAR\n"
854 "       myhalf3 specularnormal = myhalf3(normalize(diffusenormal + myhalf3(normalize(EyeVector))));\n"
855 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
856 "# endif\n"
857 "\n"
858 "       // apply lightmap color\n"
859 "       color.rgb = color.rgb * AmbientScale + tempcolor * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
860 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
861 "\n"
862 "\n"
863 "\n"
864 "\n"
865 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
866 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
867 "\n"
868 "       // get the light normal\n"
869 "       myhalf3 diffusenormal = normalize(myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) - myhalf3(0.5));\n"
870 "       // calculate directional shading\n"
871 "       myhalf3 tempcolor = color.rgb * (DiffuseScale * myhalf(max(float(dot(surfacenormal, diffusenormal)), 0.0)));\n"
872 "# ifdef USESPECULAR\n"
873 "       myhalf3 specularnormal = myhalf3(normalize(diffusenormal + myhalf3(normalize(EyeVector))));\n"
874 "       tempcolor += myhalf3(texture2D(Texture_Gloss, TexCoord)) * SpecularScale * pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower);\n"
875 "# endif\n"
876 "\n"
877 "       // apply lightmap color\n"
878 "       color.rgb = color.rgb * AmbientScale + tempcolor * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
879 "#endif // MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
880 "\n"
881 "\n"
882 "\n"
883 "\n"
884 "#ifdef MODE_LIGHTMAP\n"
885 "       // apply lightmap color\n"
886 "       color.rgb = color.rgb * myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * DiffuseScale + color.rgb * AmbientScale;\n"
887 "#endif // MODE_LIGHTMAP\n"
888 "\n"
889 "\n"
890 "\n"
891 "\n"
892 "#ifdef MODE_VERTEXCOLOR\n"
893 "       // apply lightmap color\n"
894 "       color.rgb = color.rgb * myhalf3(gl_Color.rgb) * DiffuseScale + color.rgb * AmbientScale;\n"
895 "#endif // MODE_VERTEXCOLOR\n"
896 "\n"
897 "\n"
898 "\n"
899 "\n"
900 "#ifdef MODE_FLATCOLOR\n"
901 "#endif // MODE_FLATCOLOR\n"
902 "\n"
903 "\n"
904 "\n"
905 "\n"
906 "\n"
907 "\n"
908 "\n"
909 "       color *= TintColor;\n"
910 "\n"
911 "#ifdef USEGLOW\n"
912 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * GlowScale;\n"
913 "#endif\n"
914 "\n"
915 "#ifdef USECONTRASTBOOST\n"
916 "       color.rgb = color.rgb / (ContrastBoostCoeff * color.rgb + myhalf3(1, 1, 1));\n"
917 "#endif\n"
918 "\n"
919 "       color.rgb *= SceneBrightness;\n"
920 "\n"
921 "       // apply fog after Contrastboost/SceneBrightness because its color is already modified appropriately\n"
922 "#ifdef USEFOG\n"
923 "       color.rgb = mix(FogColor, color.rgb, myhalf(texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*FogRangeRecip, 0.0))));\n"
924 "#endif\n"
925 "\n"
926 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
927 "#ifdef USEREFLECTION\n"
928 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
929 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
930 "       vec4 ScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xyxy * DistortScaleRefractReflect;\n"
931 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord.zw)) * ReflectColor.rgb, ReflectColor.a);\n"
932 "#endif\n"
933 "\n"
934 "       gl_FragColor = vec4(color);\n"
935 "}\n"
936 "#endif // MODE_REFRACTION\n"
937 "#endif // MODE_WATER\n"
938 "\n"
939 "#endif // FRAGMENT_SHADER\n"
940 ;
941
942 typedef struct shaderpermutationinfo_s
943 {
944         const char *pretext;
945         const char *name;
946 }
947 shaderpermutationinfo_t;
948
949 typedef struct shadermodeinfo_s
950 {
951         const char *vertexfilename;
952         const char *geometryfilename;
953         const char *fragmentfilename;
954         const char *pretext;
955         const char *name;
956 }
957 shadermodeinfo_t;
958
959 typedef enum shaderpermutation_e
960 {
961         SHADERPERMUTATION_DIFFUSE = 1<<0, // (lightsource) whether to use directional shading
962         SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, // indicates this is a two-layer material blend based on vertex alpha (q3bsp)
963         SHADERPERMUTATION_COLORMAPPING = 1<<2, // indicates this is a colormapped skin
964         SHADERPERMUTATION_CONTRASTBOOST = 1<<3, // r_glsl_contrastboost boosts the contrast at low color levels (similar to gamma)
965         SHADERPERMUTATION_FOG = 1<<4, // tint the color by fog color or black if using additive blend mode
966         SHADERPERMUTATION_CUBEFILTER = 1<<5, // (lightsource) use cubemap light filter
967         SHADERPERMUTATION_GLOW = 1<<6, // (lightmap) blend in an additive glow texture
968         SHADERPERMUTATION_SPECULAR = 1<<7, // (lightsource or deluxemapping) render specular effects
969         SHADERPERMUTATION_REFLECTION = 1<<8, // normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
970         SHADERPERMUTATION_OFFSETMAPPING = 1<<9, // adjust texcoords to roughly simulate a displacement mapped surface
971         SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<10, // adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
972         SHADERPERMUTATION_LIMIT = 1<<11, // size of permutations array
973         SHADERPERMUTATION_COUNT = 11 // size of shaderpermutationinfo array
974 }
975 shaderpermutation_t;
976
977 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
978 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
979 {
980         {"#define USEDIFFUSE\n", " diffuse"},
981         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
982         {"#define USECOLORMAPPING\n", " colormapping"},
983         {"#define USECONTRASTBOOST\n", " contrastboost"},
984         {"#define USEFOG\n", " fog"},
985         {"#define USECUBEFILTER\n", " cubefilter"},
986         {"#define USEGLOW\n", " glow"},
987         {"#define USESPECULAR\n", " specular"},
988         {"#define USEREFLECTION\n", " reflection"},
989         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
990         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
991 };
992
993 // this enum is multiplied by SHADERPERMUTATION_MODEBASE
994 typedef enum shadermode_e
995 {
996         SHADERMODE_FLATCOLOR, // (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
997         SHADERMODE_VERTEXCOLOR, // (lightmap) modulate texture by vertex colors (q3bsp)
998         SHADERMODE_LIGHTMAP, // (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
999         SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, // (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
1000         SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, // (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
1001         SHADERMODE_LIGHTDIRECTION, // (lightmap) use directional pixel shading from fixed light direction (q3bsp)
1002         SHADERMODE_LIGHTSOURCE, // (lightsource) use directional pixel shading from light source (rtlight)
1003         SHADERMODE_REFRACTION, // refract background (the material is rendered normally after this pass)
1004         SHADERMODE_WATER, // refract background and reflection (the material is rendered normally after this pass)
1005         SHADERMODE_COUNT
1006 }
1007 shadermode_t;
1008
1009 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
1010 shadermodeinfo_t shadermodeinfo[SHADERMODE_COUNT] =
1011 {
1012         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
1013         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
1014         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
1015         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
1016         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
1017         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
1018         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
1019         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
1020         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
1021 };
1022
1023 typedef struct r_glsl_permutation_s
1024 {
1025         // indicates if we have tried compiling this permutation already
1026         qboolean compiled;
1027         // 0 if compilation failed
1028         int program;
1029         // locations of detected uniforms in program object, or -1 if not found
1030         int loc_Texture_Normal;
1031         int loc_Texture_Color;
1032         int loc_Texture_Gloss;
1033         int loc_Texture_Glow;
1034         int loc_Texture_SecondaryNormal;
1035         int loc_Texture_SecondaryColor;
1036         int loc_Texture_SecondaryGloss;
1037         int loc_Texture_SecondaryGlow;
1038         int loc_Texture_Pants;
1039         int loc_Texture_Shirt;
1040         int loc_Texture_FogMask;
1041         int loc_Texture_Lightmap;
1042         int loc_Texture_Deluxemap;
1043         int loc_Texture_Attenuation;
1044         int loc_Texture_Cube;
1045         int loc_Texture_Refraction;
1046         int loc_Texture_Reflection;
1047         int loc_FogColor;
1048         int loc_LightPosition;
1049         int loc_EyePosition;
1050         int loc_Color_Pants;
1051         int loc_Color_Shirt;
1052         int loc_FogRangeRecip;
1053         int loc_AmbientScale;
1054         int loc_DiffuseScale;
1055         int loc_SpecularScale;
1056         int loc_SpecularPower;
1057         int loc_GlowScale;
1058         int loc_SceneBrightness; // or: Scenebrightness * ContrastBoost
1059         int loc_OffsetMapping_Scale;
1060         int loc_TintColor;
1061         int loc_AmbientColor;
1062         int loc_DiffuseColor;
1063         int loc_SpecularColor;
1064         int loc_LightDir;
1065         int loc_ContrastBoostCoeff; // 1 - 1/ContrastBoost
1066         int loc_DistortScaleRefractReflect;
1067         int loc_ScreenScaleRefractReflect;
1068         int loc_ScreenCenterRefractReflect;
1069         int loc_RefractColor;
1070         int loc_ReflectColor;
1071         int loc_ReflectFactor;
1072         int loc_ReflectOffset;
1073 }
1074 r_glsl_permutation_t;
1075
1076 // information about each possible shader permutation
1077 r_glsl_permutation_t r_glsl_permutations[SHADERMODE_COUNT][SHADERPERMUTATION_LIMIT];
1078 // currently selected permutation
1079 r_glsl_permutation_t *r_glsl_permutation;
1080
1081 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
1082 {
1083         char *shaderstring;
1084         if (!filename || !filename[0])
1085                 return NULL;
1086         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
1087         if (shaderstring)
1088         {
1089                 if (printfromdisknotice)
1090                         Con_DPrint("from disk... ");
1091                 return shaderstring;
1092         }
1093         else if (!strcmp(filename, "glsl/default.glsl"))
1094         {
1095                 shaderstring = Mem_Alloc(r_main_mempool, strlen(builtinshaderstring) + 1);
1096                 memcpy(shaderstring, builtinshaderstring, strlen(builtinshaderstring) + 1);
1097         }
1098         return shaderstring;
1099 }
1100
1101 static void R_GLSL_CompilePermutation(shadermode_t mode, shaderpermutation_t permutation)
1102 {
1103         int i;
1104         shadermodeinfo_t *modeinfo = shadermodeinfo + mode;
1105         r_glsl_permutation_t *p = &r_glsl_permutations[mode][permutation];
1106         int vertstrings_count = 0;
1107         int geomstrings_count = 0;
1108         int fragstrings_count = 0;
1109         char *vertexstring, *geometrystring, *fragmentstring;
1110         const char *vertstrings_list[32+3];
1111         const char *geomstrings_list[32+3];
1112         const char *fragstrings_list[32+3];
1113         char permutationname[256];
1114
1115         if (p->compiled)
1116                 return;
1117         p->compiled = true;
1118         p->program = 0;
1119
1120         permutationname[0] = 0;
1121         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
1122         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
1123         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
1124
1125         strlcat(permutationname, shadermodeinfo[mode].vertexfilename, sizeof(permutationname));
1126
1127         // the first pretext is which type of shader to compile as
1128         // (later these will all be bound together as a program object)
1129         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
1130         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
1131         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
1132
1133         // the second pretext is the mode (for example a light source)
1134         vertstrings_list[vertstrings_count++] = shadermodeinfo[mode].pretext;
1135         geomstrings_list[geomstrings_count++] = shadermodeinfo[mode].pretext;
1136         fragstrings_list[fragstrings_count++] = shadermodeinfo[mode].pretext;
1137         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
1138
1139         // now add all the permutation pretexts
1140         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1141         {
1142                 if (permutation & (1<<i))
1143                 {
1144                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
1145                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
1146                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
1147                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
1148                 }
1149                 else
1150                 {
1151                         // keep line numbers correct
1152                         vertstrings_list[vertstrings_count++] = "\n";
1153                         geomstrings_list[geomstrings_count++] = "\n";
1154                         fragstrings_list[fragstrings_count++] = "\n";
1155                 }
1156         }
1157
1158         // now append the shader text itself
1159         vertstrings_list[vertstrings_count++] = vertexstring;
1160         geomstrings_list[geomstrings_count++] = geometrystring;
1161         fragstrings_list[fragstrings_count++] = fragmentstring;
1162
1163         // if any sources were NULL, clear the respective list
1164         if (!vertexstring)
1165                 vertstrings_count = 0;
1166         if (!geometrystring)
1167                 geomstrings_count = 0;
1168         if (!fragmentstring)
1169                 fragstrings_count = 0;
1170
1171         // compile the shader program
1172         if (vertstrings_count + geomstrings_count + fragstrings_count)
1173                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
1174         if (p->program)
1175         {
1176                 CHECKGLERROR
1177                 qglUseProgramObjectARB(p->program);CHECKGLERROR
1178                 // look up all the uniform variable names we care about, so we don't
1179                 // have to look them up every time we set them
1180                 p->loc_Texture_Normal             = qglGetUniformLocationARB(p->program, "Texture_Normal");
1181                 p->loc_Texture_Color              = qglGetUniformLocationARB(p->program, "Texture_Color");
1182                 p->loc_Texture_Gloss              = qglGetUniformLocationARB(p->program, "Texture_Gloss");
1183                 p->loc_Texture_Glow               = qglGetUniformLocationARB(p->program, "Texture_Glow");
1184                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
1185                 p->loc_Texture_SecondaryColor     = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
1186                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
1187                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
1188                 p->loc_Texture_FogMask            = qglGetUniformLocationARB(p->program, "Texture_FogMask");
1189                 p->loc_Texture_Pants              = qglGetUniformLocationARB(p->program, "Texture_Pants");
1190                 p->loc_Texture_Shirt              = qglGetUniformLocationARB(p->program, "Texture_Shirt");
1191                 p->loc_Texture_Lightmap           = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
1192                 p->loc_Texture_Deluxemap          = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
1193                 p->loc_Texture_Refraction         = qglGetUniformLocationARB(p->program, "Texture_Refraction");
1194                 p->loc_Texture_Reflection         = qglGetUniformLocationARB(p->program, "Texture_Reflection");
1195                 p->loc_Texture_Attenuation        = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
1196                 p->loc_Texture_Cube               = qglGetUniformLocationARB(p->program, "Texture_Cube");
1197                 p->loc_FogColor                   = qglGetUniformLocationARB(p->program, "FogColor");
1198                 p->loc_LightPosition              = qglGetUniformLocationARB(p->program, "LightPosition");
1199                 p->loc_EyePosition                = qglGetUniformLocationARB(p->program, "EyePosition");
1200                 p->loc_Color_Pants                = qglGetUniformLocationARB(p->program, "Color_Pants");
1201                 p->loc_Color_Shirt                = qglGetUniformLocationARB(p->program, "Color_Shirt");
1202                 p->loc_FogRangeRecip              = qglGetUniformLocationARB(p->program, "FogRangeRecip");
1203                 p->loc_AmbientScale               = qglGetUniformLocationARB(p->program, "AmbientScale");
1204                 p->loc_DiffuseScale               = qglGetUniformLocationARB(p->program, "DiffuseScale");
1205                 p->loc_SpecularPower              = qglGetUniformLocationARB(p->program, "SpecularPower");
1206                 p->loc_SpecularScale              = qglGetUniformLocationARB(p->program, "SpecularScale");
1207                 p->loc_GlowScale                  = qglGetUniformLocationARB(p->program, "GlowScale");
1208                 p->loc_SceneBrightness            = qglGetUniformLocationARB(p->program, "SceneBrightness");
1209                 p->loc_OffsetMapping_Scale        = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
1210                 p->loc_TintColor                  = qglGetUniformLocationARB(p->program, "TintColor");
1211                 p->loc_AmbientColor               = qglGetUniformLocationARB(p->program, "AmbientColor");
1212                 p->loc_DiffuseColor               = qglGetUniformLocationARB(p->program, "DiffuseColor");
1213                 p->loc_SpecularColor              = qglGetUniformLocationARB(p->program, "SpecularColor");
1214                 p->loc_LightDir                   = qglGetUniformLocationARB(p->program, "LightDir");
1215                 p->loc_ContrastBoostCoeff         = qglGetUniformLocationARB(p->program, "ContrastBoostCoeff");
1216                 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
1217                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
1218                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
1219                 p->loc_RefractColor               = qglGetUniformLocationARB(p->program, "RefractColor");
1220                 p->loc_ReflectColor               = qglGetUniformLocationARB(p->program, "ReflectColor");
1221                 p->loc_ReflectFactor              = qglGetUniformLocationARB(p->program, "ReflectFactor");
1222                 p->loc_ReflectOffset              = qglGetUniformLocationARB(p->program, "ReflectOffset");
1223                 // initialize the samplers to refer to the texture units we use
1224                 if (p->loc_Texture_Normal          >= 0) qglUniform1iARB(p->loc_Texture_Normal         , GL20TU_NORMAL);
1225                 if (p->loc_Texture_Color           >= 0) qglUniform1iARB(p->loc_Texture_Color          , GL20TU_COLOR);
1226                 if (p->loc_Texture_Gloss           >= 0) qglUniform1iARB(p->loc_Texture_Gloss          , GL20TU_GLOSS);
1227                 if (p->loc_Texture_Glow            >= 0) qglUniform1iARB(p->loc_Texture_Glow           , GL20TU_GLOW);
1228                 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
1229                 if (p->loc_Texture_SecondaryColor  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
1230                 if (p->loc_Texture_SecondaryGloss  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
1231                 if (p->loc_Texture_SecondaryGlow   >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow  , GL20TU_SECONDARY_GLOW);
1232                 if (p->loc_Texture_Pants           >= 0) qglUniform1iARB(p->loc_Texture_Pants          , GL20TU_PANTS);
1233                 if (p->loc_Texture_Shirt           >= 0) qglUniform1iARB(p->loc_Texture_Shirt          , GL20TU_SHIRT);
1234                 if (p->loc_Texture_FogMask         >= 0) qglUniform1iARB(p->loc_Texture_FogMask        , GL20TU_FOGMASK);
1235                 if (p->loc_Texture_Lightmap        >= 0) qglUniform1iARB(p->loc_Texture_Lightmap       , GL20TU_LIGHTMAP);
1236                 if (p->loc_Texture_Deluxemap       >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap      , GL20TU_DELUXEMAP);
1237                 if (p->loc_Texture_Attenuation     >= 0) qglUniform1iARB(p->loc_Texture_Attenuation    , GL20TU_ATTENUATION);
1238                 if (p->loc_Texture_Cube            >= 0) qglUniform1iARB(p->loc_Texture_Cube           , GL20TU_CUBE);
1239                 if (p->loc_Texture_Refraction      >= 0) qglUniform1iARB(p->loc_Texture_Refraction     , GL20TU_REFRACTION);
1240                 if (p->loc_Texture_Reflection      >= 0) qglUniform1iARB(p->loc_Texture_Reflection     , GL20TU_REFLECTION);
1241                 CHECKGLERROR
1242                 qglUseProgramObjectARB(0);CHECKGLERROR
1243                 if (developer.integer)
1244                         Con_Printf("GLSL shader %s compiled.\n", permutationname);
1245         }
1246         else
1247                 Con_Printf("GLSL shader %s failed!  some features may not work properly.\n", permutationname);
1248
1249         // free the strings
1250         if (vertexstring)
1251                 Mem_Free(vertexstring);
1252         if (geometrystring)
1253                 Mem_Free(geometrystring);
1254         if (fragmentstring)
1255                 Mem_Free(fragmentstring);
1256 }
1257
1258 void R_GLSL_Restart_f(void)
1259 {
1260         shadermode_t mode;
1261         shaderpermutation_t permutation;
1262         for (mode = 0;mode < SHADERMODE_COUNT;mode++)
1263                 for (permutation = 0;permutation < SHADERPERMUTATION_LIMIT;permutation++)
1264                         if (r_glsl_permutations[mode][permutation].program)
1265                                 GL_Backend_FreeProgram(r_glsl_permutations[mode][permutation].program);
1266         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
1267 }
1268
1269 void R_GLSL_DumpShader_f(void)
1270 {
1271         int i;
1272
1273         qfile_t *file = FS_Open("glsl/default.glsl", "w", false, false);
1274         if(!file)
1275         {
1276                 Con_Printf("failed to write to glsl/default.glsl\n");
1277                 return;
1278         }
1279
1280         FS_Print(file, "// The engine may define the following macros:\n");
1281         FS_Print(file, "// #define VERTEX_SHADER\n// #define GEOMETRY_SHADER\n// #define FRAGMENT_SHADER\n");
1282         for (i = 0;i < SHADERMODE_COUNT;i++)
1283                 FS_Printf(file, "// %s", shadermodeinfo[i].pretext);
1284         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1285                 FS_Printf(file, "// %s", shaderpermutationinfo[i].pretext);
1286         FS_Print(file, "\n");
1287         FS_Print(file, builtinshaderstring);
1288         FS_Close(file);
1289
1290         Con_Printf("glsl/default.glsl written\n");
1291 }
1292
1293 extern rtexture_t *r_shadow_attenuationgradienttexture;
1294 extern rtexture_t *r_shadow_attenuation2dtexture;
1295 extern rtexture_t *r_shadow_attenuation3dtexture;
1296 int R_SetupSurfaceShader(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass)
1297 {
1298         // select a permutation of the lighting shader appropriate to this
1299         // combination of texture, entity, light source, and fogging, only use the
1300         // minimum features necessary to avoid wasting rendering time in the
1301         // fragment shader on features that are not being used
1302         unsigned int permutation = 0;
1303         shadermode_t mode = 0;
1304         r_glsl_permutation = NULL;
1305         // TODO: implement geometry-shader based shadow volumes someday
1306         if (r_glsl_offsetmapping.integer)
1307         {
1308                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
1309                 if (r_glsl_offsetmapping_reliefmapping.integer)
1310                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
1311         }
1312         if (rsurfacepass == RSURFPASS_BACKGROUND)
1313         {
1314                 // distorted background
1315                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
1316                         mode = SHADERMODE_WATER;
1317                 else
1318                         mode = SHADERMODE_REFRACTION;
1319         }
1320         else if (rsurfacepass == RSURFPASS_RTLIGHT)
1321         {
1322                 // light source
1323                 mode = SHADERMODE_LIGHTSOURCE;
1324                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
1325                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1326                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
1327                         permutation |= SHADERPERMUTATION_CUBEFILTER;
1328                 if (diffusescale > 0)
1329                         permutation |= SHADERPERMUTATION_DIFFUSE;
1330                 if (specularscale > 0)
1331                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
1332                 if (r_refdef.fogenabled)
1333                         permutation |= SHADERPERMUTATION_FOG;
1334                 if (rsurface.texture->colormapping)
1335                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1336                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1337                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1338         }
1339         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
1340         {
1341                 // unshaded geometry (fullbright or ambient model lighting)
1342                 mode = SHADERMODE_FLATCOLOR;
1343                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
1344                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1345                 if (rsurface.texture->currentskinframe->glow)
1346                         permutation |= SHADERPERMUTATION_GLOW;
1347                 if (r_refdef.fogenabled)
1348                         permutation |= SHADERPERMUTATION_FOG;
1349                 if (rsurface.texture->colormapping)
1350                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1351                 if (r_glsl_offsetmapping.integer)
1352                 {
1353                         permutation |= SHADERPERMUTATION_OFFSETMAPPING;
1354                         if (r_glsl_offsetmapping_reliefmapping.integer)
1355                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
1356                 }
1357                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1358                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1359                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1360                         permutation |= SHADERPERMUTATION_REFLECTION;
1361         }
1362         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
1363         {
1364                 // directional model lighting
1365                 mode = SHADERMODE_LIGHTDIRECTION;
1366                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
1367                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1368                 if (rsurface.texture->currentskinframe->glow)
1369                         permutation |= SHADERPERMUTATION_GLOW;
1370                 permutation |= SHADERPERMUTATION_DIFFUSE;
1371                 if (specularscale > 0)
1372                         permutation |= SHADERPERMUTATION_SPECULAR;
1373                 if (r_refdef.fogenabled)
1374                         permutation |= SHADERPERMUTATION_FOG;
1375                 if (rsurface.texture->colormapping)
1376                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1377                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1378                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1379                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1380                         permutation |= SHADERPERMUTATION_REFLECTION;
1381         }
1382         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
1383         {
1384                 // ambient model lighting
1385                 mode = SHADERMODE_LIGHTDIRECTION;
1386                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
1387                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1388                 if (rsurface.texture->currentskinframe->glow)
1389                         permutation |= SHADERPERMUTATION_GLOW;
1390                 if (r_refdef.fogenabled)
1391                         permutation |= SHADERPERMUTATION_FOG;
1392                 if (rsurface.texture->colormapping)
1393                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1394                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1395                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1396                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1397                         permutation |= SHADERPERMUTATION_REFLECTION;
1398         }
1399         else
1400         {
1401                 // lightmapped wall
1402                 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
1403                 {
1404                         // deluxemapping (light direction texture)
1405                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
1406                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
1407                         else
1408                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
1409                         permutation |= SHADERPERMUTATION_DIFFUSE;
1410                         if (specularscale > 0)
1411                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
1412                 }
1413                 else if (r_glsl_deluxemapping.integer >= 2)
1414                 {
1415                         // fake deluxemapping (uniform light direction in tangentspace)
1416                         mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
1417                         permutation |= SHADERPERMUTATION_DIFFUSE;
1418                         if (specularscale > 0)
1419                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
1420                 }
1421                 else if (rsurface.uselightmaptexture)
1422                 {
1423                         // ordinary lightmapping (q1bsp, q3bsp)
1424                         mode = SHADERMODE_LIGHTMAP;
1425                 }
1426                 else
1427                 {
1428                         // ordinary vertex coloring (q3bsp)
1429                         mode = SHADERMODE_VERTEXCOLOR;
1430                 }
1431                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
1432                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
1433                 if (rsurface.texture->currentskinframe->glow)
1434                         permutation |= SHADERPERMUTATION_GLOW;
1435                 if (r_refdef.fogenabled)
1436                         permutation |= SHADERPERMUTATION_FOG;
1437                 if (rsurface.texture->colormapping)
1438                         permutation |= SHADERPERMUTATION_COLORMAPPING;
1439                 if(r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)
1440                         permutation |= SHADERPERMUTATION_CONTRASTBOOST;
1441                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
1442                         permutation |= SHADERPERMUTATION_REFLECTION;
1443         }
1444         r_glsl_permutation = &r_glsl_permutations[mode][permutation];
1445         if (!r_glsl_permutation->program)
1446         {
1447                 if (!r_glsl_permutation->compiled)
1448                         R_GLSL_CompilePermutation(mode, permutation);
1449                 if (!r_glsl_permutation->program)
1450                 {
1451                         // remove features until we find a valid permutation
1452                         int i;
1453                         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
1454                         {
1455                                 // reduce i more quickly whenever it would not remove any bits
1456                                 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
1457                                 if (!(permutation & j))
1458                                         continue;
1459                                 permutation -= j;
1460                                 r_glsl_permutation = &r_glsl_permutations[mode][permutation];
1461                                 if (!r_glsl_permutation->compiled)
1462                                         R_GLSL_CompilePermutation(mode, permutation);
1463                                 if (r_glsl_permutation->program)
1464                                         break;
1465                         }
1466                         if (i >= SHADERPERMUTATION_COUNT)
1467                         {
1468                                 Con_Printf("OpenGL 2.0 shaders disabled - unable to find a working shader permutation fallback on this driver (set r_glsl 1 if you want to try again)\n");
1469                                 Cvar_SetValueQuick(&r_glsl, 0);
1470                                 return 0; // no bit left to clear
1471                         }
1472                 }
1473         }
1474         CHECKGLERROR
1475         qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
1476         if (mode == SHADERMODE_LIGHTSOURCE)
1477         {
1478                 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
1479                 if (permutation & SHADERPERMUTATION_DIFFUSE)
1480                 {
1481                         if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2], rsurface.texture->lightmapcolor[3]);
1482                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, ambientscale);
1483                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, diffusescale);
1484                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, specularscale);
1485                 }
1486                 else
1487                 {
1488                         // ambient only is simpler
1489                         if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, lightcolorbase[0] * ambientscale, lightcolorbase[1] * ambientscale, lightcolorbase[2] * ambientscale, rsurface.texture->lightmapcolor[3]);
1490                         if (r_glsl_permutation->loc_AmbientScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, 1);
1491                         if (r_glsl_permutation->loc_DiffuseScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, 0);
1492                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, 0);
1493                 }
1494                 // additive passes are only darkened by fog, not tinted
1495                 if (r_glsl_permutation->loc_FogColor >= 0)
1496                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
1497         }
1498         else
1499         {
1500                 if (mode == SHADERMODE_LIGHTDIRECTION)
1501                 {
1502                         if (r_glsl_permutation->loc_AmbientColor  >= 0) qglUniform3fARB(r_glsl_permutation->loc_AmbientColor , rsurface.modellight_ambient[0] * ambientscale  * 0.5f, rsurface.modellight_ambient[1] * ambientscale  * 0.5f, rsurface.modellight_ambient[2] * ambientscale  * 0.5f);
1503                         if (r_glsl_permutation->loc_DiffuseColor  >= 0) qglUniform3fARB(r_glsl_permutation->loc_DiffuseColor , rsurface.modellight_diffuse[0] * diffusescale  * 0.5f, rsurface.modellight_diffuse[1] * diffusescale  * 0.5f, rsurface.modellight_diffuse[2] * diffusescale  * 0.5f);
1504                         if (r_glsl_permutation->loc_SpecularColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_SpecularColor, rsurface.modellight_diffuse[0] * specularscale * 0.5f, rsurface.modellight_diffuse[1] * specularscale * 0.5f, rsurface.modellight_diffuse[2] * specularscale * 0.5f);
1505                         if (r_glsl_permutation->loc_LightDir      >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
1506                 }
1507                 else
1508                 {
1509                         if (r_glsl_permutation->loc_AmbientScale  >= 0) qglUniform1fARB(r_glsl_permutation->loc_AmbientScale, r_ambient.value * 1.0f / 128.0f);
1510                         if (r_glsl_permutation->loc_DiffuseScale  >= 0) qglUniform1fARB(r_glsl_permutation->loc_DiffuseScale, r_refdef.lightmapintensity);
1511                         if (r_glsl_permutation->loc_SpecularScale >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularScale, r_refdef.lightmapintensity * specularscale);
1512                 }
1513                 if (r_glsl_permutation->loc_TintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_TintColor, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2], rsurface.texture->lightmapcolor[3]);
1514                 if (r_glsl_permutation->loc_GlowScale     >= 0) qglUniform1fARB(r_glsl_permutation->loc_GlowScale, r_hdr_glowintensity.value);
1515                 // additive passes are only darkened by fog, not tinted
1516                 if (r_glsl_permutation->loc_FogColor >= 0)
1517                 {
1518                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
1519                                 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
1520                         else
1521                                 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
1522                 }
1523                 if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
1524                 if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
1525                 if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
1526                 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
1527                 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
1528                 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
1529                 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
1530         }
1531         if (r_glsl_permutation->loc_ContrastBoostCoeff >= 0)
1532         {
1533                 // The formula used is actually:
1534                 //   color.rgb *= ContrastBoost / ((ContrastBoost - 1) * color.rgb + 1);
1535                 //   color.rgb *= SceneBrightness;
1536                 // simplified:
1537                 //   color.rgb = [[SceneBrightness * ContrastBoost]] * color.rgb / ([[ContrastBoost - 1]] * color.rgb + 1);
1538                 // and do [[calculations]] here in the engine
1539                 qglUniform1fARB(r_glsl_permutation->loc_ContrastBoostCoeff, r_glsl_contrastboost.value - 1);
1540                 if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_refdef.view.colorscale * r_glsl_contrastboost.value);
1541         }
1542         else
1543                 if (r_glsl_permutation->loc_SceneBrightness >= 0) qglUniform1fARB(r_glsl_permutation->loc_SceneBrightness, r_refdef.view.colorscale);
1544         if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.modelorg[0], rsurface.modelorg[1], rsurface.modelorg[2]);
1545         if (r_glsl_permutation->loc_Color_Pants >= 0)
1546         {
1547                 if (rsurface.texture->currentskinframe->pants)
1548                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
1549                 else
1550                         qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
1551         }
1552         if (r_glsl_permutation->loc_Color_Shirt >= 0)
1553         {
1554                 if (rsurface.texture->currentskinframe->shirt)
1555                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
1556                 else
1557                         qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
1558         }
1559         if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, r_refdef.fograngerecip);
1560         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower);
1561         if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
1562         CHECKGLERROR
1563         return permutation;
1564 }
1565
1566 #define SKINFRAME_HASH 1024
1567
1568 struct
1569 {
1570         int loadsequence; // incremented each level change
1571         memexpandablearray_t array;
1572         skinframe_t *hash[SKINFRAME_HASH];
1573 }
1574 r_skinframe;
1575
1576 void R_SkinFrame_PrepareForPurge(void)
1577 {
1578         r_skinframe.loadsequence++;
1579         // wrap it without hitting zero
1580         if (r_skinframe.loadsequence >= 200)
1581                 r_skinframe.loadsequence = 1;
1582 }
1583
1584 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
1585 {
1586         if (!skinframe)
1587                 return;
1588         // mark the skinframe as used for the purging code
1589         skinframe->loadsequence = r_skinframe.loadsequence;
1590 }
1591
1592 void R_SkinFrame_Purge(void)
1593 {
1594         int i;
1595         skinframe_t *s;
1596         for (i = 0;i < SKINFRAME_HASH;i++)
1597         {
1598                 for (s = r_skinframe.hash[i];s;s = s->next)
1599                 {
1600                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
1601                         {
1602                                 if (s->merged == s->base)
1603                                         s->merged = NULL;
1604                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
1605                                 R_PurgeTexture(s->stain );s->stain  = NULL;
1606                                 R_PurgeTexture(s->merged);s->merged = NULL;
1607                                 R_PurgeTexture(s->base  );s->base   = NULL;
1608                                 R_PurgeTexture(s->pants );s->pants  = NULL;
1609                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
1610                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
1611                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
1612                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
1613                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
1614                                 s->loadsequence = 0;
1615                         }
1616                 }
1617         }
1618 }
1619
1620 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
1621         skinframe_t *item;
1622         char basename[MAX_QPATH];
1623
1624         Image_StripImageExtension(name, basename, sizeof(basename));
1625
1626         if( last == NULL ) {
1627                 int hashindex;
1628                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
1629                 item = r_skinframe.hash[hashindex];
1630         } else {
1631                 item = last->next;
1632         }
1633
1634         // linearly search through the hash bucket
1635         for( ; item ; item = item->next ) {
1636                 if( !strcmp( item->basename, basename ) ) {
1637                         return item;
1638                 }
1639         }
1640         return NULL;
1641 }
1642
1643 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
1644 {
1645         skinframe_t *item;
1646         int hashindex;
1647         char basename[MAX_QPATH];
1648
1649         Image_StripImageExtension(name, basename, sizeof(basename));
1650
1651         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
1652         for (item = r_skinframe.hash[hashindex];item;item = item->next)
1653                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
1654                         break;
1655
1656         if (!item) {
1657                 rtexture_t *dyntexture;
1658                 // check whether its a dynamic texture
1659                 dyntexture = CL_GetDynTexture( basename );
1660                 if (!add && !dyntexture)
1661                         return NULL;
1662                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
1663                 memset(item, 0, sizeof(*item));
1664                 strlcpy(item->basename, basename, sizeof(item->basename));
1665                 item->base = dyntexture; // either NULL or dyntexture handle
1666                 item->textureflags = textureflags;
1667                 item->comparewidth = comparewidth;
1668                 item->compareheight = compareheight;
1669                 item->comparecrc = comparecrc;
1670                 item->next = r_skinframe.hash[hashindex];
1671                 r_skinframe.hash[hashindex] = item;
1672         }
1673         else if( item->base == NULL )
1674         {
1675                 rtexture_t *dyntexture;
1676                 // check whether its a dynamic texture
1677                 // this only needs to be done because Purge doesnt delete skinframes - only sets the texture pointers to NULL and we need to restore it before returing.. [11/29/2007 Black]
1678                 dyntexture = CL_GetDynTexture( basename );
1679                 item->base = dyntexture; // either NULL or dyntexture handle
1680         }
1681
1682         R_SkinFrame_MarkUsed(item);
1683         return item;
1684 }
1685
1686 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
1687 {
1688         // FIXME: it should be possible to disable loading various layers using
1689         // cvars, to prevent wasted loading time and memory usage if the user does
1690         // not want them
1691         qboolean loadnormalmap = true;
1692         qboolean loadgloss = true;
1693         qboolean loadpantsandshirt = true;
1694         qboolean loadglow = true;
1695         int j;
1696         unsigned char *pixels;
1697         unsigned char *bumppixels;
1698         unsigned char *basepixels = NULL;
1699         int basepixels_width;
1700         int basepixels_height;
1701         skinframe_t *skinframe;
1702
1703         if (cls.state == ca_dedicated)
1704                 return NULL;
1705
1706         // return an existing skinframe if already loaded
1707         // if loading of the first image fails, don't make a new skinframe as it
1708         // would cause all future lookups of this to be missing
1709         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
1710         if (skinframe && skinframe->base)
1711                 return skinframe;
1712
1713         basepixels = loadimagepixelsbgra(name, complain, true);
1714         if (basepixels == NULL)
1715                 return NULL;
1716
1717         // we've got some pixels to store, so really allocate this new texture now
1718         if (!skinframe)
1719                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
1720         skinframe->stain = NULL;
1721         skinframe->merged = NULL;
1722         skinframe->base = r_texture_notexture;
1723         skinframe->pants = NULL;
1724         skinframe->shirt = NULL;
1725         skinframe->nmap = r_texture_blanknormalmap;
1726         skinframe->gloss = NULL;
1727         skinframe->glow = NULL;
1728         skinframe->fog = NULL;
1729
1730         basepixels_width = image_width;
1731         basepixels_height = image_height;
1732         skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1733
1734         if (textureflags & TEXF_ALPHA)
1735         {
1736                 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
1737                         if (basepixels[j] < 255)
1738                                 break;
1739                 if (j < basepixels_width * basepixels_height * 4)
1740                 {
1741                         // has transparent pixels
1742                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1743                         for (j = 0;j < image_width * image_height * 4;j += 4)
1744                         {
1745                                 pixels[j+0] = 255;
1746                                 pixels[j+1] = 255;
1747                                 pixels[j+2] = 255;
1748                                 pixels[j+3] = basepixels[j+3];
1749                         }
1750                         skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1751                         Mem_Free(pixels);
1752                 }
1753         }
1754
1755         // _norm is the name used by tenebrae and has been adopted as standard
1756         if (loadnormalmap)
1757         {
1758                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false)) != NULL)
1759                 {
1760                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1761                         Mem_Free(pixels);
1762                         pixels = NULL;
1763                 }
1764                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false)) != NULL)
1765                 {
1766                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
1767                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
1768                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1769                         Mem_Free(pixels);
1770                         Mem_Free(bumppixels);
1771                 }
1772                 else if (r_shadow_bumpscale_basetexture.value > 0)
1773                 {
1774                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
1775                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
1776                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
1777                         Mem_Free(pixels);
1778                 }
1779         }
1780         // _luma is supported for tenebrae compatibility
1781         // (I think it's a very stupid name, but oh well)
1782         // _glow is the preferred name
1783         if (loadglow          && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false)) != NULL || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false)) != NULL)) {skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1784         if (loadgloss         && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false)) != NULL) {skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1785         if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false)) != NULL) {skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1786         if (loadpantsandshirt && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false)) != NULL) {skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);Mem_Free(pixels);pixels = NULL;}
1787
1788         if (basepixels)
1789                 Mem_Free(basepixels);
1790
1791         return skinframe;
1792 }
1793
1794 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)
1795 {
1796         int i;
1797         if (!force)
1798         {
1799                 for (i = 0;i < width*height;i++)
1800                         if (((unsigned char *)&palette[in[i]])[3] > 0)
1801                                 break;
1802                 if (i == width*height)
1803                         return NULL;
1804         }
1805         return R_LoadTexture2D (r_main_texturepool, name, width, height, in, TEXTYPE_PALETTE, textureflags, palette);
1806 }
1807
1808 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
1809 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
1810 {
1811         int i;
1812         unsigned char *temp1, *temp2;
1813         skinframe_t *skinframe;
1814
1815         if (cls.state == ca_dedicated)
1816                 return NULL;
1817
1818         // if already loaded just return it, otherwise make a new skinframe
1819         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
1820         if (skinframe && skinframe->base)
1821                 return skinframe;
1822
1823         skinframe->stain = NULL;
1824         skinframe->merged = NULL;
1825         skinframe->base = r_texture_notexture;
1826         skinframe->pants = NULL;
1827         skinframe->shirt = NULL;
1828         skinframe->nmap = r_texture_blanknormalmap;
1829         skinframe->gloss = NULL;
1830         skinframe->glow = NULL;
1831         skinframe->fog = NULL;
1832
1833         // if no data was provided, then clearly the caller wanted to get a blank skinframe
1834         if (!skindata)
1835                 return NULL;
1836
1837         if (r_shadow_bumpscale_basetexture.value > 0)
1838         {
1839                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1840                 temp2 = temp1 + width * height * 4;
1841                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1842                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
1843                 Mem_Free(temp1);
1844         }
1845         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, NULL);
1846         if (textureflags & TEXF_ALPHA)
1847         {
1848                 for (i = 3;i < width * height * 4;i += 4)
1849                         if (skindata[i] < 255)
1850                                 break;
1851                 if (i < width * height * 4)
1852                 {
1853                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
1854                         memcpy(fogpixels, skindata, width * height * 4);
1855                         for (i = 0;i < width * height * 4;i += 4)
1856                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
1857                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, NULL);
1858                         Mem_Free(fogpixels);
1859                 }
1860         }
1861
1862         return skinframe;
1863 }
1864
1865 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
1866 {
1867         int i;
1868         unsigned char *temp1, *temp2;
1869         skinframe_t *skinframe;
1870
1871         if (cls.state == ca_dedicated)
1872                 return NULL;
1873
1874         // if already loaded just return it, otherwise make a new skinframe
1875         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
1876         if (skinframe && skinframe->base)
1877                 return skinframe;
1878
1879         skinframe->stain = NULL;
1880         skinframe->merged = NULL;
1881         skinframe->base = r_texture_notexture;
1882         skinframe->pants = NULL;
1883         skinframe->shirt = NULL;
1884         skinframe->nmap = r_texture_blanknormalmap;
1885         skinframe->gloss = NULL;
1886         skinframe->glow = NULL;
1887         skinframe->fog = NULL;
1888
1889         // if no data was provided, then clearly the caller wanted to get a blank skinframe
1890         if (!skindata)
1891                 return NULL;
1892
1893         if (r_shadow_bumpscale_basetexture.value > 0)
1894         {
1895                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
1896                 temp2 = temp1 + width * height * 4;
1897                 // use either a custom palette or the quake palette
1898                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
1899                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
1900                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
1901                 Mem_Free(temp1);
1902         }
1903         // use either a custom palette, or the quake palette
1904         skinframe->base = skinframe->merged = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_merged", skinframe->basename), (loadglowtexture ? palette_bgra_nofullbrights : ((skinframe->textureflags & TEXF_ALPHA) ? palette_bgra_transparent : palette_bgra_complete)), skinframe->textureflags, true); // all
1905         if (loadglowtexture)
1906                 skinframe->glow = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_glow", skinframe->basename), palette_bgra_onlyfullbrights, skinframe->textureflags, false); // glow
1907         if (loadpantsandshirt)
1908         {
1909                 skinframe->pants = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_pants", skinframe->basename), palette_bgra_pantsaswhite, skinframe->textureflags, false); // pants
1910                 skinframe->shirt = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_shirt", skinframe->basename), palette_bgra_shirtaswhite, skinframe->textureflags, false); // shirt
1911         }
1912         if (skinframe->pants || skinframe->shirt)
1913                 skinframe->base = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_nospecial", skinframe->basename), loadglowtexture ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap, skinframe->textureflags, false); // no special colors
1914         if (textureflags & TEXF_ALPHA)
1915         {
1916                 for (i = 0;i < width * height;i++)
1917                         if (((unsigned char *)palette_bgra_alpha)[skindata[i]*4+3] < 255)
1918                                 break;
1919                 if (i < width * height)
1920                         skinframe->fog = R_SkinFrame_TextureForSkinLayer(skindata, width, height, va("%s_fog", skinframe->basename), palette_bgra_alpha, skinframe->textureflags, true); // fog mask
1921         }
1922
1923         return skinframe;
1924 }
1925
1926 skinframe_t *R_SkinFrame_LoadMissing(void)
1927 {
1928         skinframe_t *skinframe;
1929
1930         if (cls.state == ca_dedicated)
1931                 return NULL;
1932
1933         skinframe = R_SkinFrame_Find("missing", TEXF_PRECACHE, 0, 0, 0, true);
1934         skinframe->stain = NULL;
1935         skinframe->merged = NULL;
1936         skinframe->base = r_texture_notexture;
1937         skinframe->pants = NULL;
1938         skinframe->shirt = NULL;
1939         skinframe->nmap = r_texture_blanknormalmap;
1940         skinframe->gloss = NULL;
1941         skinframe->glow = NULL;
1942         skinframe->fog = NULL;
1943
1944         return skinframe;
1945 }
1946
1947 void gl_main_start(void)
1948 {
1949         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1950         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1951
1952         // set up r_skinframe loading system for textures
1953         memset(&r_skinframe, 0, sizeof(r_skinframe));
1954         r_skinframe.loadsequence = 1;
1955         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
1956
1957         r_main_texturepool = R_AllocTexturePool();
1958         R_BuildBlankTextures();
1959         R_BuildNoTexture();
1960         if (gl_texturecubemap)
1961         {
1962                 R_BuildWhiteCube();
1963                 R_BuildNormalizationCube();
1964         }
1965         r_texture_fogattenuation = NULL;
1966         //r_texture_fogintensity = NULL;
1967         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1968         memset(&r_waterstate, 0, sizeof(r_waterstate));
1969         memset(r_glsl_permutations, 0, sizeof(r_glsl_permutations));
1970         memset(&r_svbsp, 0, sizeof (r_svbsp));
1971
1972         r_refdef.fogmasktable_density = 0;
1973 }
1974
1975 void gl_main_shutdown(void)
1976 {
1977         memset(r_qwskincache, 0, sizeof(r_qwskincache));
1978         memset(r_qwskincache_skinframe, 0, sizeof(r_qwskincache_skinframe));
1979
1980         // clear out the r_skinframe state
1981         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
1982         memset(&r_skinframe, 0, sizeof(r_skinframe));
1983
1984         if (r_svbsp.nodes)
1985                 Mem_Free(r_svbsp.nodes);
1986         memset(&r_svbsp, 0, sizeof (r_svbsp));
1987         R_FreeTexturePool(&r_main_texturepool);
1988         r_texture_blanknormalmap = NULL;
1989         r_texture_white = NULL;
1990         r_texture_grey128 = NULL;
1991         r_texture_black = NULL;
1992         r_texture_whitecube = NULL;
1993         r_texture_normalizationcube = NULL;
1994         r_texture_fogattenuation = NULL;
1995         //r_texture_fogintensity = NULL;
1996         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
1997         memset(&r_waterstate, 0, sizeof(r_waterstate));
1998         R_GLSL_Restart_f();
1999 }
2000
2001 extern void CL_ParseEntityLump(char *entitystring);
2002 void gl_main_newmap(void)
2003 {
2004         // FIXME: move this code to client
2005         int l;
2006         char *entities, entname[MAX_QPATH];
2007         if (cl.worldmodel)
2008         {
2009                 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
2010                 l = (int)strlen(entname) - 4;
2011                 if (l >= 0 && !strcmp(entname + l, ".bsp"))
2012                 {
2013                         memcpy(entname + l, ".ent", 5);
2014                         if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
2015                         {
2016                                 CL_ParseEntityLump(entities);
2017                                 Mem_Free(entities);
2018                                 return;
2019                         }
2020                 }
2021                 if (cl.worldmodel->brush.entities)
2022                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
2023         }
2024 }
2025
2026 void GL_Main_Init(void)
2027 {
2028         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
2029
2030         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
2031         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
2032         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
2033         if (gamemode == GAME_NEHAHRA)
2034         {
2035                 Cvar_RegisterVariable (&gl_fogenable);
2036                 Cvar_RegisterVariable (&gl_fogdensity);
2037                 Cvar_RegisterVariable (&gl_fogred);
2038                 Cvar_RegisterVariable (&gl_foggreen);
2039                 Cvar_RegisterVariable (&gl_fogblue);
2040                 Cvar_RegisterVariable (&gl_fogstart);
2041                 Cvar_RegisterVariable (&gl_fogend);
2042                 Cvar_RegisterVariable (&gl_skyclip);
2043         }
2044         Cvar_RegisterVariable(&r_depthfirst);
2045         Cvar_RegisterVariable(&r_nearclip);
2046         Cvar_RegisterVariable(&r_showbboxes);
2047         Cvar_RegisterVariable(&r_showsurfaces);
2048         Cvar_RegisterVariable(&r_showtris);
2049         Cvar_RegisterVariable(&r_shownormals);
2050         Cvar_RegisterVariable(&r_showlighting);
2051         Cvar_RegisterVariable(&r_showshadowvolumes);
2052         Cvar_RegisterVariable(&r_showcollisionbrushes);
2053         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
2054         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
2055         Cvar_RegisterVariable(&r_showdisabledepthtest);
2056         Cvar_RegisterVariable(&r_drawportals);
2057         Cvar_RegisterVariable(&r_drawentities);
2058         Cvar_RegisterVariable(&r_cullentities_trace);
2059         Cvar_RegisterVariable(&r_cullentities_trace_samples);
2060         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
2061         Cvar_RegisterVariable(&r_cullentities_trace_delay);
2062         Cvar_RegisterVariable(&r_drawviewmodel);
2063         Cvar_RegisterVariable(&r_speeds);
2064         Cvar_RegisterVariable(&r_fullbrights);
2065         Cvar_RegisterVariable(&r_wateralpha);
2066         Cvar_RegisterVariable(&r_dynamic);
2067         Cvar_RegisterVariable(&r_fullbright);
2068         Cvar_RegisterVariable(&r_shadows);
2069         Cvar_RegisterVariable(&r_shadows_throwdistance);
2070         Cvar_RegisterVariable(&r_q1bsp_skymasking);
2071         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
2072         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
2073         Cvar_RegisterVariable(&r_fog_exp2);
2074         Cvar_RegisterVariable(&r_textureunits);
2075         Cvar_RegisterVariable(&r_glsl);
2076         Cvar_RegisterVariable(&r_glsl_offsetmapping);
2077         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
2078         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
2079         Cvar_RegisterVariable(&r_glsl_deluxemapping);
2080         Cvar_RegisterVariable(&r_water);
2081         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
2082         Cvar_RegisterVariable(&r_water_clippingplanebias);
2083         Cvar_RegisterVariable(&r_water_refractdistort);
2084         Cvar_RegisterVariable(&r_water_reflectdistort);
2085         Cvar_RegisterVariable(&r_lerpsprites);
2086         Cvar_RegisterVariable(&r_lerpmodels);
2087         Cvar_RegisterVariable(&r_lerplightstyles);
2088         Cvar_RegisterVariable(&r_waterscroll);
2089         Cvar_RegisterVariable(&r_bloom);
2090         Cvar_RegisterVariable(&r_bloom_colorscale);
2091         Cvar_RegisterVariable(&r_bloom_brighten);
2092         Cvar_RegisterVariable(&r_bloom_blur);
2093         Cvar_RegisterVariable(&r_bloom_resolution);
2094         Cvar_RegisterVariable(&r_bloom_colorexponent);
2095         Cvar_RegisterVariable(&r_bloom_colorsubtract);
2096         Cvar_RegisterVariable(&r_hdr);
2097         Cvar_RegisterVariable(&r_hdr_scenebrightness);
2098         Cvar_RegisterVariable(&r_glsl_contrastboost);
2099         Cvar_RegisterVariable(&r_hdr_glowintensity);
2100         Cvar_RegisterVariable(&r_hdr_range);
2101         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
2102         Cvar_RegisterVariable(&developer_texturelogging);
2103         Cvar_RegisterVariable(&gl_lightmaps);
2104         Cvar_RegisterVariable(&r_test);
2105         Cvar_RegisterVariable(&r_batchmode);
2106         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
2107                 Cvar_SetValue("r_fullbrights", 0);
2108         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
2109
2110         Cvar_RegisterVariable(&r_track_sprites);
2111         Cvar_RegisterVariable(&r_track_sprites_flags);
2112         Cvar_RegisterVariable(&r_track_sprites_scalew);
2113         Cvar_RegisterVariable(&r_track_sprites_scaleh);
2114 }
2115
2116 extern void R_Textures_Init(void);
2117 extern void GL_Draw_Init(void);
2118 extern void GL_Main_Init(void);
2119 extern void R_Shadow_Init(void);
2120 extern void R_Sky_Init(void);
2121 extern void GL_Surf_Init(void);
2122 extern void R_Particles_Init(void);
2123 extern void R_Explosion_Init(void);
2124 extern void gl_backend_init(void);
2125 extern void Sbar_Init(void);
2126 extern void R_LightningBeams_Init(void);
2127 extern void Mod_RenderInit(void);
2128
2129 void Render_Init(void)
2130 {
2131         gl_backend_init();
2132         R_Textures_Init();
2133         GL_Main_Init();
2134         GL_Draw_Init();
2135         R_Shadow_Init();
2136         R_Sky_Init();
2137         GL_Surf_Init();
2138         Sbar_Init();
2139         R_Particles_Init();
2140         R_Explosion_Init();
2141         R_LightningBeams_Init();
2142         Mod_RenderInit();
2143 }
2144
2145 /*
2146 ===============
2147 GL_Init
2148 ===============
2149 */
2150 extern char *ENGINE_EXTENSIONS;
2151 void GL_Init (void)
2152 {
2153         VID_CheckExtensions();
2154
2155         // LordHavoc: report supported extensions
2156         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
2157
2158         // clear to black (loading plaque will be seen over this)
2159         CHECKGLERROR
2160         qglClearColor(0,0,0,1);CHECKGLERROR
2161         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
2162 }
2163
2164 int R_CullBox(const vec3_t mins, const vec3_t maxs)
2165 {
2166         int i;
2167         mplane_t *p;
2168         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
2169         {
2170                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
2171                 if (i == 4)
2172                         continue;
2173                 p = r_refdef.view.frustum + i;
2174                 switch(p->signbits)
2175                 {
2176                 default:
2177                 case 0:
2178                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2179                                 return true;
2180                         break;
2181                 case 1:
2182                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2183                                 return true;
2184                         break;
2185                 case 2:
2186                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2187                                 return true;
2188                         break;
2189                 case 3:
2190                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2191                                 return true;
2192                         break;
2193                 case 4:
2194                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2195                                 return true;
2196                         break;
2197                 case 5:
2198                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2199                                 return true;
2200                         break;
2201                 case 6:
2202                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2203                                 return true;
2204                         break;
2205                 case 7:
2206                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2207                                 return true;
2208                         break;
2209                 }
2210         }
2211         return false;
2212 }
2213
2214 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
2215 {
2216         int i;
2217         const mplane_t *p;
2218         for (i = 0;i < numplanes;i++)
2219         {
2220                 p = planes + i;
2221                 switch(p->signbits)
2222                 {
2223                 default:
2224                 case 0:
2225                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2226                                 return true;
2227                         break;
2228                 case 1:
2229                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
2230                                 return true;
2231                         break;
2232                 case 2:
2233                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2234                                 return true;
2235                         break;
2236                 case 3:
2237                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
2238                                 return true;
2239                         break;
2240                 case 4:
2241                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2242                                 return true;
2243                         break;
2244                 case 5:
2245                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
2246                                 return true;
2247                         break;
2248                 case 6:
2249                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2250                                 return true;
2251                         break;
2252                 case 7:
2253                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
2254                                 return true;
2255                         break;
2256                 }
2257         }
2258         return false;
2259 }
2260
2261 //==================================================================================
2262
2263 static void R_View_UpdateEntityVisible (void)
2264 {
2265         int i, renderimask;
2266         entity_render_t *ent;
2267
2268         if (!r_drawentities.integer)
2269                 return;
2270
2271         renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL) : ((chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL : RENDER_EXTERIORMODEL);
2272         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
2273         {
2274                 // worldmodel can check visibility
2275                 for (i = 0;i < r_refdef.scene.numentities;i++)
2276                 {
2277                         ent = r_refdef.scene.entities[i];
2278                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs)) && ((ent->effects & EF_NODEPTHTEST) || (ent->flags & RENDER_VIEWMODEL) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs));
2279
2280                 }
2281                 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight)
2282                 {
2283                         for (i = 0;i < r_refdef.scene.numentities;i++)
2284                         {
2285                                 ent = r_refdef.scene.entities[i];
2286                                 if(r_refdef.viewcache.entityvisible[i] && !(ent->effects & EF_NODEPTHTEST) && !(ent->flags & RENDER_VIEWMODEL) && !(ent->model && (ent->model->name[0] == '*')))
2287                                 {
2288                                         if(Mod_CanSeeBox_Trace(r_cullentities_trace_samples.integer, r_cullentities_trace_enlarge.value, r_refdef.scene.worldmodel, r_refdef.view.origin, ent->mins, ent->maxs))
2289                                                 ent->last_trace_visibility = realtime;
2290                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
2291                                                 r_refdef.viewcache.entityvisible[i] = 0;
2292                                 }
2293                         }
2294                 }
2295         }
2296         else
2297         {
2298                 // no worldmodel or it can't check visibility
2299                 for (i = 0;i < r_refdef.scene.numentities;i++)
2300                 {
2301                         ent = r_refdef.scene.entities[i];
2302                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
2303                 }
2304         }
2305 }
2306
2307 // only used if skyrendermasked, and normally returns false
2308 int R_DrawBrushModelsSky (void)
2309 {
2310         int i, sky;
2311         entity_render_t *ent;
2312
2313         if (!r_drawentities.integer)
2314                 return false;
2315
2316         sky = false;
2317         for (i = 0;i < r_refdef.scene.numentities;i++)
2318         {
2319                 if (!r_refdef.viewcache.entityvisible[i])
2320                         continue;
2321                 ent = r_refdef.scene.entities[i];
2322                 if (!ent->model || !ent->model->DrawSky)
2323                         continue;
2324                 ent->model->DrawSky(ent);
2325                 sky = true;
2326         }
2327         return sky;
2328 }
2329
2330 static void R_DrawNoModel(entity_render_t *ent);
2331 static void R_DrawModels(void)
2332 {
2333         int i;
2334         entity_render_t *ent;
2335
2336         if (!r_drawentities.integer)
2337                 return;
2338
2339         for (i = 0;i < r_refdef.scene.numentities;i++)
2340         {
2341                 if (!r_refdef.viewcache.entityvisible[i])
2342                         continue;
2343                 ent = r_refdef.scene.entities[i];
2344                 r_refdef.stats.entities++;
2345                 if (ent->model && ent->model->Draw != NULL)
2346                         ent->model->Draw(ent);
2347                 else
2348                         R_DrawNoModel(ent);
2349         }
2350 }
2351
2352 static void R_DrawModelsDepth(void)
2353 {
2354         int i;
2355         entity_render_t *ent;
2356
2357         if (!r_drawentities.integer)
2358                 return;
2359
2360         for (i = 0;i < r_refdef.scene.numentities;i++)
2361         {
2362                 if (!r_refdef.viewcache.entityvisible[i])
2363                         continue;
2364                 ent = r_refdef.scene.entities[i];
2365                 if (ent->model && ent->model->DrawDepth != NULL)
2366                         ent->model->DrawDepth(ent);
2367         }
2368 }
2369
2370 static void R_DrawModelsDebug(void)
2371 {
2372         int i;
2373         entity_render_t *ent;
2374
2375         if (!r_drawentities.integer)
2376                 return;
2377
2378         for (i = 0;i < r_refdef.scene.numentities;i++)
2379         {
2380                 if (!r_refdef.viewcache.entityvisible[i])
2381                         continue;
2382                 ent = r_refdef.scene.entities[i];
2383                 if (ent->model && ent->model->DrawDebug != NULL)
2384                         ent->model->DrawDebug(ent);
2385         }
2386 }
2387
2388 static void R_DrawModelsAddWaterPlanes(void)
2389 {
2390         int i;
2391         entity_render_t *ent;
2392
2393         if (!r_drawentities.integer)
2394                 return;
2395
2396         for (i = 0;i < r_refdef.scene.numentities;i++)
2397         {
2398                 if (!r_refdef.viewcache.entityvisible[i])
2399                         continue;
2400                 ent = r_refdef.scene.entities[i];
2401                 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
2402                         ent->model->DrawAddWaterPlanes(ent);
2403         }
2404 }
2405
2406 static void R_View_SetFrustum(void)
2407 {
2408         int i;
2409         double slopex, slopey;
2410         vec3_t forward, left, up, origin;
2411
2412         // we can't trust r_refdef.view.forward and friends in reflected scenes
2413         Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
2414
2415 #if 0
2416         r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
2417         r_refdef.view.frustum[0].normal[1] = 0 - 0;
2418         r_refdef.view.frustum[0].normal[2] = -1 - 0;
2419         r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
2420         r_refdef.view.frustum[1].normal[1] = 0 + 0;
2421         r_refdef.view.frustum[1].normal[2] = -1 + 0;
2422         r_refdef.view.frustum[2].normal[0] = 0 - 0;
2423         r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
2424         r_refdef.view.frustum[2].normal[2] = -1 - 0;
2425         r_refdef.view.frustum[3].normal[0] = 0 + 0;
2426         r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
2427         r_refdef.view.frustum[3].normal[2] = -1 + 0;
2428 #endif
2429
2430 #if 0
2431         zNear = r_refdef.nearclip;
2432         nudge = 1.0 - 1.0 / (1<<23);
2433         r_refdef.view.frustum[4].normal[0] = 0 - 0;
2434         r_refdef.view.frustum[4].normal[1] = 0 - 0;
2435         r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
2436         r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
2437         r_refdef.view.frustum[5].normal[0] = 0 + 0;
2438         r_refdef.view.frustum[5].normal[1] = 0 + 0;
2439         r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
2440         r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
2441 #endif
2442
2443
2444
2445 #if 0
2446         r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
2447         r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
2448         r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
2449         r_refdef.view.frustum[0].dist = m[15] - m[12];
2450
2451         r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
2452         r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
2453         r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
2454         r_refdef.view.frustum[1].dist = m[15] + m[12];
2455
2456         r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
2457         r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
2458         r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
2459         r_refdef.view.frustum[2].dist = m[15] - m[13];
2460
2461         r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
2462         r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
2463         r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
2464         r_refdef.view.frustum[3].dist = m[15] + m[13];
2465
2466         r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
2467         r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
2468         r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
2469         r_refdef.view.frustum[4].dist = m[15] - m[14];
2470
2471         r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
2472         r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
2473         r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
2474         r_refdef.view.frustum[5].dist = m[15] + m[14];
2475 #endif
2476
2477         if (r_refdef.view.useperspective)
2478         {
2479                 slopex = 1.0 / r_refdef.view.frustum_x;
2480                 slopey = 1.0 / r_refdef.view.frustum_y;
2481                 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
2482                 VectorMA(forward,  slopex, left, r_refdef.view.frustum[1].normal);
2483                 VectorMA(forward, -slopey, up  , r_refdef.view.frustum[2].normal);
2484                 VectorMA(forward,  slopey, up  , r_refdef.view.frustum[3].normal);
2485                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
2486
2487                 // Leaving those out was a mistake, those were in the old code, and they
2488                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
2489                 // I couldn't reproduce it after adding those normalizations. --blub
2490                 VectorNormalize(r_refdef.view.frustum[0].normal);
2491                 VectorNormalize(r_refdef.view.frustum[1].normal);
2492                 VectorNormalize(r_refdef.view.frustum[2].normal);
2493                 VectorNormalize(r_refdef.view.frustum[3].normal);
2494
2495                 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
2496                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, -1024 * slopex, left, -1024 * slopey, up, r_refdef.view.frustumcorner[0]);
2497                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward,  1024 * slopex, left, -1024 * slopey, up, r_refdef.view.frustumcorner[1]);
2498                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, -1024 * slopex, left,  1024 * slopey, up, r_refdef.view.frustumcorner[2]);
2499                 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward,  1024 * slopex, left,  1024 * slopey, up, r_refdef.view.frustumcorner[3]);
2500
2501                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
2502                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
2503                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
2504                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
2505                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
2506         }
2507         else
2508         {
2509                 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
2510                 VectorScale(left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
2511                 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
2512                 VectorScale(up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
2513                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
2514                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
2515                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
2516                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
2517                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
2518                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
2519         }
2520         r_refdef.view.numfrustumplanes = 5;
2521
2522         if (r_refdef.view.useclipplane)
2523         {
2524                 r_refdef.view.numfrustumplanes = 6;
2525                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
2526         }
2527
2528         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
2529                 PlaneClassify(r_refdef.view.frustum + i);
2530
2531         // LordHavoc: note to all quake engine coders, Quake had a special case
2532         // for 90 degrees which assumed a square view (wrong), so I removed it,
2533         // Quake2 has it disabled as well.
2534
2535         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
2536         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
2537         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
2538         //PlaneClassify(&frustum[0]);
2539
2540         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
2541         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
2542         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
2543         //PlaneClassify(&frustum[1]);
2544
2545         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
2546         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
2547         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
2548         //PlaneClassify(&frustum[2]);
2549
2550         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
2551         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
2552         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
2553         //PlaneClassify(&frustum[3]);
2554
2555         // nearclip plane
2556         //VectorCopy(forward, r_refdef.view.frustum[4].normal);
2557         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
2558         //PlaneClassify(&frustum[4]);
2559 }
2560
2561 void R_View_Update(void)
2562 {
2563         R_View_SetFrustum();
2564         R_View_WorldVisibility(r_refdef.view.useclipplane);
2565         R_View_UpdateEntityVisible();
2566 }
2567
2568 void R_SetupView(qboolean allowwaterclippingplane)
2569 {
2570         if (!r_refdef.view.useperspective)
2571                 GL_SetupView_Mode_Ortho(-r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip);
2572         else if (r_refdef.rtworldshadows || r_refdef.rtdlightshadows)
2573                 GL_SetupView_Mode_PerspectiveInfiniteFarClip(r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip);
2574         else
2575                 GL_SetupView_Mode_Perspective(r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip);
2576
2577         GL_SetupView_Orientation_FromEntity(&r_refdef.view.matrix);
2578
2579         if (r_refdef.view.useclipplane && allowwaterclippingplane)
2580         {
2581                 // LordHavoc: couldn't figure out how to make this approach the
2582                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
2583                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
2584                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
2585                         dist = r_refdef.view.clipplane.dist;
2586                 GL_SetupView_ApplyCustomNearClipPlane(r_refdef.view.clipplane.normal[0], r_refdef.view.clipplane.normal[1], r_refdef.view.clipplane.normal[2], dist);
2587         }
2588 }
2589
2590 void R_ResetViewRendering2D(void)
2591 {
2592         if (gl_support_fragment_shader)
2593         {
2594                 qglUseProgramObjectARB(0);CHECKGLERROR
2595         }
2596
2597         DrawQ_Finish();
2598
2599         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
2600         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2601         GL_SetupView_Mode_Ortho(0, 0, 1, 1, -10, 100);
2602         GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
2603         GL_Color(1, 1, 1, 1);
2604         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2605         GL_BlendFunc(GL_ONE, GL_ZERO);
2606         GL_AlphaTest(false);
2607         GL_ScissorTest(false);
2608         GL_DepthMask(false);
2609         GL_DepthRange(0, 1);
2610         GL_DepthTest(false);
2611         R_Mesh_Matrix(&identitymatrix);
2612         R_Mesh_ResetTextureState();
2613         GL_PolygonOffset(0, 0);
2614         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
2615         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2616         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2617         qglStencilMask(~0);CHECKGLERROR
2618         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
2619         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
2620         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
2621 }
2622
2623 void R_ResetViewRendering3D(void)
2624 {
2625         if (gl_support_fragment_shader)
2626         {
2627                 qglUseProgramObjectARB(0);CHECKGLERROR
2628         }
2629
2630         DrawQ_Finish();
2631
2632         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
2633         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2634         R_SetupView(true);
2635         GL_Scissor(r_refdef.view.x, r_refdef.view.y, r_refdef.view.width, r_refdef.view.height);
2636         GL_Color(1, 1, 1, 1);
2637         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
2638         GL_BlendFunc(GL_ONE, GL_ZERO);
2639         GL_AlphaTest(false);
2640         GL_ScissorTest(true);
2641         GL_DepthMask(true);
2642         GL_DepthRange(0, 1);
2643         GL_DepthTest(true);
2644         R_Mesh_Matrix(&identitymatrix);
2645         R_Mesh_ResetTextureState();
2646         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
2647         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
2648         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
2649         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
2650         qglStencilMask(~0);CHECKGLERROR
2651         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
2652         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
2653         GL_CullFace(r_refdef.view.cullface_back);
2654 }
2655
2656 /*
2657         R_Bloom_SetupShader(
2658 "// bloom shader\n"
2659 "// written by Forest 'LordHavoc' Hale\n"
2660 "\n"
2661 "// common definitions between vertex shader and fragment shader:\n"
2662 "\n"
2663 "#ifdef __GLSL_CG_DATA_TYPES\n"
2664 "#define myhalf half\n"
2665 "#define myhalf2 half2\n"
2666 "#define myhalf3 half3\n"
2667 "#define myhalf4 half4\n"
2668 "#else\n"
2669 "#define myhalf float\n"
2670 "#define myhalf2 vec2\n"
2671 "#define myhalf3 vec3\n"
2672 "#define myhalf4 vec4\n"
2673 "#endif\n"
2674 "\n"
2675 "varying vec2 ScreenTexCoord;\n"
2676 "varying vec2 BloomTexCoord;\n"
2677 "\n"
2678 "\n"
2679 "\n"
2680 "\n"
2681 "// vertex shader specific:\n"
2682 "#ifdef VERTEX_SHADER\n"
2683 "\n"
2684 "void main(void)\n"
2685 "{\n"
2686 "       ScreenTexCoord = vec2(gl_MultiTexCoord0);\n"
2687 "       BloomTexCoord = vec2(gl_MultiTexCoord1);\n"
2688 "       // transform vertex to camera space, using ftransform to match non-VS\n"
2689 "       // rendering\n"
2690 "       gl_Position = ftransform();\n"
2691 "}\n"
2692 "\n"
2693 "#endif // VERTEX_SHADER\n"
2694 "\n"
2695 "\n"
2696 "\n"
2697 "\n"
2698 "// fragment shader specific:\n"
2699 "#ifdef FRAGMENT_SHADER\n"
2700 "\n"
2701 "void main(void)\n"
2702 "{\n"
2703 "       int x, y;
2704 "       myhalf3 color = myhalf3(texture2D(Texture_Screen, ScreenTexCoord));\n"
2705 "       for (x = -BLUR_X;x <= BLUR_X;x++)
2706 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2707 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2708 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2709 "       color.rgb += myhalf3(texture2D(Texture_Bloom, BloomTexCoord));\n"
2710
2711 "       gl_FragColor = vec4(color);\n"
2712 "}\n"
2713 "\n"
2714 "#endif // FRAGMENT_SHADER\n"
2715 */
2716
2717 void R_RenderScene(qboolean addwaterplanes);
2718
2719 static void R_Water_StartFrame(void)
2720 {
2721         int i;
2722         int waterwidth, waterheight, texturewidth, textureheight;
2723         r_waterstate_waterplane_t *p;
2724
2725         // set waterwidth and waterheight to the water resolution that will be
2726         // used (often less than the screen resolution for faster rendering)
2727         waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
2728         waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
2729
2730         // calculate desired texture sizes
2731         // can't use water if the card does not support the texture size
2732         if (!r_water.integer || !r_glsl.integer || !gl_support_fragment_shader || waterwidth > gl_max_texture_size || waterheight > gl_max_texture_size)
2733                 texturewidth = textureheight = waterwidth = waterheight = 0;
2734         else if (gl_support_arb_texture_non_power_of_two)
2735         {
2736                 texturewidth = waterwidth;
2737                 textureheight = waterheight;
2738         }
2739         else
2740         {
2741                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
2742                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
2743         }
2744
2745         // allocate textures as needed
2746         if (r_waterstate.waterwidth != waterwidth || r_waterstate.waterheight != waterheight || r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight)
2747         {
2748                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
2749                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
2750                 {
2751                         if (p->texture_refraction)
2752                                 R_FreeTexture(p->texture_refraction);
2753                         p->texture_refraction = NULL;
2754                         if (p->texture_reflection)
2755                                 R_FreeTexture(p->texture_reflection);
2756                         p->texture_reflection = NULL;
2757                 }
2758                 memset(&r_waterstate, 0, sizeof(r_waterstate));
2759                 r_waterstate.waterwidth = waterwidth;
2760                 r_waterstate.waterheight = waterheight;
2761                 r_waterstate.texturewidth = texturewidth;
2762                 r_waterstate.textureheight = textureheight;
2763         }
2764
2765         if (r_waterstate.waterwidth)
2766         {
2767                 r_waterstate.enabled = true;
2768
2769                 // set up variables that will be used in shader setup
2770                 r_waterstate.screenscale[0] = 0.5f * (float)waterwidth / (float)texturewidth;
2771                 r_waterstate.screenscale[1] = 0.5f * (float)waterheight / (float)textureheight;
2772                 r_waterstate.screencenter[0] = 0.5f * (float)waterwidth / (float)texturewidth;
2773                 r_waterstate.screencenter[1] = 0.5f * (float)waterheight / (float)textureheight;
2774         }
2775
2776         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
2777         r_waterstate.numwaterplanes = 0;
2778 }
2779
2780 static void R_Water_AddWaterPlane(msurface_t *surface)
2781 {
2782         int triangleindex, planeindex;
2783         const int *e;
2784         vec3_t vert[3];
2785         vec3_t normal;
2786         vec3_t center;
2787         r_waterstate_waterplane_t *p;
2788         // just use the first triangle with a valid normal for any decisions
2789         VectorClear(normal);
2790         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2791         {
2792                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
2793                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
2794                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
2795                 TriangleNormal(vert[0], vert[1], vert[2], normal);
2796                 if (VectorLength2(normal) >= 0.001)
2797                         break;
2798         }
2799
2800         // find a matching plane if there is one
2801         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
2802                 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
2803                         break;
2804         if (planeindex >= r_waterstate.maxwaterplanes)
2805                 return; // nothing we can do, out of planes
2806
2807         // if this triangle does not fit any known plane rendered this frame, add one
2808         if (planeindex >= r_waterstate.numwaterplanes)
2809         {
2810                 // store the new plane
2811                 r_waterstate.numwaterplanes++;
2812                 VectorCopy(normal, p->plane.normal);
2813                 VectorNormalize(p->plane.normal);
2814                 p->plane.dist = DotProduct(vert[0], p->plane.normal);
2815                 PlaneClassify(&p->plane);
2816                 // flip the plane if it does not face the viewer
2817                 if (PlaneDiff(r_refdef.view.origin, &p->plane) < 0)
2818                 {
2819                         VectorNegate(p->plane.normal, p->plane.normal);
2820                         p->plane.dist *= -1;
2821                         PlaneClassify(&p->plane);
2822                 }
2823                 // clear materialflags and pvs
2824                 p->materialflags = 0;
2825                 p->pvsvalid = false;
2826         }
2827         // merge this surface's materialflags into the waterplane
2828         p->materialflags |= surface->texture->currentframe->currentmaterialflags;
2829         // merge this surface's PVS into the waterplane
2830         VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
2831         if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
2832          && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
2833         {
2834                 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
2835                 p->pvsvalid = true;
2836         }
2837 }
2838
2839 static void R_Water_ProcessPlanes(void)
2840 {
2841         r_refdef_view_t originalview;
2842         int planeindex;
2843         r_waterstate_waterplane_t *p;
2844
2845         originalview = r_refdef.view;
2846
2847         // make sure enough textures are allocated
2848         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
2849         {
2850                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
2851                 {
2852                         if (!p->texture_refraction)
2853                                 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2854                         if (!p->texture_refraction)
2855                                 goto error;
2856                 }
2857
2858                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
2859                 {
2860                         if (!p->texture_reflection)
2861                                 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
2862                         if (!p->texture_reflection)
2863                                 goto error;
2864                 }
2865         }
2866
2867         // render views
2868         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
2869         {
2870                 r_refdef.view.showdebug = false;
2871                 r_refdef.view.width = r_waterstate.waterwidth;
2872                 r_refdef.view.height = r_waterstate.waterheight;
2873                 r_refdef.view.useclipplane = true;
2874                 r_waterstate.renderingscene = true;
2875
2876                 // render the normal view scene and copy into texture
2877                 // (except that a clipping plane should be used to hide everything on one side of the water, and the viewer's weapon model should be omitted)
2878                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
2879                 {
2880                         r_refdef.view.clipplane = p->plane;
2881                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
2882                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
2883                         PlaneClassify(&r_refdef.view.clipplane);
2884
2885                         R_RenderScene(false);
2886
2887                         // copy view into the screen texture
2888                         R_Mesh_TexBind(0, R_GetTexture(p->texture_refraction));
2889                         GL_ActiveTexture(0);
2890                         CHECKGLERROR
2891                         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2892                 }
2893
2894                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
2895                 {
2896                         // render reflected scene and copy into texture
2897                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
2898                         // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
2899                         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
2900                         r_refdef.view.clipplane = p->plane;
2901                         // reverse the cullface settings for this render
2902                         r_refdef.view.cullface_front = GL_FRONT;
2903                         r_refdef.view.cullface_back = GL_BACK;
2904                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
2905                         {
2906                                 r_refdef.view.usecustompvs = true;
2907                                 if (p->pvsvalid)
2908                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
2909                                 else
2910                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
2911                         }
2912
2913                         R_ResetViewRendering3D();
2914                         R_ClearScreen(r_refdef.fogenabled);
2915                         if (r_timereport_active)
2916                                 R_TimeReport("viewclear");
2917
2918                         R_RenderScene(false);
2919
2920                         R_Mesh_TexBind(0, R_GetTexture(p->texture_reflection));
2921                         GL_ActiveTexture(0);
2922                         CHECKGLERROR
2923                         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
2924
2925                         R_ResetViewRendering3D();
2926                         R_ClearScreen(r_refdef.fogenabled);
2927                         if (r_timereport_active)
2928                                 R_TimeReport("viewclear");
2929                 }
2930
2931                 r_refdef.view = originalview;
2932                 r_refdef.view.clear = true;
2933                 r_waterstate.renderingscene = false;
2934         }
2935         return;
2936 error:
2937         r_refdef.view = originalview;
2938         r_waterstate.renderingscene = false;
2939         Cvar_SetValueQuick(&r_water, 0);
2940         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
2941         return;
2942 }
2943
2944 void R_Bloom_StartFrame(void)
2945 {
2946         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
2947
2948         // set bloomwidth and bloomheight to the bloom resolution that will be
2949         // used (often less than the screen resolution for faster rendering)
2950         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.width);
2951         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
2952         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
2953
2954         // calculate desired texture sizes
2955         if (gl_support_arb_texture_non_power_of_two)
2956         {
2957                 screentexturewidth = r_refdef.view.width;
2958                 screentextureheight = r_refdef.view.height;
2959                 bloomtexturewidth = r_bloomstate.bloomwidth;
2960                 bloomtextureheight = r_bloomstate.bloomheight;
2961         }
2962         else
2963         {
2964                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
2965                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
2966                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
2967                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
2968         }
2969
2970         if (r_hdr.integer)
2971         {
2972                 screentexturewidth = screentextureheight = 0;
2973         }
2974         else if (r_bloom.integer)
2975         {
2976         }
2977         else
2978         {
2979                 screentexturewidth = screentextureheight = 0;
2980                 bloomtexturewidth = bloomtextureheight = 0;
2981         }
2982
2983         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)
2984         {
2985                 // can't use bloom if the parameters are too weird
2986                 // can't use bloom if the card does not support the texture size
2987                 if (r_bloomstate.texture_screen)
2988                         R_FreeTexture(r_bloomstate.texture_screen);
2989                 if (r_bloomstate.texture_bloom)
2990                         R_FreeTexture(r_bloomstate.texture_bloom);
2991                 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
2992                 return;
2993         }
2994
2995         r_bloomstate.enabled = true;
2996         r_bloomstate.hdr = r_hdr.integer != 0;
2997
2998         // allocate textures as needed
2999         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
3000         {
3001                 if (r_bloomstate.texture_screen)
3002                         R_FreeTexture(r_bloomstate.texture_screen);
3003                 r_bloomstate.texture_screen = NULL;
3004                 r_bloomstate.screentexturewidth = screentexturewidth;
3005                 r_bloomstate.screentextureheight = screentextureheight;
3006                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
3007                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_BGRA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
3008         }
3009         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
3010         {
3011                 if (r_bloomstate.texture_bloom)
3012                         R_FreeTexture(r_bloomstate.texture_bloom);
3013                 r_bloomstate.texture_bloom = NULL;
3014                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
3015                 r_bloomstate.bloomtextureheight = bloomtextureheight;
3016                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
3017                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALWAYSPRECACHE, NULL);
3018         }
3019
3020         // set up a texcoord array for the full resolution screen image
3021         // (we have to keep this around to copy back during final render)
3022         r_bloomstate.screentexcoord2f[0] = 0;
3023         r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
3024         r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
3025         r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
3026         r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
3027         r_bloomstate.screentexcoord2f[5] = 0;
3028         r_bloomstate.screentexcoord2f[6] = 0;
3029         r_bloomstate.screentexcoord2f[7] = 0;
3030
3031         // set up a texcoord array for the reduced resolution bloom image
3032         // (which will be additive blended over the screen image)
3033         r_bloomstate.bloomtexcoord2f[0] = 0;
3034         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3035         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3036         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3037         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3038         r_bloomstate.bloomtexcoord2f[5] = 0;
3039         r_bloomstate.bloomtexcoord2f[6] = 0;
3040         r_bloomstate.bloomtexcoord2f[7] = 0;
3041 }
3042
3043 void R_Bloom_CopyScreenTexture(float colorscale)
3044 {
3045         r_refdef.stats.bloom++;
3046
3047         R_ResetViewRendering2D();
3048         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3049         R_Mesh_ColorPointer(NULL, 0, 0);
3050         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
3051         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
3052
3053         // copy view into the screen texture
3054         GL_ActiveTexture(0);
3055         CHECKGLERROR
3056         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
3057         r_refdef.stats.bloom_copypixels += r_refdef.view.width * r_refdef.view.height;
3058
3059         // now scale it down to the bloom texture size
3060         CHECKGLERROR
3061         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3062         GL_BlendFunc(GL_ONE, GL_ZERO);
3063         GL_Color(colorscale, colorscale, colorscale, 1);
3064         // TODO: optimize with multitexture or GLSL
3065         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3066         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3067
3068         // we now have a bloom image in the framebuffer
3069         // copy it into the bloom image texture for later processing
3070         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3071         GL_ActiveTexture(0);
3072         CHECKGLERROR
3073         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3074         r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3075 }
3076
3077 void R_Bloom_CopyHDRTexture(void)
3078 {
3079         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3080         GL_ActiveTexture(0);
3081         CHECKGLERROR
3082         qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_refdef.view.height), r_refdef.view.width, r_refdef.view.height);CHECKGLERROR
3083         r_refdef.stats.bloom_copypixels += r_refdef.view.width * r_refdef.view.height;
3084 }
3085
3086 void R_Bloom_MakeTexture(void)
3087 {
3088         int x, range, dir;
3089         float xoffset, yoffset, r, brighten;
3090
3091         r_refdef.stats.bloom++;
3092
3093         R_ResetViewRendering2D();
3094         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3095         R_Mesh_ColorPointer(NULL, 0, 0);
3096
3097         // we have a bloom image in the framebuffer
3098         CHECKGLERROR
3099         qglViewport(r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3100
3101         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
3102         {
3103                 x *= 2;
3104                 r = bound(0, r_bloom_colorexponent.value / x, 1);
3105                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
3106                 GL_Color(r, r, r, 1);
3107                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3108                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3109                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3110                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3111
3112                 // copy the vertically blurred bloom view to a texture
3113                 GL_ActiveTexture(0);
3114                 CHECKGLERROR
3115                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3116                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3117         }
3118
3119         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
3120         brighten = r_bloom_brighten.value;
3121         if (r_hdr.integer)
3122                 brighten *= r_hdr_range.value;
3123         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3124         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.offsettexcoord2f, 0, 0);
3125
3126         for (dir = 0;dir < 2;dir++)
3127         {
3128                 // blend on at multiple vertical offsets to achieve a vertical blur
3129                 // TODO: do offset blends using GLSL
3130                 GL_BlendFunc(GL_ONE, GL_ZERO);
3131                 for (x = -range;x <= range;x++)
3132                 {
3133                         if (!dir){xoffset = 0;yoffset = x;}
3134                         else {xoffset = x;yoffset = 0;}
3135                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
3136                         yoffset /= (float)r_bloomstate.bloomtextureheight;
3137                         // compute a texcoord array with the specified x and y offset
3138                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
3139                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3140                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3141                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
3142                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
3143                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
3144                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
3145                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
3146                         // this r value looks like a 'dot' particle, fading sharply to
3147                         // black at the edges
3148                         // (probably not realistic but looks good enough)
3149                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
3150                         //r = (dir ? 1.0f : brighten)/(range*2+1);
3151                         r = (dir ? 1.0f : brighten)/(range*2+1)*(1 - x*x/(float)(range*range));
3152                         GL_Color(r, r, r, 1);
3153                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3154                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3155                         GL_BlendFunc(GL_ONE, GL_ONE);
3156                 }
3157
3158                 // copy the vertically blurred bloom view to a texture
3159                 GL_ActiveTexture(0);
3160                 CHECKGLERROR
3161                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3162                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3163         }
3164
3165         // apply subtract last
3166         // (just like it would be in a GLSL shader)
3167         if (r_bloom_colorsubtract.value > 0 && gl_support_ext_blend_subtract)
3168         {
3169                 GL_BlendFunc(GL_ONE, GL_ZERO);
3170                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3171                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3172                 GL_Color(1, 1, 1, 1);
3173                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3174                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3175
3176                 GL_BlendFunc(GL_ONE, GL_ONE);
3177                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
3178                 R_Mesh_TexBind(0, R_GetTexture(r_texture_white));
3179                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3180                 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
3181                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3182                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3183                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
3184
3185                 // copy the darkened bloom view to a texture
3186                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3187                 GL_ActiveTexture(0);
3188                 CHECKGLERROR
3189                 qglCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, r_refdef.view.x, vid.height - (r_refdef.view.y + r_bloomstate.bloomheight), r_bloomstate.bloomwidth, r_bloomstate.bloomheight);CHECKGLERROR
3190                 r_refdef.stats.bloom_copypixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
3191         }
3192 }
3193
3194 void R_HDR_RenderBloomTexture(void)
3195 {
3196         int oldwidth, oldheight;
3197         float oldcolorscale;
3198
3199         oldcolorscale = r_refdef.view.colorscale;
3200         oldwidth = r_refdef.view.width;
3201         oldheight = r_refdef.view.height;
3202         r_refdef.view.width = r_bloomstate.bloomwidth;
3203         r_refdef.view.height = r_bloomstate.bloomheight;
3204
3205         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
3206         // TODO: add exposure compensation features
3207         // TODO: add fp16 framebuffer support
3208
3209         r_refdef.view.showdebug = false;
3210         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
3211
3212         R_ClearScreen(r_refdef.fogenabled);
3213         if (r_timereport_active)
3214                 R_TimeReport("HDRclear");
3215
3216         r_waterstate.numwaterplanes = 0;
3217         R_RenderScene(r_waterstate.enabled);
3218         r_refdef.view.showdebug = true;
3219
3220         R_ResetViewRendering2D();
3221
3222         R_Bloom_CopyHDRTexture();
3223         R_Bloom_MakeTexture();
3224
3225         // restore the view settings
3226         r_refdef.view.width = oldwidth;
3227         r_refdef.view.height = oldheight;
3228         r_refdef.view.colorscale = oldcolorscale;
3229
3230         R_ResetViewRendering3D();
3231
3232         R_ClearScreen(r_refdef.fogenabled);
3233         if (r_timereport_active)
3234                 R_TimeReport("viewclear");
3235 }
3236
3237 static void R_BlendView(void)
3238 {
3239         if (r_bloomstate.enabled && r_bloomstate.hdr)
3240         {
3241                 // render high dynamic range bloom effect
3242                 // the bloom texture was made earlier this render, so we just need to
3243                 // blend it onto the screen...
3244                 R_ResetViewRendering2D();
3245                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3246                 R_Mesh_ColorPointer(NULL, 0, 0);
3247                 GL_Color(1, 1, 1, 1);
3248                 GL_BlendFunc(GL_ONE, GL_ONE);
3249                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3250                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3251                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3252                 r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
3253         }
3254         else if (r_bloomstate.enabled)
3255         {
3256                 // render simple bloom effect
3257                 // copy the screen and shrink it and darken it for the bloom process
3258                 R_Bloom_CopyScreenTexture(r_bloom_colorscale.value);
3259                 // make the bloom texture
3260                 R_Bloom_MakeTexture();
3261                 // put the original screen image back in place and blend the bloom
3262                 // texture on it
3263                 R_ResetViewRendering2D();
3264                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3265                 R_Mesh_ColorPointer(NULL, 0, 0);
3266                 GL_Color(1, 1, 1, 1);
3267                 GL_BlendFunc(GL_ONE, GL_ZERO);
3268                 // do both in one pass if possible
3269                 R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_bloom));
3270                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
3271                 if (r_textureunits.integer >= 2 && gl_combine.integer)
3272                 {
3273                         R_Mesh_TexCombine(1, GL_ADD, GL_ADD, 1, 1);
3274                         R_Mesh_TexBind(1, R_GetTexture(r_bloomstate.texture_screen));
3275                         R_Mesh_TexCoordPointer(1, 2, r_bloomstate.screentexcoord2f, 0, 0);
3276                 }
3277                 else
3278                 {
3279                         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3280                         r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
3281                         // now blend on the bloom texture
3282                         GL_BlendFunc(GL_ONE, GL_ONE);
3283                         R_Mesh_TexBind(0, R_GetTexture(r_bloomstate.texture_screen));
3284                         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
3285                 }
3286                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3287                 r_refdef.stats.bloom_drawpixels += r_refdef.view.width * r_refdef.view.height;
3288         }
3289         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
3290         {
3291                 // apply a color tint to the whole view
3292                 R_ResetViewRendering2D();
3293                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
3294                 R_Mesh_ColorPointer(NULL, 0, 0);
3295                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3296                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
3297                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3298         }
3299 }
3300
3301 void R_RenderScene(qboolean addwaterplanes);
3302
3303 matrix4x4_t r_waterscrollmatrix;
3304
3305 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
3306 {
3307         if (r_refdef.fog_density)
3308         {
3309                 r_refdef.fogcolor[0] = r_refdef.fog_red;
3310                 r_refdef.fogcolor[1] = r_refdef.fog_green;
3311                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
3312
3313                 {
3314                         vec3_t fogvec;
3315                         VectorCopy(r_refdef.fogcolor, fogvec);
3316                         if(r_glsl.integer && (r_glsl_contrastboost.value > 1 || r_glsl_contrastboost.value < 0)) // need to support contrast boost
3317                         {
3318                                 //   color.rgb /= ((ContrastBoost - 1) * color.rgb + 1);
3319                                 fogvec[0] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[0] + 1);
3320                                 fogvec[1] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[1] + 1);
3321                                 fogvec[2] *= r_glsl_contrastboost.value / ((r_glsl_contrastboost.value - 1) * fogvec[2] + 1);
3322                         }
3323                         //   color.rgb *= ContrastBoost * SceneBrightness;
3324                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
3325                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
3326                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
3327                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
3328                 }
3329         }
3330 }
3331
3332 void R_UpdateVariables(void)
3333 {
3334         R_Textures_Frame();
3335
3336         r_refdef.farclip = 4096;
3337         if (r_refdef.scene.worldmodel)
3338                 r_refdef.farclip += VectorDistance(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs);
3339         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
3340
3341         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
3342                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
3343         r_refdef.polygonfactor = 0;
3344         r_refdef.polygonoffset = 0;
3345         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
3346         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
3347
3348         r_refdef.rtworld = r_shadow_realtime_world.integer;
3349         r_refdef.rtworldshadows = r_shadow_realtime_world_shadows.integer && gl_stencil;
3350         r_refdef.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
3351         r_refdef.rtdlightshadows = r_refdef.rtdlight && r_shadow_realtime_dlight_shadows.integer && gl_stencil;
3352         r_refdef.lightmapintensity = r_refdef.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
3353         if (r_showsurfaces.integer)
3354         {
3355                 r_refdef.rtworld = false;
3356                 r_refdef.rtworldshadows = false;
3357                 r_refdef.rtdlight = false;
3358                 r_refdef.rtdlightshadows = false;
3359                 r_refdef.lightmapintensity = 0;
3360         }
3361
3362         if (gamemode == GAME_NEHAHRA)
3363         {
3364                 if (gl_fogenable.integer)
3365                 {
3366                         r_refdef.oldgl_fogenable = true;
3367                         r_refdef.fog_density = gl_fogdensity.value;
3368                         r_refdef.fog_red = gl_fogred.value;
3369                         r_refdef.fog_green = gl_foggreen.value;
3370                         r_refdef.fog_blue = gl_fogblue.value;
3371                         r_refdef.fog_alpha = 1;
3372                         r_refdef.fog_start = 0;
3373                         r_refdef.fog_end = gl_skyclip.value;
3374                 }
3375                 else if (r_refdef.oldgl_fogenable)
3376                 {
3377                         r_refdef.oldgl_fogenable = false;
3378                         r_refdef.fog_density = 0;
3379                         r_refdef.fog_red = 0;
3380                         r_refdef.fog_green = 0;
3381                         r_refdef.fog_blue = 0;
3382                         r_refdef.fog_alpha = 0;
3383                         r_refdef.fog_start = 0;
3384                         r_refdef.fog_end = 0;
3385                 }
3386         }
3387
3388         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
3389         r_refdef.fog_start = max(0, r_refdef.fog_start);
3390         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
3391
3392         // R_UpdateFogColor(); // why? R_RenderScene does it anyway
3393
3394         if (r_refdef.fog_density)
3395         {
3396                 r_refdef.fogenabled = true;
3397                 // this is the point where the fog reaches 0.9986 alpha, which we
3398                 // consider a good enough cutoff point for the texture
3399                 // (0.9986 * 256 == 255.6)
3400                 if (r_fog_exp2.integer)
3401                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
3402                 else
3403                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
3404                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
3405                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
3406                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
3407                 // fog color was already set
3408                 // update the fog texture
3409                 if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
3410                         R_BuildFogTexture();
3411         }
3412         else
3413                 r_refdef.fogenabled = false;
3414 }
3415
3416 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
3417 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
3418 /*
3419 ================
3420 R_SelectScene
3421 ================
3422 */
3423 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
3424         if( scenetype != r_currentscenetype ) {
3425                 // store the old scenetype
3426                 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
3427                 r_currentscenetype = scenetype;
3428                 // move in the new scene
3429                 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
3430         }
3431 }
3432
3433 /*
3434 ================
3435 R_GetScenePointer
3436 ================
3437 */
3438 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
3439 {
3440         // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
3441         if( scenetype == r_currentscenetype ) {
3442                 return &r_refdef.scene;
3443         } else {
3444                 return &r_scenes_store[ scenetype ];
3445         }
3446 }
3447
3448 /*
3449 ================
3450 R_RenderView
3451 ================
3452 */
3453 void R_RenderView(void)
3454 {
3455         if (!r_refdef.scene.entities/* || !r_refdef.scene.worldmodel*/)
3456                 return; //Host_Error ("R_RenderView: NULL worldmodel");
3457
3458         r_refdef.view.colorscale = r_hdr_scenebrightness.value;
3459
3460         // break apart the view matrix into vectors for various purposes
3461         // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
3462         // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
3463         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
3464         VectorNegate(r_refdef.view.left, r_refdef.view.right);
3465         // make an inverted copy of the view matrix for tracking sprites
3466         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
3467
3468         R_Shadow_UpdateWorldLightSelection();
3469
3470         R_Bloom_StartFrame();
3471         R_Water_StartFrame();
3472
3473         CHECKGLERROR
3474         if (r_timereport_active)
3475                 R_TimeReport("viewsetup");
3476
3477         R_ResetViewRendering3D();
3478
3479         if (r_refdef.view.clear || r_refdef.fogenabled)
3480         {
3481                 R_ClearScreen(r_refdef.fogenabled);
3482                 if (r_timereport_active)
3483                         R_TimeReport("viewclear");
3484         }
3485         r_refdef.view.clear = true;
3486
3487         r_refdef.view.showdebug = true;
3488
3489         // this produces a bloom texture to be used in R_BlendView() later
3490         if (r_hdr.integer)
3491                 R_HDR_RenderBloomTexture();
3492
3493         r_waterstate.numwaterplanes = 0;
3494         R_RenderScene(r_waterstate.enabled);
3495
3496         R_BlendView();
3497         if (r_timereport_active)
3498                 R_TimeReport("blendview");
3499
3500         GL_Scissor(0, 0, vid.width, vid.height);
3501         GL_ScissorTest(false);
3502         CHECKGLERROR
3503 }
3504
3505 extern void R_DrawLightningBeams (void);
3506 extern void VM_CL_AddPolygonsToMeshQueue (void);
3507 extern void R_DrawPortals (void);
3508 extern cvar_t cl_locs_show;
3509 static void R_DrawLocs(void);
3510 static void R_DrawEntityBBoxes(void);
3511 void R_RenderScene(qboolean addwaterplanes)
3512 {
3513         r_refdef.stats.renders++;
3514
3515         R_UpdateFogColor();
3516
3517         if (addwaterplanes)
3518         {
3519                 R_ResetViewRendering3D();
3520
3521                 R_View_Update();
3522                 if (r_timereport_active)
3523                         R_TimeReport("watervis");
3524
3525                 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
3526                 {
3527                         r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
3528                         if (r_timereport_active)
3529                                 R_TimeReport("waterworld");
3530                 }
3531
3532                 // don't let sound skip if going slow
3533                 if (r_refdef.scene.extraupdate)
3534                         S_ExtraUpdate ();
3535
3536                 R_DrawModelsAddWaterPlanes();
3537                 if (r_timereport_active)
3538                         R_TimeReport("watermodels");
3539
3540                 R_Water_ProcessPlanes();
3541                 if (r_timereport_active)
3542                         R_TimeReport("waterscenes");
3543         }
3544
3545         R_ResetViewRendering3D();
3546
3547         // don't let sound skip if going slow
3548         if (r_refdef.scene.extraupdate)
3549                 S_ExtraUpdate ();
3550
3551         R_MeshQueue_BeginScene();
3552
3553         R_SkyStartFrame();
3554
3555         R_View_Update();
3556         if (r_timereport_active)
3557                 R_TimeReport("visibility");
3558
3559         Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
3560
3561         if (cl.csqc_vidvars.drawworld)
3562         {
3563                 // don't let sound skip if going slow
3564                 if (r_refdef.scene.extraupdate)
3565                         S_ExtraUpdate ();
3566
3567                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
3568                 {
3569                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
3570                         if (r_timereport_active)
3571                                 R_TimeReport("worldsky");
3572                 }
3573
3574                 if (R_DrawBrushModelsSky() && r_timereport_active)
3575                         R_TimeReport("bmodelsky");
3576         }
3577
3578         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
3579         {
3580                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
3581                 if (r_timereport_active)
3582                         R_TimeReport("worlddepth");
3583         }
3584         if (r_depthfirst.integer >= 2)
3585         {
3586                 R_DrawModelsDepth();
3587                 if (r_timereport_active)
3588                         R_TimeReport("modeldepth");
3589         }
3590
3591         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
3592         {
3593                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
3594                 if (r_timereport_active)
3595                         R_TimeReport("world");
3596         }
3597
3598         // don't let sound skip if going slow
3599         if (r_refdef.scene.extraupdate)
3600                 S_ExtraUpdate ();
3601
3602         R_DrawModels();
3603         if (r_timereport_active)
3604                 R_TimeReport("models");
3605
3606         // don't let sound skip if going slow
3607         if (r_refdef.scene.extraupdate)
3608                 S_ExtraUpdate ();
3609
3610         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
3611         {
3612                 R_DrawModelShadows();
3613
3614                 R_ResetViewRendering3D();
3615
3616                 // don't let sound skip if going slow
3617                 if (r_refdef.scene.extraupdate)
3618                         S_ExtraUpdate ();
3619         }
3620
3621         R_ShadowVolumeLighting(false);
3622         if (r_timereport_active)
3623                 R_TimeReport("rtlights");
3624
3625         // don't let sound skip if going slow
3626         if (r_refdef.scene.extraupdate)
3627                 S_ExtraUpdate ();
3628
3629         if (cl.csqc_vidvars.drawworld)
3630         {
3631                 R_DrawLightningBeams();
3632                 if (r_timereport_active)
3633                         R_TimeReport("lightning");
3634
3635                 R_DrawDecals();
3636                 if (r_timereport_active)
3637                         R_TimeReport("decals");
3638
3639                 R_DrawParticles();
3640                 if (r_timereport_active)
3641                         R_TimeReport("particles");
3642
3643                 R_DrawExplosions();
3644                 if (r_timereport_active)
3645                         R_TimeReport("explosions");
3646         }
3647
3648         if (gl_support_fragment_shader)
3649         {
3650                 qglUseProgramObjectARB(0);CHECKGLERROR
3651         }
3652         VM_CL_AddPolygonsToMeshQueue();
3653
3654         if (r_refdef.view.showdebug)
3655         {
3656                 if (cl_locs_show.integer)
3657                 {
3658                         R_DrawLocs();
3659                         if (r_timereport_active)
3660                                 R_TimeReport("showlocs");
3661                 }
3662
3663                 if (r_drawportals.integer)
3664                 {
3665                         R_DrawPortals();
3666                         if (r_timereport_active)
3667                                 R_TimeReport("portals");
3668                 }
3669
3670                 if (r_showbboxes.value > 0)
3671                 {
3672                         R_DrawEntityBBoxes();
3673                         if (r_timereport_active)
3674                                 R_TimeReport("bboxes");
3675                 }
3676         }
3677
3678         if (gl_support_fragment_shader)
3679         {
3680                 qglUseProgramObjectARB(0);CHECKGLERROR
3681         }
3682         R_MeshQueue_RenderTransparent();
3683         if (r_timereport_active)
3684                 R_TimeReport("drawtrans");
3685
3686         if (gl_support_fragment_shader)
3687         {
3688                 qglUseProgramObjectARB(0);CHECKGLERROR
3689         }
3690
3691         if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value > 0 || r_showcollisionbrushes.value > 0))
3692         {
3693                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
3694                 if (r_timereport_active)
3695                         R_TimeReport("worlddebug");
3696                 R_DrawModelsDebug();
3697                 if (r_timereport_active)
3698                         R_TimeReport("modeldebug");
3699         }
3700
3701         if (gl_support_fragment_shader)
3702         {
3703                 qglUseProgramObjectARB(0);CHECKGLERROR
3704         }
3705
3706         if (cl.csqc_vidvars.drawworld)
3707         {
3708                 R_DrawCoronas();
3709                 if (r_timereport_active)
3710                         R_TimeReport("coronas");
3711         }
3712
3713         // don't let sound skip if going slow
3714         if (r_refdef.scene.extraupdate)
3715                 S_ExtraUpdate ();
3716
3717         R_ResetViewRendering2D();
3718 }
3719
3720 static const int bboxelements[36] =
3721 {
3722         5, 1, 3, 5, 3, 7,
3723         6, 2, 0, 6, 0, 4,
3724         7, 3, 2, 7, 2, 6,
3725         4, 0, 1, 4, 1, 5,
3726         4, 5, 7, 4, 7, 6,
3727         1, 0, 2, 1, 2, 3,
3728 };
3729
3730 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
3731 {
3732         int i;
3733         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
3734         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3735         GL_DepthMask(false);
3736         GL_DepthRange(0, 1);
3737         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
3738         R_Mesh_Matrix(&identitymatrix);
3739         R_Mesh_ResetTextureState();
3740
3741         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
3742         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
3743         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
3744         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
3745         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
3746         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
3747         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
3748         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
3749         R_FillColors(color4f, 8, cr, cg, cb, ca);
3750         if (r_refdef.fogenabled)
3751         {
3752                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
3753                 {
3754                         f1 = FogPoint_World(v);
3755                         f2 = 1 - f1;
3756                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
3757                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
3758                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
3759                 }
3760         }
3761         R_Mesh_VertexPointer(vertex3f, 0, 0);
3762         R_Mesh_ColorPointer(color4f, 0, 0);
3763         R_Mesh_ResetTextureState();
3764         R_Mesh_Draw(0, 8, 12, bboxelements, 0, 0);
3765 }
3766
3767 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
3768 {
3769         int i;
3770         float color[4];
3771         prvm_edict_t *edict;
3772         // this function draws bounding boxes of server entities
3773         if (!sv.active)
3774                 return;
3775         SV_VM_Begin();
3776         for (i = 0;i < numsurfaces;i++)
3777         {
3778                 edict = PRVM_EDICT_NUM(surfacelist[i]);
3779                 switch ((int)edict->fields.server->solid)
3780                 {
3781                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
3782                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
3783                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
3784                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
3785                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
3786                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
3787                 }
3788                 color[3] *= r_showbboxes.value;
3789                 color[3] = bound(0, color[3], 1);
3790                 GL_DepthTest(!r_showdisabledepthtest.integer);
3791                 GL_CullFace(r_refdef.view.cullface_front);
3792                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
3793         }
3794         SV_VM_End();
3795 }
3796
3797 static void R_DrawEntityBBoxes(void)
3798 {
3799         int i;
3800         prvm_edict_t *edict;
3801         vec3_t center;
3802         // this function draws bounding boxes of server entities
3803         if (!sv.active)
3804                 return;
3805         SV_VM_Begin();
3806         for (i = 0;i < prog->num_edicts;i++)
3807         {
3808                 edict = PRVM_EDICT_NUM(i);
3809                 if (edict->priv.server->free)
3810                         continue;
3811                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
3812                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
3813         }
3814         SV_VM_End();
3815 }
3816
3817 int nomodelelements[24] =
3818 {
3819         5, 2, 0,
3820         5, 1, 2,
3821         5, 0, 3,
3822         5, 3, 1,
3823         0, 2, 4,
3824         2, 1, 4,
3825         3, 0, 4,
3826         1, 3, 4
3827 };
3828
3829 float nomodelvertex3f[6*3] =
3830 {
3831         -16,   0,   0,
3832          16,   0,   0,
3833           0, -16,   0,
3834           0,  16,   0,
3835           0,   0, -16,
3836           0,   0,  16
3837 };
3838
3839 float nomodelcolor4f[6*4] =
3840 {
3841         0.0f, 0.0f, 0.5f, 1.0f,
3842         0.0f, 0.0f, 0.5f, 1.0f,
3843         0.0f, 0.5f, 0.0f, 1.0f,
3844         0.0f, 0.5f, 0.0f, 1.0f,
3845         0.5f, 0.0f, 0.0f, 1.0f,
3846         0.5f, 0.0f, 0.0f, 1.0f
3847 };
3848
3849 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
3850 {
3851         int i;
3852         float f1, f2, *c;
3853         float color4f[6*4];
3854         // this is only called once per entity so numsurfaces is always 1, and
3855         // surfacelist is always {0}, so this code does not handle batches
3856         R_Mesh_Matrix(&ent->matrix);
3857
3858         if (ent->flags & EF_ADDITIVE)
3859         {
3860                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
3861                 GL_DepthMask(false);
3862         }
3863         else if (ent->alpha < 1)
3864         {
3865                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3866                 GL_DepthMask(false);
3867         }
3868         else
3869         {
3870                 GL_BlendFunc(GL_ONE, GL_ZERO);
3871                 GL_DepthMask(true);
3872         }
3873         GL_DepthRange(0, (ent->flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
3874         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
3875         GL_DepthTest(!(ent->effects & EF_NODEPTHTEST));
3876         GL_CullFace((ent->effects & EF_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
3877         R_Mesh_VertexPointer(nomodelvertex3f, 0, 0);
3878         if (r_refdef.fogenabled)
3879         {
3880                 vec3_t org;
3881                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
3882                 R_Mesh_ColorPointer(color4f, 0, 0);
3883                 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3884                 f1 = FogPoint_World(org);
3885                 f2 = 1 - f1;
3886                 for (i = 0, c = color4f;i < 6;i++, c += 4)
3887                 {
3888                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
3889                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
3890                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
3891                         c[3] *= ent->alpha;
3892                 }
3893         }
3894         else if (ent->alpha != 1)
3895         {
3896                 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
3897                 R_Mesh_ColorPointer(color4f, 0, 0);
3898                 for (i = 0, c = color4f;i < 6;i++, c += 4)
3899                         c[3] *= ent->alpha;
3900         }
3901         else
3902                 R_Mesh_ColorPointer(nomodelcolor4f, 0, 0);
3903         R_Mesh_ResetTextureState();
3904         R_Mesh_Draw(0, 6, 8, nomodelelements, 0, 0);
3905 }
3906
3907 void R_DrawNoModel(entity_render_t *ent)
3908 {
3909         vec3_t org;
3910         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
3911         //if ((ent->effects & EF_ADDITIVE) || (ent->alpha < 1))
3912                 R_MeshQueue_AddTransparent(ent->effects & EF_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
3913         //else
3914         //      R_DrawNoModelCallback(ent, 0);
3915 }
3916
3917 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
3918 {
3919         vec3_t right1, right2, diff, normal;
3920
3921         VectorSubtract (org2, org1, normal);
3922
3923         // calculate 'right' vector for start
3924         VectorSubtract (r_refdef.view.origin, org1, diff);
3925         CrossProduct (normal, diff, right1);
3926         VectorNormalize (right1);
3927
3928         // calculate 'right' vector for end
3929         VectorSubtract (r_refdef.view.origin, org2, diff);
3930         CrossProduct (normal, diff, right2);
3931         VectorNormalize (right2);
3932
3933         vert[ 0] = org1[0] + width * right1[0];
3934         vert[ 1] = org1[1] + width * right1[1];
3935         vert[ 2] = org1[2] + width * right1[2];
3936         vert[ 3] = org1[0] - width * right1[0];
3937         vert[ 4] = org1[1] - width * right1[1];
3938         vert[ 5] = org1[2] - width * right1[2];
3939         vert[ 6] = org2[0] - width * right2[0];
3940         vert[ 7] = org2[1] - width * right2[1];
3941         vert[ 8] = org2[2] - width * right2[2];
3942         vert[ 9] = org2[0] + width * right2[0];
3943         vert[10] = org2[1] + width * right2[1];
3944         vert[11] = org2[2] + width * right2[2];
3945 }
3946
3947 float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1};
3948
3949 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)
3950 {
3951         float fog = 1.0f;
3952         float vertex3f[12];
3953
3954         if (r_refdef.fogenabled && !depthdisable) // TODO maybe make the unfog effect a separate flag?
3955                 fog = FogPoint_World(origin);
3956
3957         R_Mesh_Matrix(&identitymatrix);
3958         GL_BlendFunc(blendfunc1, blendfunc2);
3959
3960         if(v_flipped_state)
3961         {
3962                 scalex1 = -scalex1;
3963                 scalex2 = -scalex2;
3964                 GL_CullFace(r_refdef.view.cullface_front);
3965         }
3966         else
3967                 GL_CullFace(r_refdef.view.cullface_back);
3968         GL_CullFace(GL_NONE);
3969
3970         GL_DepthMask(false);
3971         GL_DepthRange(0, depthshort ? 0.0625 : 1);
3972         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
3973         GL_DepthTest(!depthdisable);
3974
3975         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
3976         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
3977         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
3978         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
3979         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
3980         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
3981         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
3982         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
3983         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
3984         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
3985         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
3986         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
3987
3988         R_Mesh_VertexPointer(vertex3f, 0, 0);
3989         R_Mesh_ColorPointer(NULL, 0, 0);
3990         R_Mesh_ResetTextureState();
3991         R_Mesh_TexBind(0, R_GetTexture(texture));
3992         R_Mesh_TexCoordPointer(0, 2, spritetexcoord2f, 0, 0);
3993         // FIXME: fixed function path can't properly handle r_refdef.view.colorscale > 1
3994         GL_Color(cr * fog * r_refdef.view.colorscale, cg * fog * r_refdef.view.colorscale, cb * fog * r_refdef.view.colorscale, ca);
3995         R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
3996
3997         if (blendfunc2 == GL_ONE_MINUS_SRC_ALPHA)
3998         {
3999                 R_Mesh_TexBind(0, R_GetTexture(fogtexture));
4000                 GL_BlendFunc(blendfunc1, GL_ONE);
4001                 fog = 1 - fog;
4002                 GL_Color(r_refdef.fogcolor[0] * fog, r_refdef.fogcolor[1] * fog, r_refdef.fogcolor[2] * fog, ca);
4003                 R_Mesh_Draw(0, 4, 2, polygonelements, 0, 0);
4004         }
4005 }
4006
4007 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
4008 {
4009         int i;
4010         float *vertex3f;
4011         float v[3];
4012         VectorSet(v, x, y, z);
4013         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
4014                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
4015                         break;
4016         if (i == mesh->numvertices)
4017         {
4018                 if (mesh->numvertices < mesh->maxvertices)
4019                 {
4020                         VectorCopy(v, vertex3f);
4021                         mesh->numvertices++;
4022                 }
4023                 return mesh->numvertices;
4024         }
4025         else
4026                 return i;
4027 }
4028
4029 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
4030 {
4031         int i;
4032         int *e, element[3];
4033         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
4034         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
4035         e = mesh->element3i + mesh->numtriangles * 3;
4036         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
4037         {
4038                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
4039                 if (mesh->numtriangles < mesh->maxtriangles)
4040                 {
4041                         *e++ = element[0];
4042                         *e++ = element[1];
4043                         *e++ = element[2];
4044                         mesh->numtriangles++;
4045                 }
4046                 element[1] = element[2];
4047         }
4048 }
4049
4050 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
4051 {
4052         int i;
4053         int *e, element[3];
4054         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
4055         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
4056         e = mesh->element3i + mesh->numtriangles * 3;
4057         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
4058         {
4059                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
4060                 if (mesh->numtriangles < mesh->maxtriangles)
4061                 {
4062                         *e++ = element[0];
4063                         *e++ = element[1];
4064                         *e++ = element[2];
4065                         mesh->numtriangles++;
4066                 }
4067                 element[1] = element[2];
4068         }
4069 }
4070
4071 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
4072 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
4073 {
4074         int planenum, planenum2;
4075         int w;
4076         int tempnumpoints;
4077         mplane_t *plane, *plane2;
4078         double maxdist;
4079         double temppoints[2][256*3];
4080         // figure out how large a bounding box we need to properly compute this brush
4081         maxdist = 0;
4082         for (w = 0;w < numplanes;w++)
4083                 maxdist = max(maxdist, planes[w].dist);
4084         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
4085         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
4086         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
4087         {
4088                 w = 0;
4089                 tempnumpoints = 4;
4090                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
4091                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
4092                 {
4093                         if (planenum2 == planenum)
4094                                 continue;
4095                         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);
4096                         w = !w;
4097                 }
4098                 if (tempnumpoints < 3)
4099                         continue;
4100                 // generate elements forming a triangle fan for this polygon
4101                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
4102         }
4103 }
4104
4105 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)
4106 {
4107         texturelayer_t *layer;
4108         layer = t->currentlayers + t->currentnumlayers++;
4109         layer->type = type;
4110         layer->depthmask = depthmask;
4111         layer->blendfunc1 = blendfunc1;
4112         layer->blendfunc2 = blendfunc2;
4113         layer->texture = texture;
4114         layer->texmatrix = *matrix;
4115         layer->color[0] = r * r_refdef.view.colorscale;
4116         layer->color[1] = g * r_refdef.view.colorscale;
4117         layer->color[2] = b * r_refdef.view.colorscale;
4118         layer->color[3] = a;
4119 }
4120
4121 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
4122 {
4123         double index, f;
4124         index = parms[2] + r_refdef.scene.time * parms[3];
4125         index -= floor(index);
4126         switch (func)
4127         {
4128         default:
4129         case Q3WAVEFUNC_NONE:
4130         case Q3WAVEFUNC_NOISE:
4131         case Q3WAVEFUNC_COUNT:
4132                 f = 0;
4133                 break;
4134         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
4135         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
4136         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
4137         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
4138         case Q3WAVEFUNC_TRIANGLE:
4139                 index *= 4;
4140                 f = index - floor(index);
4141                 if (index < 1)
4142                         f = f;
4143                 else if (index < 2)
4144                         f = 1 - f;
4145                 else if (index < 3)
4146                         f = -f;
4147                 else
4148                         f = -(1 - f);
4149                 break;
4150         }
4151         return (float)(parms[0] + parms[1] * f);
4152 }
4153
4154 void R_UpdateTextureInfo(const entity_render_t *ent, texture_t *t)
4155 {
4156         int i;
4157         model_t *model = ent->model;
4158         float f;
4159         float tcmat[12];
4160         q3shaderinfo_layer_tcmod_t *tcmod;
4161
4162         // switch to an alternate material if this is a q1bsp animated material
4163         {
4164                 texture_t *texture = t;
4165                 int s = ent->skinnum;
4166                 if ((unsigned int)s >= (unsigned int)model->numskins)
4167                         s = 0;
4168                 if (model->skinscenes)
4169                 {
4170                         if (model->skinscenes[s].framecount > 1)
4171                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
4172                         else
4173                                 s = model->skinscenes[s].firstframe;
4174                 }
4175                 if (s > 0)
4176                         t = t + s * model->num_surfaces;
4177                 if (t->animated)
4178                 {
4179                         // use an alternate animation if the entity's frame is not 0,
4180                         // and only if the texture has an alternate animation
4181                         if (ent->frame2 != 0 && t->anim_total[1])
4182                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
4183                         else
4184                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
4185                 }
4186                 texture->currentframe = t;
4187         }
4188
4189         // update currentskinframe to be a qw skin or animation frame
4190         if ((i = ent->entitynumber - 1) >= 0 && i < cl.maxclients)
4191         {
4192                 if (strcmp(r_qwskincache[i], cl.scores[i].qw_skin))
4193                 {
4194                         strlcpy(r_qwskincache[i], cl.scores[i].qw_skin, sizeof(r_qwskincache[i]));
4195                         Con_DPrintf("loading skins/%s\n", r_qwskincache[i]);
4196                         r_qwskincache_skinframe[i] = R_SkinFrame_LoadExternal(va("skins/%s", r_qwskincache[i]), TEXF_PRECACHE | (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS, developer.integer > 0);
4197                 }
4198                 t->currentskinframe = r_qwskincache_skinframe[i];
4199                 if (t->currentskinframe == NULL)
4200                         t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
4201         }
4202         else if (t->numskinframes >= 2)
4203                 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - ent->frame2time)) % t->numskinframes];
4204         if (t->backgroundnumskinframes >= 2)
4205                 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - ent->frame2time)) % t->backgroundnumskinframes];
4206
4207         t->currentmaterialflags = t->basematerialflags;
4208         t->currentalpha = ent->alpha;
4209         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
4210         {
4211                 t->currentalpha *= r_wateralpha.value;
4212                 /*
4213                  * FIXME what is this supposed to do?
4214                 // if rendering refraction/reflection, disable transparency
4215                 if (r_waterstate.enabled && (t->currentalpha < 1 || (t->currentmaterialflags & MATERIALFLAG_ALPHA)))
4216                         t->currentmaterialflags |= MATERIALFLAG_WATERSHADER;
4217                 */
4218         }
4219         if(!r_waterstate.enabled)
4220                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION);
4221         if (!(ent->flags & RENDER_LIGHT))
4222                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
4223         else if (rsurface.modeltexcoordlightmap2f == NULL)
4224         {
4225                 // pick a model lighting mode
4226                 if (VectorLength2(ent->modellight_diffuse) >= (1.0f / 256.0f))
4227                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
4228                 else
4229                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
4230         }
4231         if (ent->effects & EF_ADDITIVE)
4232                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
4233         else if (t->currentalpha < 1)
4234                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
4235         if (ent->effects & EF_DOUBLESIDED)
4236                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
4237         if (ent->effects & EF_NODEPTHTEST)
4238                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
4239         if (ent->flags & RENDER_VIEWMODEL)
4240                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
4241         if (t->backgroundnumskinframes)
4242                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
4243         if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
4244         {
4245                 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER))
4246                         t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
4247         }
4248         else
4249                 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER);
4250
4251         // there is no tcmod
4252         if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
4253                 t->currenttexmatrix = r_waterscrollmatrix;
4254
4255         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
4256         {
4257                 matrix4x4_t matrix;
4258                 switch(tcmod->tcmod)
4259                 {
4260                 case Q3TCMOD_COUNT:
4261                 case Q3TCMOD_NONE:
4262                         if (t->currentmaterialflags & MATERIALFLAG_WATER && r_waterscroll.value != 0)
4263                                 matrix = r_waterscrollmatrix;
4264                         else
4265                                 matrix = identitymatrix;
4266                         break;
4267                 case Q3TCMOD_ENTITYTRANSLATE:
4268                         // this is used in Q3 to allow the gamecode to control texcoord
4269                         // scrolling on the entity, which is not supported in darkplaces yet.
4270                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
4271                         break;
4272                 case Q3TCMOD_ROTATE:
4273                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
4274                         Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
4275                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
4276                         break;
4277                 case Q3TCMOD_SCALE:
4278                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
4279                         break;
4280                 case Q3TCMOD_SCROLL:
4281                         Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
4282                         break;
4283                 case Q3TCMOD_STRETCH:
4284                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
4285                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
4286                         break;
4287                 case Q3TCMOD_TRANSFORM:
4288                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
4289                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
4290                         VectorSet(tcmat +  6, 0                   , 0                , 1);
4291                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
4292                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
4293                         break;
4294                 case Q3TCMOD_TURBULENT:
4295                         // this is handled in the RSurf_PrepareVertices function
4296                         matrix = identitymatrix;
4297                         break;
4298                 }
4299                 // either replace or concatenate the transformation
4300                 if (i < 1)
4301                         t->currenttexmatrix = matrix;
4302                 else
4303                 {
4304                         matrix4x4_t temp = t->currenttexmatrix;
4305                         Matrix4x4_Concat(&t->currenttexmatrix, &matrix, &temp);
4306                 }
4307         }
4308
4309         t->colormapping = VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f);
4310         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
4311         t->glosstexture = r_texture_black;
4312         t->backgroundbasetexture = t->backgroundnumskinframes ? ((!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base) : r_texture_white;
4313         t->backgroundglosstexture = r_texture_black;
4314         t->specularpower = r_shadow_glossexponent.value;
4315         // TODO: store reference values for these in the texture?
4316         t->specularscale = 0;
4317         if (r_shadow_gloss.integer > 0)
4318         {
4319                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
4320                 {
4321                         if (r_shadow_glossintensity.value > 0)
4322                         {
4323                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
4324                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
4325                                 t->specularscale = r_shadow_glossintensity.value;
4326                         }
4327                 }
4328                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
4329                 {
4330                         t->glosstexture = r_texture_white;
4331                         t->backgroundglosstexture = r_texture_white;
4332                         t->specularscale = r_shadow_gloss2intensity.value;
4333                 }
4334         }
4335
4336         // lightmaps mode looks bad with dlights using actual texturing, so turn
4337         // off the colormap and glossmap, but leave the normalmap on as it still
4338         // accurately represents the shading involved
4339         if (gl_lightmaps.integer && !(t->currentmaterialflags & MATERIALFLAG_BLENDED))
4340         {
4341                 t->basetexture = r_texture_white;
4342                 t->specularscale = 0;
4343         }
4344
4345         Vector4Set(t->lightmapcolor, ent->colormod[0], ent->colormod[1], ent->colormod[2], t->currentalpha);
4346         VectorClear(t->dlightcolor);
4347         t->currentnumlayers = 0;
4348         if (!(t->currentmaterialflags & MATERIALFLAG_NODRAW))
4349         {
4350                 if (!(t->currentmaterialflags & MATERIALFLAG_SKY))
4351                 {
4352                         int blendfunc1, blendfunc2, depthmask;
4353                         if (t->currentmaterialflags & MATERIALFLAG_ADD)
4354                         {
4355                                 blendfunc1 = GL_SRC_ALPHA;
4356                                 blendfunc2 = GL_ONE;
4357                         }
4358                         else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
4359                         {
4360                                 blendfunc1 = GL_SRC_ALPHA;
4361                                 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
4362                         }
4363                         else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
4364                         {
4365                                 blendfunc1 = t->customblendfunc[0];
4366                                 blendfunc2 = t->customblendfunc[1];
4367                         }
4368                         else
4369                         {
4370                                 blendfunc1 = GL_ONE;
4371                                 blendfunc2 = GL_ZERO;
4372                         }
4373                         depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
4374                         if (t->currentmaterialflags & (MATERIALFLAG_WATER | MATERIALFLAG_WALL))
4375                         {
4376                                 rtexture_t *currentbasetexture;
4377                                 int layerflags = 0;
4378                                 if (r_refdef.fogenabled && (t->currentmaterialflags & MATERIALFLAG_BLENDED))
4379                                         layerflags |= TEXTURELAYERFLAG_FOGDARKEN;
4380                                 currentbasetexture = (VectorLength2(ent->colormap_pantscolor) + VectorLength2(ent->colormap_shirtcolor) < (1.0f / 1048576.0f) && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
4381                                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4382                                 {
4383                                         // fullbright is not affected by r_refdef.lightmapintensity
4384                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
4385                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
4386                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * t->lightmapcolor[0], ent->colormap_pantscolor[1] * t->lightmapcolor[1], ent->colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
4387                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
4388                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * t->lightmapcolor[0], ent->colormap_shirtcolor[1] * t->lightmapcolor[1], ent->colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
4389                                 }
4390                                 else
4391                                 {
4392                                         vec3_t ambientcolor;
4393                                         float colorscale;
4394                                         // set the color tint used for lights affecting this surface
4395                                         VectorSet(t->dlightcolor, ent->colormod[0] * t->lightmapcolor[3], ent->colormod[1] * t->lightmapcolor[3], ent->colormod[2] * t->lightmapcolor[3]);
4396                                         colorscale = 2;
4397                                         // q3bsp has no lightmap updates, so the lightstylevalue that
4398                                         // would normally be baked into the lightmap must be
4399                                         // applied to the color
4400                                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
4401                                         if (ent->model->type == mod_brushq3)
4402                                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
4403                                         colorscale *= r_refdef.lightmapintensity;
4404                                         VectorScale(t->lightmapcolor, r_ambient.value * (1.0f / 64.0f), ambientcolor);
4405                                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
4406                                         // basic lit geometry
4407                                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, currentbasetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
4408                                         // add pants/shirt if needed
4409                                         if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
4410                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * t->lightmapcolor[0], ent->colormap_pantscolor[1] * t->lightmapcolor[1], ent->colormap_pantscolor[2]  * t->lightmapcolor[2], t->lightmapcolor[3]);
4411                                         if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
4412                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * t->lightmapcolor[0], ent->colormap_shirtcolor[1] * t->lightmapcolor[1], ent->colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
4413                                         // now add ambient passes if needed
4414                                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
4415                                         {
4416                                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, currentbasetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
4417                                                 if (VectorLength2(ent->colormap_pantscolor) >= (1.0f / 1048576.0f) && t->currentskinframe->pants)
4418                                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->pants, &t->currenttexmatrix, ent->colormap_pantscolor[0] * ambientcolor[0], ent->colormap_pantscolor[1] * ambientcolor[1], ent->colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
4419                                                 if (VectorLength2(ent->colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->currentskinframe->shirt)
4420                                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->currentskinframe->shirt, &t->currenttexmatrix, ent->colormap_shirtcolor[0] * ambientcolor[0], ent->colormap_shirtcolor[1] * ambientcolor[1], ent->colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
4421                                         }
4422                                 }
4423                                 if (t->currentskinframe->glow != NULL)
4424                                         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->lightmapcolor[3]);
4425                                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
4426                                 {
4427                                         // if this is opaque use alpha blend which will darken the earlier
4428                                         // passes cheaply.
4429                                         //
4430                                         // if this is an alpha blended material, all the earlier passes
4431                                         // were darkened by fog already, so we only need to add the fog
4432                                         // color ontop through the fog mask texture
4433                                         //
4434                                         // if this is an additive blended material, all the earlier passes
4435                                         // were darkened by fog already, and we should not add fog color
4436                                         // (because the background was not darkened, there is no fog color
4437                                         // that was lost behind it).
4438                                         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.view.colorscale, r_refdef.fogcolor[1] / r_refdef.view.colorscale, r_refdef.fogcolor[2] / r_refdef.view.colorscale, t->lightmapcolor[3]);
4439                                 }
4440                         }
4441                 }
4442         }
4443 }
4444
4445 void R_UpdateAllTextureInfo(entity_render_t *ent)
4446 {
4447         int i;
4448         if (ent->model)
4449                 for (i = 0;i < ent->model->num_texturesperskin;i++)
4450                         R_UpdateTextureInfo(ent, ent->model->data_textures + i);
4451 }
4452
4453 rsurfacestate_t rsurface;
4454
4455 void R_Mesh_ResizeArrays(int newvertices)
4456 {
4457         float *base;
4458         if (rsurface.array_size >= newvertices)
4459                 return;
4460         if (rsurface.array_modelvertex3f)
4461                 Mem_Free(rsurface.array_modelvertex3f);
4462         rsurface.array_size = (newvertices + 1023) & ~1023;
4463         base = (float *)Mem_Alloc(r_main_mempool, rsurface.array_size * sizeof(float[33]));
4464         rsurface.array_modelvertex3f     = base + rsurface.array_size * 0;
4465         rsurface.array_modelsvector3f    = base + rsurface.array_size * 3;
4466         rsurface.array_modeltvector3f    = base + rsurface.array_size * 6;
4467         rsurface.array_modelnormal3f     = base + rsurface.array_size * 9;
4468         rsurface.array_deformedvertex3f  = base + rsurface.array_size * 12;
4469         rsurface.array_deformedsvector3f = base + rsurface.array_size * 15;
4470         rsurface.array_deformedtvector3f = base + rsurface.array_size * 18;
4471         rsurface.array_deformednormal3f  = base + rsurface.array_size * 21;
4472         rsurface.array_texcoord3f        = base + rsurface.array_size * 24;
4473         rsurface.array_color4f           = base + rsurface.array_size * 27;
4474         rsurface.array_generatedtexcoordtexture2f = base + rsurface.array_size * 31;
4475 }
4476
4477 void RSurf_CleanUp(void)
4478 {
4479         CHECKGLERROR
4480         if (rsurface.mode == RSURFMODE_GLSL)
4481         {
4482                 qglUseProgramObjectARB(0);CHECKGLERROR
4483         }
4484         GL_AlphaTest(false);
4485         rsurface.mode = RSURFMODE_NONE;
4486         rsurface.uselightmaptexture = false;
4487         rsurface.texture = NULL;
4488 }
4489
4490 void RSurf_ActiveWorldEntity(void)
4491 {
4492         model_t *model = r_refdef.scene.worldmodel;
4493         RSurf_CleanUp();
4494         if (rsurface.array_size < model->surfmesh.num_vertices)
4495                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
4496         rsurface.matrix = identitymatrix;
4497         rsurface.inversematrix = identitymatrix;
4498         R_Mesh_Matrix(&identitymatrix);
4499         VectorCopy(r_refdef.view.origin, rsurface.modelorg);
4500         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
4501         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
4502         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
4503         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
4504         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
4505         rsurface.frameblend[0].frame = 0;
4506         rsurface.frameblend[0].lerp = 1;
4507         rsurface.frameblend[1].frame = 0;
4508         rsurface.frameblend[1].lerp = 0;
4509         rsurface.frameblend[2].frame = 0;
4510         rsurface.frameblend[2].lerp = 0;
4511         rsurface.frameblend[3].frame = 0;
4512         rsurface.frameblend[3].lerp = 0;
4513         rsurface.basepolygonfactor = r_refdef.polygonfactor;
4514         rsurface.basepolygonoffset = r_refdef.polygonoffset;
4515         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
4516         rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
4517         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
4518         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
4519         rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
4520         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
4521         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
4522         rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
4523         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
4524         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
4525         rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
4526         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
4527         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
4528         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
4529         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
4530         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
4531         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
4532         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
4533         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
4534         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
4535         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
4536         rsurface.modelelement3i = model->surfmesh.data_element3i;
4537         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo;
4538         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
4539         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
4540         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
4541         rsurface.modelsurfaces = model->data_surfaces;
4542         rsurface.generatedvertex = false;
4543         rsurface.vertex3f  = rsurface.modelvertex3f;
4544         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
4545         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
4546         rsurface.svector3f = rsurface.modelsvector3f;
4547         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
4548         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
4549         rsurface.tvector3f = rsurface.modeltvector3f;
4550         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
4551         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
4552         rsurface.normal3f  = rsurface.modelnormal3f;
4553         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
4554         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
4555         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
4556 }
4557
4558 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
4559 {
4560         model_t *model = ent->model;
4561         RSurf_CleanUp();
4562         if (rsurface.array_size < model->surfmesh.num_vertices)
4563                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
4564         rsurface.matrix = ent->matrix;
4565         rsurface.inversematrix = ent->inversematrix;
4566         R_Mesh_Matrix(&rsurface.matrix);
4567         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.modelorg);
4568         rsurface.modellight_ambient[0] = ent->modellight_ambient[0] * ent->colormod[0];
4569         rsurface.modellight_ambient[1] = ent->modellight_ambient[1] * ent->colormod[1];
4570         rsurface.modellight_ambient[2] = ent->modellight_ambient[2] * ent->colormod[2];
4571         rsurface.modellight_diffuse[0] = ent->modellight_diffuse[0] * ent->colormod[0];
4572         rsurface.modellight_diffuse[1] = ent->modellight_diffuse[1] * ent->colormod[1];
4573         rsurface.modellight_diffuse[2] = ent->modellight_diffuse[2] * ent->colormod[2];
4574         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
4575         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
4576         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
4577         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
4578         rsurface.frameblend[0] = ent->frameblend[0];
4579         rsurface.frameblend[1] = ent->frameblend[1];
4580         rsurface.frameblend[2] = ent->frameblend[2];
4581         rsurface.frameblend[3] = ent->frameblend[3];
4582         rsurface.basepolygonfactor = r_refdef.polygonfactor;
4583         rsurface.basepolygonoffset = r_refdef.polygonoffset;
4584         if (ent->model->brush.submodel)
4585         {
4586                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
4587                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
4588         }
4589         if (model->surfmesh.isanimated && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].frame != 0))
4590         {
4591                 if (wanttangents)
4592                 {
4593                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
4594                         rsurface.modelsvector3f = rsurface.array_modelsvector3f;
4595                         rsurface.modeltvector3f = rsurface.array_modeltvector3f;
4596                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
4597                         Mod_Alias_GetMesh_Vertices(model, rsurface.frameblend, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
4598                 }
4599                 else if (wantnormals)
4600                 {
4601                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
4602                         rsurface.modelsvector3f = NULL;
4603                         rsurface.modeltvector3f = NULL;
4604                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
4605                         Mod_Alias_GetMesh_Vertices(model, rsurface.frameblend, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
4606                 }
4607                 else
4608                 {
4609                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
4610                         rsurface.modelsvector3f = NULL;
4611                         rsurface.modeltvector3f = NULL;
4612                         rsurface.modelnormal3f = NULL;
4613                         Mod_Alias_GetMesh_Vertices(model, rsurface.frameblend, rsurface.array_modelvertex3f, NULL, NULL, NULL);
4614                 }
4615                 rsurface.modelvertex3f_bufferobject = 0;
4616                 rsurface.modelvertex3f_bufferoffset = 0;
4617                 rsurface.modelsvector3f_bufferobject = 0;
4618                 rsurface.modelsvector3f_bufferoffset = 0;
4619                 rsurface.modeltvector3f_bufferobject = 0;
4620                 rsurface.modeltvector3f_bufferoffset = 0;
4621                 rsurface.modelnormal3f_bufferobject = 0;
4622                 rsurface.modelnormal3f_bufferoffset = 0;
4623                 rsurface.generatedvertex = true;
4624         }
4625         else
4626         {
4627                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
4628                 rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
4629                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
4630                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
4631                 rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
4632                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
4633                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
4634                 rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
4635                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
4636                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
4637                 rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
4638                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
4639                 rsurface.generatedvertex = false;
4640         }
4641         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
4642         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
4643         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
4644         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
4645         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
4646         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
4647         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
4648         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
4649         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
4650         rsurface.modelelement3i = model->surfmesh.data_element3i;
4651         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo;
4652         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
4653         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
4654         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
4655         rsurface.modelsurfaces = model->data_surfaces;
4656         rsurface.vertex3f  = rsurface.modelvertex3f;
4657         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
4658         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
4659         rsurface.svector3f = rsurface.modelsvector3f;
4660         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
4661         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
4662         rsurface.tvector3f = rsurface.modeltvector3f;
4663         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
4664         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
4665         rsurface.normal3f  = rsurface.modelnormal3f;
4666         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
4667         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
4668         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
4669 }
4670
4671 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
4672 void RSurf_PrepareVerticesForBatch(qboolean generatenormals, qboolean generatetangents, int texturenumsurfaces, msurface_t **texturesurfacelist)
4673 {
4674         int deformindex;
4675         int texturesurfaceindex;
4676         int i, j;
4677         float amplitude;
4678         float animpos;
4679         float scale;
4680         const float *v1, *in_tc;
4681         float *out_tc;
4682         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
4683         float waveparms[4];
4684         q3shaderinfo_deform_t *deform;
4685         // 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
4686         if (rsurface.generatedvertex)
4687         {
4688                 if (rsurface.texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
4689                         generatenormals = true;
4690                 for (i = 0;i < Q3MAXDEFORMS;i++)
4691                 {
4692                         if (rsurface.texture->deforms[i].deform == Q3DEFORM_AUTOSPRITE)
4693                         {
4694                                 generatetangents = true;
4695                                 generatenormals = true;
4696                         }
4697                         if (rsurface.texture->deforms[i].deform != Q3DEFORM_NONE)
4698                                 generatenormals = true;
4699                 }
4700                 if (generatenormals && !rsurface.modelnormal3f)
4701                 {
4702                         rsurface.normal3f = rsurface.modelnormal3f = rsurface.array_modelnormal3f;
4703                         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject = 0;
4704                         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset = 0;
4705                         Mod_BuildNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer);
4706                 }
4707                 if (generatetangents && !rsurface.modelsvector3f)
4708                 {
4709                         rsurface.svector3f = rsurface.modelsvector3f = rsurface.array_modelsvector3f;
4710                         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject = 0;
4711                         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset = 0;
4712                         rsurface.tvector3f = rsurface.modeltvector3f = rsurface.array_modeltvector3f;
4713                         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject = 0;
4714                         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset = 0;
4715                         Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f, r_smoothnormals_areaweighting.integer);
4716                 }
4717         }
4718         rsurface.vertex3f  = rsurface.modelvertex3f;
4719         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
4720         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
4721         rsurface.svector3f = rsurface.modelsvector3f;
4722         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
4723         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
4724         rsurface.tvector3f = rsurface.modeltvector3f;
4725         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
4726         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
4727         rsurface.normal3f  = rsurface.modelnormal3f;
4728         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
4729         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
4730         // if vertices are deformed (sprite flares and things in maps, possibly
4731         // water waves, bulges and other deformations), generate them into
4732         // rsurface.deform* arrays from whatever the rsurface.* arrays point to
4733         // (may be static model data or generated data for an animated model, or
4734         //  the previous deform pass)
4735         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
4736         {
4737                 switch (deform->deform)
4738                 {
4739                 default:
4740                 case Q3DEFORM_PROJECTIONSHADOW:
4741                 case Q3DEFORM_TEXT0:
4742                 case Q3DEFORM_TEXT1:
4743                 case Q3DEFORM_TEXT2:
4744                 case Q3DEFORM_TEXT3:
4745                 case Q3DEFORM_TEXT4:
4746                 case Q3DEFORM_TEXT5:
4747                 case Q3DEFORM_TEXT6:
4748                 case Q3DEFORM_TEXT7:
4749                 case Q3DEFORM_NONE:
4750                         break;
4751                 case Q3DEFORM_AUTOSPRITE:
4752                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
4753                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
4754                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
4755                         VectorNormalize(newforward);
4756                         VectorNormalize(newright);
4757                         VectorNormalize(newup);
4758                         // make deformed versions of only the model vertices used by the specified surfaces
4759                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4760                         {
4761                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4762                                 // a single autosprite surface can contain multiple sprites...
4763                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
4764                                 {
4765                                         VectorClear(center);
4766                                         for (i = 0;i < 4;i++)
4767                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
4768                                         VectorScale(center, 0.25f, center);
4769                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, forward);
4770                                         VectorCopy((rsurface.svector3f + 3 * surface->num_firstvertex) + j*3, right);
4771                                         VectorCopy((rsurface.tvector3f + 3 * surface->num_firstvertex) + j*3, up);
4772                                         for (i = 0;i < 4;i++)
4773                                         {
4774                                                 VectorSubtract((rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i)*3, center, v);
4775                                                 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
4776                                         }
4777                                 }
4778                                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformednormal3f, r_smoothnormals_areaweighting.integer);
4779                                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modeltexcoordtexture2f, rsurface.array_deformednormal3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformedsvector3f, rsurface.array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
4780                         }
4781                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4782                         rsurface.vertex3f_bufferobject = 0;
4783                         rsurface.vertex3f_bufferoffset = 0;
4784                         rsurface.svector3f = rsurface.array_deformedsvector3f;
4785                         rsurface.svector3f_bufferobject = 0;
4786                         rsurface.svector3f_bufferoffset = 0;
4787                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
4788                         rsurface.tvector3f_bufferobject = 0;
4789                         rsurface.tvector3f_bufferoffset = 0;
4790                         rsurface.normal3f = rsurface.array_deformednormal3f;
4791                         rsurface.normal3f_bufferobject = 0;
4792                         rsurface.normal3f_bufferoffset = 0;
4793                         break;
4794                 case Q3DEFORM_AUTOSPRITE2:
4795                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
4796                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
4797                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
4798                         VectorNormalize(newforward);
4799                         VectorNormalize(newright);
4800                         VectorNormalize(newup);
4801                         // make deformed versions of only the model vertices used by the specified surfaces
4802                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4803                         {
4804                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4805                                 const float *v1, *v2;
4806                                 vec3_t start, end;
4807                                 float f, l;
4808                                 struct
4809                                 {
4810                                         float length2;
4811                                         const float *v1;
4812                                         const float *v2;
4813                                 }
4814                                 shortest[2];
4815                                 memset(shortest, 0, sizeof(shortest));
4816                                 // a single autosprite surface can contain multiple sprites...
4817                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
4818                                 {
4819                                         VectorClear(center);
4820                                         for (i = 0;i < 4;i++)
4821                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
4822                                         VectorScale(center, 0.25f, center);
4823                                         // find the two shortest edges, then use them to define the
4824                                         // axis vectors for rotating around the central axis
4825                                         for (i = 0;i < 6;i++)
4826                                         {
4827                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][0]);
4828                                                 v2 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][1]);
4829 #if 0
4830                                                 Debug_PolygonBegin(NULL, 0);
4831                                                 Debug_PolygonVertex(v1[0], v1[1], v1[2], 0, 0, 1, 0, 0, 1);
4832                                                 Debug_PolygonVertex((v1[0] + v2[0]) * 0.5f + rsurface.normal3f[3 * (surface->num_firstvertex + j)+0] * 4, (v1[1] + v2[1]) * 0.5f + rsurface.normal3f[3 * (surface->num_firstvertex + j)+1], (v1[2] + v2[2]) * 0.5f + rsurface.normal3f[3 * (surface->num_firstvertex + j)+2], 0, 0, 1, 1, 0, 1);
4833                                                 Debug_PolygonVertex(v2[0], v2[1], v2[2], 0, 0, 1, 0, 0, 1);
4834                                                 Debug_PolygonEnd();
4835 #endif
4836                                                 l = VectorDistance2(v1, v2);
4837                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
4838                                                 if (v1[2] != v2[2])
4839                                                         l += (1.0f / 1024.0f);
4840                                                 if (shortest[0].length2 > l || i == 0)
4841                                                 {
4842                                                         shortest[1] = shortest[0];
4843                                                         shortest[0].length2 = l;
4844                                                         shortest[0].v1 = v1;
4845                                                         shortest[0].v2 = v2;
4846                                                 }
4847                                                 else if (shortest[1].length2 > l || i == 1)
4848                                                 {
4849                                                         shortest[1].length2 = l;
4850                                                         shortest[1].v1 = v1;
4851                                                         shortest[1].v2 = v2;
4852                                                 }
4853                                         }
4854                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
4855                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
4856 #if 0
4857                                         Debug_PolygonBegin(NULL, 0);
4858                                         Debug_PolygonVertex(start[0], start[1], start[2], 0, 0, 1, 1, 0, 1);
4859                                         Debug_PolygonVertex(center[0] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+0] * 4, center[1] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+1] * 4, center[2] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+2] * 4, 0, 0, 0, 1, 0, 1);
4860                                         Debug_PolygonVertex(end[0], end[1], end[2], 0, 0, 0, 1, 1, 1);
4861                                         Debug_PolygonEnd();
4862 #endif
4863                                         // this calculates the right vector from the shortest edge
4864                                         // and the up vector from the edge midpoints
4865                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
4866                                         VectorNormalize(right);
4867                                         VectorSubtract(end, start, up);
4868                                         VectorNormalize(up);
4869                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
4870                                         //VectorSubtract(rsurface.modelorg, center, forward);
4871                                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
4872                                         VectorNegate(forward, forward);
4873                                         VectorReflect(forward, 0, up, forward);
4874                                         VectorNormalize(forward);
4875                                         CrossProduct(up, forward, newright);
4876                                         VectorNormalize(newright);
4877 #if 0
4878                                         Debug_PolygonBegin(NULL, 0);
4879                                         Debug_PolygonVertex(center[0] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+0] * 8, center[1] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+1] * 8, center[2] + rsurface.normal3f[3 * (surface->num_firstvertex + j)+2] * 8, 0, 0, 1, 0, 0, 1);
4880                                         Debug_PolygonVertex(center[0] + right[0] * 8, center[1] + right[1] * 8, center[2] + right[2] * 8, 0, 0, 0, 1, 0, 1);
4881                                         Debug_PolygonVertex(center[0] + up   [0] * 8, center[1] + up   [1] * 8, center[2] + up   [2] * 8, 0, 0, 0, 0, 1, 1);
4882                                         Debug_PolygonEnd();
4883 #endif
4884 #if 0
4885                                         Debug_PolygonBegin(NULL, 0);
4886                                         Debug_PolygonVertex(center[0] + forward [0] * 8, center[1] + forward [1] * 8, center[2] + forward [2] * 8, 0, 0, 1, 0, 0, 1);
4887                                         Debug_PolygonVertex(center[0] + newright[0] * 8, center[1] + newright[1] * 8, center[2] + newright[2] * 8, 0, 0, 0, 1, 0, 1);
4888                                         Debug_PolygonVertex(center[0] + up      [0] * 8, center[1] + up      [1] * 8, center[2] + up      [2] * 8, 0, 0, 0, 0, 1, 1);
4889                                         Debug_PolygonEnd();
4890 #endif
4891                                         // rotate the quad around the up axis vector, this is made
4892                                         // especially easy by the fact we know the quad is flat,
4893                                         // so we only have to subtract the center position and
4894                                         // measure distance along the right vector, and then
4895                                         // multiply that by the newright vector and add back the
4896                                         // center position
4897                                         // we also need to subtract the old position to undo the
4898                                         // displacement from the center, which we do with a
4899                                         // DotProduct, the subtraction/addition of center is also
4900                                         // optimized into DotProducts here
4901                                         l = DotProduct(right, center);
4902                                         for (i = 0;i < 4;i++)
4903                                         {
4904                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + j + i);
4905                                                 f = DotProduct(right, v1) - l;
4906                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
4907                                         }
4908                                 }
4909                                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformednormal3f, r_smoothnormals_areaweighting.integer);
4910                                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modeltexcoordtexture2f, rsurface.array_deformednormal3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformedsvector3f, rsurface.array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
4911                         }
4912                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4913                         rsurface.vertex3f_bufferobject = 0;
4914                         rsurface.vertex3f_bufferoffset = 0;
4915                         rsurface.svector3f = rsurface.array_deformedsvector3f;
4916                         rsurface.svector3f_bufferobject = 0;
4917                         rsurface.svector3f_bufferoffset = 0;
4918                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
4919                         rsurface.tvector3f_bufferobject = 0;
4920                         rsurface.tvector3f_bufferoffset = 0;
4921                         rsurface.normal3f = rsurface.array_deformednormal3f;
4922                         rsurface.normal3f_bufferobject = 0;
4923                         rsurface.normal3f_bufferoffset = 0;
4924                         break;
4925                 case Q3DEFORM_NORMAL:
4926                         // deform the normals to make reflections wavey
4927                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4928                         {
4929                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4930                                 for (j = 0;j < surface->num_vertices;j++)
4931                                 {
4932                                         float vertex[3];
4933                                         float *normal = (rsurface.array_deformednormal3f  + 3 * surface->num_firstvertex) + j*3;
4934                                         VectorScale((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, 0.98f, vertex);
4935                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, normal);
4936                                         normal[0] += deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
4937                                         normal[1] += deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
4938                                         normal[2] += deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
4939                                         VectorNormalize(normal);
4940                                 }
4941                                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface.vertex3f, rsurface.modeltexcoordtexture2f, rsurface.array_deformednormal3f, rsurface.modelelement3i + surface->num_firsttriangle * 3, rsurface.array_deformedsvector3f, rsurface.array_deformedtvector3f, r_smoothnormals_areaweighting.integer);
4942                         }
4943                         rsurface.svector3f = rsurface.array_deformedsvector3f;
4944                         rsurface.svector3f_bufferobject = 0;
4945                         rsurface.svector3f_bufferoffset = 0;
4946                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
4947                         rsurface.tvector3f_bufferobject = 0;
4948                         rsurface.tvector3f_bufferoffset = 0;
4949                         rsurface.normal3f = rsurface.array_deformednormal3f;
4950                         rsurface.normal3f_bufferobject = 0;
4951                         rsurface.normal3f_bufferoffset = 0;
4952                         break;
4953                 case Q3DEFORM_WAVE:
4954                         // deform vertex array to make wavey water and flags and such
4955                         waveparms[0] = deform->waveparms[0];
4956                         waveparms[1] = deform->waveparms[1];
4957                         waveparms[2] = deform->waveparms[2];
4958                         waveparms[3] = deform->waveparms[3];
4959                         // this is how a divisor of vertex influence on deformation
4960                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
4961                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
4962                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4963                         {
4964                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4965                                 for (j = 0;j < surface->num_vertices;j++)
4966                                 {
4967                                         float *vertex = (rsurface.array_deformedvertex3f  + 3 * surface->num_firstvertex) + j*3;
4968                                         VectorCopy((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, vertex);
4969                                         // if the wavefunc depends on time, evaluate it per-vertex
4970                                         if (waveparms[3])
4971                                         {
4972                                                 waveparms[2] = deform->waveparms[2] + (vertex[0] + vertex[1] + vertex[2]) * animpos;
4973                                                 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
4974                                         }
4975                                         VectorMA(vertex, scale, (rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, vertex);
4976                                 }
4977                         }
4978                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4979                         rsurface.vertex3f_bufferobject = 0;
4980                         rsurface.vertex3f_bufferoffset = 0;
4981                         break;
4982                 case Q3DEFORM_BULGE:
4983                         // deform vertex array to make the surface have moving bulges
4984                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
4985                         {
4986                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
4987                                 for (j = 0;j < surface->num_vertices;j++)
4988                                 {
4989                                         scale = sin((rsurface.modeltexcoordtexture2f[2 * (surface->num_firstvertex + j)] * deform->parms[0] + r_refdef.scene.time * deform->parms[2])) * deform->parms[1];
4990                                         VectorMA(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), scale, rsurface.normal3f + 3 * (surface->num_firstvertex + j), rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
4991                                 }
4992                         }
4993                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
4994                         rsurface.vertex3f_bufferobject = 0;
4995                         rsurface.vertex3f_bufferoffset = 0;
4996                         break;
4997                 case Q3DEFORM_MOVE:
4998                         // deform vertex array
4999                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
5000                         VectorScale(deform->parms, scale, waveparms);
5001                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5002                         {
5003                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5004                                 for (j = 0;j < surface->num_vertices;j++)
5005                                         VectorAdd(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), waveparms, rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
5006                         }
5007                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
5008                         rsurface.vertex3f_bufferobject = 0;
5009                         rsurface.vertex3f_bufferoffset = 0;
5010                         break;
5011                 }
5012         }
5013         // generate texcoords based on the chosen texcoord source
5014         switch(rsurface.texture->tcgen.tcgen)
5015         {
5016         default:
5017         case Q3TCGEN_TEXTURE:
5018                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordtexture2f;
5019                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordtexture2f_bufferobject;
5020                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
5021                 break;
5022         case Q3TCGEN_LIGHTMAP:
5023                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordlightmap2f;
5024                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordlightmap2f_bufferobject;
5025                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordlightmap2f_bufferoffset;
5026                 break;
5027         case Q3TCGEN_VECTOR:
5028                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5029                 {
5030                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5031                         for (j = 0, v1 = rsurface.modelvertex3f + 3 * surface->num_firstvertex, out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;j < surface->num_vertices;j++, v1 += 3, out_tc += 2)
5032                         {
5033                                 out_tc[0] = DotProduct(v1, rsurface.texture->tcgen.parms);
5034                                 out_tc[1] = DotProduct(v1, rsurface.texture->tcgen.parms + 3);
5035                         }
5036                 }
5037                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
5038                 rsurface.texcoordtexture2f_bufferobject  = 0;
5039                 rsurface.texcoordtexture2f_bufferoffset  = 0;
5040                 break;
5041         case Q3TCGEN_ENVIRONMENT:
5042                 // make environment reflections using a spheremap
5043                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5044                 {
5045                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5046                         const float *vertex = rsurface.modelvertex3f + 3 * surface->num_firstvertex;
5047                         const float *normal = rsurface.modelnormal3f + 3 * surface->num_firstvertex;
5048                         float *out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;
5049                         for (j = 0;j < surface->num_vertices;j++, vertex += 3, normal += 3, out_tc += 2)
5050                         {
5051                                 float l, d, eyedir[3];
5052                                 VectorSubtract(rsurface.modelorg, vertex, eyedir);
5053                                 l = 0.5f / VectorLength(eyedir);
5054                                 d = DotProduct(normal, eyedir)*2;
5055                                 out_tc[0] = 0.5f + (normal[1]*d - eyedir[1])*l;
5056                                 out_tc[1] = 0.5f - (normal[2]*d - eyedir[2])*l;
5057                         }
5058                 }
5059                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
5060                 rsurface.texcoordtexture2f_bufferobject  = 0;
5061                 rsurface.texcoordtexture2f_bufferoffset  = 0;
5062                 break;
5063         }
5064         // the only tcmod that needs software vertex processing is turbulent, so
5065         // check for it here and apply the changes if needed
5066         // and we only support that as the first one
5067         // (handling a mixture of turbulent and other tcmods would be problematic
5068         //  without punting it entirely to a software path)
5069         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
5070         {
5071                 amplitude = rsurface.texture->tcmods[0].parms[1];
5072                 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
5073                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5074                 {
5075                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5076                         for (j = 0, v1 = rsurface.modelvertex3f + 3 * surface->num_firstvertex, in_tc = rsurface.texcoordtexture2f + 2 * surface->num_firstvertex, out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;j < surface->num_vertices;j++, v1 += 3, in_tc += 2, out_tc += 2)
5077                         {
5078                                 out_tc[0] = in_tc[0] + amplitude * sin(((v1[0] + v1[2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
5079                                 out_tc[1] = in_tc[1] + amplitude * sin(((v1[1]        ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
5080                         }
5081                 }
5082                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
5083                 rsurface.texcoordtexture2f_bufferobject  = 0;
5084                 rsurface.texcoordtexture2f_bufferoffset  = 0;
5085         }
5086         rsurface.texcoordlightmap2f              = rsurface.modeltexcoordlightmap2f;
5087         rsurface.texcoordlightmap2f_bufferobject = rsurface.modeltexcoordlightmap2f_bufferobject;
5088         rsurface.texcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
5089         R_Mesh_VertexPointer(rsurface.vertex3f, rsurface.vertex3f_bufferobject, rsurface.vertex3f_bufferoffset);
5090 }
5091
5092 void RSurf_DrawBatch_Simple(int texturenumsurfaces, msurface_t **texturesurfacelist)
5093 {
5094         int i, j;
5095         const msurface_t *surface = texturesurfacelist[0];
5096         const msurface_t *surface2;
5097         int firstvertex;
5098         int endvertex;
5099         int numvertices;
5100         int numtriangles;
5101         // TODO: lock all array ranges before render, rather than on each surface
5102         if (texturenumsurfaces == 1)
5103         {
5104                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5105                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5106         }
5107         else if (r_batchmode.integer == 2)
5108         {
5109                 #define MAXBATCHTRIANGLES 4096
5110                 int batchtriangles = 0;
5111                 int batchelements[MAXBATCHTRIANGLES*3];
5112                 for (i = 0;i < texturenumsurfaces;i = j)
5113                 {
5114                         surface = texturesurfacelist[i];
5115                         j = i + 1;
5116                         if (surface->num_triangles > MAXBATCHTRIANGLES)
5117                         {
5118                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5119                                 continue;
5120                         }
5121                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
5122                         batchtriangles = surface->num_triangles;
5123                         firstvertex = surface->num_firstvertex;
5124                         endvertex = surface->num_firstvertex + surface->num_vertices;
5125                         for (;j < texturenumsurfaces;j++)
5126                         {
5127                                 surface2 = texturesurfacelist[j];
5128                                 if (batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
5129                                         break;
5130                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
5131                                 batchtriangles += surface2->num_triangles;
5132                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
5133                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
5134                         }
5135                         surface2 = texturesurfacelist[j-1];
5136                         numvertices = endvertex - firstvertex;
5137                         R_Mesh_Draw(firstvertex, numvertices, batchtriangles, batchelements, 0, 0);
5138                 }
5139         }
5140         else if (r_batchmode.integer == 1)
5141         {
5142                 for (i = 0;i < texturenumsurfaces;i = j)
5143                 {
5144                         surface = texturesurfacelist[i];
5145                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
5146                                 if (texturesurfacelist[j] != surface2)
5147                                         break;
5148                         surface2 = texturesurfacelist[j-1];
5149                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
5150                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
5151                         GL_LockArrays(surface->num_firstvertex, numvertices);
5152                         R_Mesh_Draw(surface->num_firstvertex, numvertices, numtriangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5153                 }
5154         }
5155         else
5156         {
5157                 for (i = 0;i < texturenumsurfaces;i++)
5158                 {
5159                         surface = texturesurfacelist[i];
5160                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5161                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5162                 }
5163         }
5164 }
5165
5166 static void RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(int texturenumsurfaces, msurface_t **texturesurfacelist, int lightmaptexunit, int deluxemaptexunit, int refractiontexunit, int reflectiontexunit)
5167 {
5168         int i, planeindex, vertexindex;
5169         float d, bestd;
5170         vec3_t vert;
5171         const float *v;
5172         r_waterstate_waterplane_t *p, *bestp;
5173         msurface_t *surface;
5174         if (r_waterstate.renderingscene)
5175                 return;
5176         for (i = 0;i < texturenumsurfaces;i++)
5177         {
5178                 surface = texturesurfacelist[i];
5179                 if (lightmaptexunit >= 0)
5180                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5181                 if (deluxemaptexunit >= 0)
5182                         R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5183                 // pick the closest matching water plane
5184                 bestd = 0;
5185                 bestp = NULL;
5186                 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
5187                 {
5188                         d = 0;
5189                         for (vertexindex = 0, v = rsurface.modelvertex3f + surface->num_firstvertex * 3;vertexindex < surface->num_vertices;vertexindex++, v += 3)
5190                         {
5191                                 Matrix4x4_Transform(&rsurface.matrix, v, vert);
5192                                 d += fabs(PlaneDiff(vert, &p->plane));
5193                         }
5194                         if (bestd > d || !bestp)
5195                         {
5196                                 bestd = d;
5197                                 bestp = p;
5198                         }
5199                 }
5200                 if (bestp)
5201                 {
5202                         if (refractiontexunit >= 0)
5203                                 R_Mesh_TexBind(refractiontexunit, R_GetTexture(bestp->texture_refraction));
5204                         if (reflectiontexunit >= 0)
5205                                 R_Mesh_TexBind(reflectiontexunit, R_GetTexture(bestp->texture_reflection));
5206                 }
5207                 else
5208                 {
5209                         if (refractiontexunit >= 0)
5210                                 R_Mesh_TexBind(refractiontexunit, R_GetTexture(r_texture_black));
5211                         if (reflectiontexunit >= 0)
5212                                 R_Mesh_TexBind(reflectiontexunit, R_GetTexture(r_texture_black));
5213                 }
5214                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5215                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5216         }
5217 }
5218
5219 static void RSurf_DrawBatch_WithLightmapSwitching(int texturenumsurfaces, msurface_t **texturesurfacelist, int lightmaptexunit, int deluxemaptexunit)
5220 {
5221         int i;
5222         int j;
5223         const msurface_t *surface = texturesurfacelist[0];
5224         const msurface_t *surface2;
5225         int firstvertex;
5226         int endvertex;
5227         int numvertices;
5228         int numtriangles;
5229         // TODO: lock all array ranges before render, rather than on each surface
5230         if (texturenumsurfaces == 1)
5231         {
5232                 R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5233                 if (deluxemaptexunit >= 0)
5234                         R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5235                 GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5236                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5237         }
5238         else if (r_batchmode.integer == 2)
5239         {
5240                 #define MAXBATCHTRIANGLES 4096
5241                 int batchtriangles = 0;
5242                 int batchelements[MAXBATCHTRIANGLES*3];
5243                 for (i = 0;i < texturenumsurfaces;i = j)
5244                 {
5245                         surface = texturesurfacelist[i];
5246                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5247                         if (deluxemaptexunit >= 0)
5248                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5249                         j = i + 1;
5250                         if (surface->num_triangles > MAXBATCHTRIANGLES)
5251                         {
5252                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5253                                 continue;
5254                         }
5255                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
5256                         batchtriangles = surface->num_triangles;
5257                         firstvertex = surface->num_firstvertex;
5258                         endvertex = surface->num_firstvertex + surface->num_vertices;
5259                         for (;j < texturenumsurfaces;j++)
5260                         {
5261                                 surface2 = texturesurfacelist[j];
5262                                 if (surface2->lightmaptexture != surface->lightmaptexture || batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
5263                                         break;
5264                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
5265                                 batchtriangles += surface2->num_triangles;
5266                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
5267                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
5268                         }
5269                         surface2 = texturesurfacelist[j-1];
5270                         numvertices = endvertex - firstvertex;
5271                         R_Mesh_Draw(firstvertex, numvertices, batchtriangles, batchelements, 0, 0);
5272                 }
5273         }
5274         else if (r_batchmode.integer == 1)
5275         {
5276 #if 0
5277                 Con_Printf("%s batch sizes ignoring lightmap:", rsurface.texture->name);
5278                 for (i = 0;i < texturenumsurfaces;i = j)
5279                 {
5280                         surface = texturesurfacelist[i];
5281                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
5282                                 if (texturesurfacelist[j] != surface2)
5283                                         break;
5284                         Con_Printf(" %i", j - i);
5285                 }
5286                 Con_Printf("\n");
5287                 Con_Printf("%s batch sizes honoring lightmap:", rsurface.texture->name);
5288 #endif
5289                 for (i = 0;i < texturenumsurfaces;i = j)
5290                 {
5291                         surface = texturesurfacelist[i];
5292                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5293                         if (deluxemaptexunit >= 0)
5294                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5295                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
5296                                 if (texturesurfacelist[j] != surface2 || texturesurfacelist[j]->lightmaptexture != surface->lightmaptexture)
5297                                         break;
5298 #if 0
5299                         Con_Printf(" %i", j - i);
5300 #endif
5301                         surface2 = texturesurfacelist[j-1];
5302                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
5303                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
5304                         GL_LockArrays(surface->num_firstvertex, numvertices);
5305                         R_Mesh_Draw(surface->num_firstvertex, numvertices, numtriangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5306                 }
5307 #if 0
5308                 Con_Printf("\n");
5309 #endif
5310         }
5311         else
5312         {
5313                 for (i = 0;i < texturenumsurfaces;i++)
5314                 {
5315                         surface = texturesurfacelist[i];
5316                         R_Mesh_TexBind(lightmaptexunit, R_GetTexture(surface->lightmaptexture));
5317                         if (deluxemaptexunit >= 0)
5318                                 R_Mesh_TexBind(deluxemaptexunit, R_GetTexture(surface->deluxemaptexture));
5319                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5320                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5321                 }
5322         }
5323 }
5324
5325 static void RSurf_DrawBatch_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
5326 {
5327         int j;
5328         int texturesurfaceindex;
5329         if (r_showsurfaces.integer == 2)
5330         {
5331                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5332                 {
5333                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5334                         for (j = 0;j < surface->num_triangles;j++)
5335                         {
5336                                 float f = ((j + surface->num_firsttriangle) & 31) * (1.0f / 31.0f) * r_refdef.view.colorscale;
5337                                 GL_Color(f, f, f, 1);
5338                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, 1, (rsurface.modelelement3i + 3 * (j + surface->num_firsttriangle)), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * (j + surface->num_firsttriangle)));
5339                         }
5340                 }
5341         }
5342         else
5343         {
5344                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5345                 {
5346                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5347                         int k = (int)(((size_t)surface) / sizeof(msurface_t));
5348                         GL_Color((k & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, ((k >> 4) & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, ((k >> 8) & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, 1);
5349                         GL_LockArrays(surface->num_firstvertex, surface->num_vertices);
5350                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (rsurface.modelelement3i + 3 * surface->num_firsttriangle), rsurface.modelelement3i_bufferobject, (sizeof(int[3]) * surface->num_firsttriangle));
5351                 }
5352         }
5353 }
5354
5355 static void RSurf_DrawBatch_GL11_ApplyFog(int texturenumsurfaces, msurface_t **texturesurfacelist)
5356 {
5357         int texturesurfaceindex;
5358         int i;
5359         float f;
5360         float *v, *c, *c2;
5361         if (rsurface.lightmapcolor4f)
5362         {
5363                 // generate color arrays for the surfaces in this list
5364                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5365                 {
5366                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5367                         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)
5368                         {
5369                                 f = FogPoint_Model(v);
5370                                 c2[0] = c[0] * f;
5371                                 c2[1] = c[1] * f;
5372                                 c2[2] = c[2] * f;
5373                                 c2[3] = c[3];
5374                         }
5375                 }
5376         }
5377         else
5378         {
5379                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5380                 {
5381                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5382                         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)
5383                         {
5384                                 f = FogPoint_Model(v);
5385                                 c2[0] = f;
5386                                 c2[1] = f;
5387                                 c2[2] = f;
5388                                 c2[3] = 1;
5389                         }
5390                 }
5391         }
5392         rsurface.lightmapcolor4f = rsurface.array_color4f;
5393         rsurface.lightmapcolor4f_bufferobject = 0;
5394         rsurface.lightmapcolor4f_bufferoffset = 0;
5395 }
5396
5397 static void RSurf_DrawBatch_GL11_ApplyColor(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a)
5398 {
5399         int texturesurfaceindex;
5400         int i;
5401         float *c, *c2;
5402         if (!rsurface.lightmapcolor4f)
5403                 return;
5404         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5405         {
5406                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5407                 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)
5408                 {
5409                         c2[0] = c[0] * r;
5410                         c2[1] = c[1] * g;
5411                         c2[2] = c[2] * b;
5412                         c2[3] = c[3] * a;
5413                 }
5414         }
5415         rsurface.lightmapcolor4f = rsurface.array_color4f;
5416         rsurface.lightmapcolor4f_bufferobject = 0;
5417         rsurface.lightmapcolor4f_bufferoffset = 0;
5418 }
5419
5420 static void RSurf_DrawBatch_GL11_Lightmap(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5421 {
5422         // TODO: optimize
5423         rsurface.lightmapcolor4f = NULL;
5424         rsurface.lightmapcolor4f_bufferobject = 0;
5425         rsurface.lightmapcolor4f_bufferoffset = 0;
5426         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5427         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5428         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5429         GL_Color(r, g, b, a);
5430         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist, 0, -1);
5431 }
5432
5433 static void RSurf_DrawBatch_GL11_Unlit(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5434 {
5435         // TODO: optimize applyfog && applycolor case
5436         // just apply fog if necessary, and tint the fog color array if necessary
5437         rsurface.lightmapcolor4f = NULL;
5438         rsurface.lightmapcolor4f_bufferobject = 0;
5439         rsurface.lightmapcolor4f_bufferoffset = 0;
5440         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5441         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5442         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5443         GL_Color(r, g, b, a);
5444         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5445 }
5446
5447 static void RSurf_DrawBatch_GL11_VertexColor(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5448 {
5449         int texturesurfaceindex;
5450         int i;
5451         float *c;
5452         // TODO: optimize
5453         if (texturesurfacelist[0]->lightmapinfo && texturesurfacelist[0]->lightmapinfo->stainsamples)
5454         {
5455                 // generate color arrays for the surfaces in this list
5456                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5457                 {
5458                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5459                         for (i = 0, c = rsurface.array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
5460                         {
5461                                 if (surface->lightmapinfo->samples)
5462                                 {
5463                                         const unsigned char *lm = surface->lightmapinfo->samples + (rsurface.modellightmapoffsets + surface->num_firstvertex)[i];
5464                                         float scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]] * (1.0f / 32768.0f);
5465                                         VectorScale(lm, scale, c);
5466                                         if (surface->lightmapinfo->styles[1] != 255)
5467                                         {
5468                                                 int size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
5469                                                 lm += size3;
5470                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]] * (1.0f / 32768.0f);
5471                                                 VectorMA(c, scale, lm, c);
5472                                                 if (surface->lightmapinfo->styles[2] != 255)
5473                                                 {
5474                                                         lm += size3;
5475                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]] * (1.0f / 32768.0f);
5476                                                         VectorMA(c, scale, lm, c);
5477                                                         if (surface->lightmapinfo->styles[3] != 255)
5478                                                         {
5479                                                                 lm += size3;
5480                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]] * (1.0f / 32768.0f);
5481                                                                 VectorMA(c, scale, lm, c);
5482                                                         }
5483                                                 }
5484                                         }
5485                                 }
5486                                 else
5487                                         VectorClear(c);
5488                                 c[3] = 1;
5489                         }
5490                 }
5491                 rsurface.lightmapcolor4f = rsurface.array_color4f;
5492                 rsurface.lightmapcolor4f_bufferobject = 0;
5493                 rsurface.lightmapcolor4f_bufferoffset = 0;
5494         }
5495         else
5496         {
5497                 rsurface.lightmapcolor4f = rsurface.modellightmapcolor4f;
5498                 rsurface.lightmapcolor4f_bufferobject = rsurface.modellightmapcolor4f_bufferobject;
5499                 rsurface.lightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
5500         }
5501         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5502         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5503         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5504         GL_Color(r, g, b, a);
5505         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5506 }
5507
5508 static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
5509 {
5510         int texturesurfaceindex;
5511         int i;
5512         float f;
5513         float *v, *c, *c2;
5514         vec3_t ambientcolor;
5515         vec3_t diffusecolor;
5516         vec3_t lightdir;
5517         // TODO: optimize
5518         // model lighting
5519         VectorCopy(rsurface.modellight_lightdir, lightdir);
5520         f = 0.5f * r_refdef.lightmapintensity;
5521         ambientcolor[0] = rsurface.modellight_ambient[0] * r * f;
5522         ambientcolor[1] = rsurface.modellight_ambient[1] * g * f;
5523         ambientcolor[2] = rsurface.modellight_ambient[2] * b * f;
5524         diffusecolor[0] = rsurface.modellight_diffuse[0] * r * f;
5525         diffusecolor[1] = rsurface.modellight_diffuse[1] * g * f;
5526         diffusecolor[2] = rsurface.modellight_diffuse[2] * b * f;
5527         if (VectorLength2(diffusecolor) > 0)
5528         {
5529                 // generate color arrays for the surfaces in this list
5530                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5531                 {
5532                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5533                         int numverts = surface->num_vertices;
5534                         v = rsurface.vertex3f + 3 * surface->num_firstvertex;
5535                         c2 = rsurface.normal3f + 3 * surface->num_firstvertex;
5536                         c = rsurface.array_color4f + 4 * surface->num_firstvertex;
5537                         // q3-style directional shading
5538                         for (i = 0;i < numverts;i++, v += 3, c2 += 3, c += 4)
5539                         {
5540                                 if ((f = DotProduct(c2, lightdir)) > 0)
5541                                         VectorMA(ambientcolor, f, diffusecolor, c);
5542                                 else
5543                                         VectorCopy(ambientcolor, c);
5544                                 c[3] = a;
5545                         }
5546                 }
5547                 r = 1;
5548                 g = 1;
5549                 b = 1;
5550                 a = 1;
5551                 applycolor = false;
5552                 rsurface.lightmapcolor4f = rsurface.array_color4f;
5553                 rsurface.lightmapcolor4f_bufferobject = 0;
5554                 rsurface.lightmapcolor4f_bufferoffset = 0;
5555         }
5556         else
5557         {
5558                 r = ambientcolor[0];
5559                 g = ambientcolor[1];
5560                 b = ambientcolor[2];
5561                 rsurface.lightmapcolor4f = NULL;
5562                 rsurface.lightmapcolor4f_bufferobject = 0;
5563                 rsurface.lightmapcolor4f_bufferoffset = 0;
5564         }
5565         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
5566         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
5567         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
5568         GL_Color(r, g, b, a);
5569         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5570 }
5571
5572 void RSurf_SetupDepthAndCulling(void)
5573 {
5574         // submodels are biased to avoid z-fighting with world surfaces that they
5575         // may be exactly overlapping (avoids z-fighting artifacts on certain
5576         // doors and things in Quake maps)
5577         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
5578         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
5579         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
5580         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
5581 }
5582
5583 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, msurface_t **texturesurfacelist)
5584 {
5585         RSurf_SetupDepthAndCulling();
5586         if (rsurface.mode != RSURFMODE_SHOWSURFACES)
5587         {
5588                 rsurface.mode = RSURFMODE_SHOWSURFACES;
5589                 GL_DepthMask(true);
5590                 GL_BlendFunc(GL_ONE, GL_ZERO);
5591                 R_Mesh_ColorPointer(NULL, 0, 0);
5592                 R_Mesh_ResetTextureState();
5593         }
5594         RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
5595         RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
5596 }
5597
5598 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, msurface_t **texturesurfacelist)
5599 {
5600         // transparent sky would be ridiculous
5601         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
5602                 return;
5603         if (rsurface.mode != RSURFMODE_SKY)
5604         {
5605                 if (rsurface.mode == RSURFMODE_GLSL)
5606                 {
5607                         qglUseProgramObjectARB(0);CHECKGLERROR
5608                 }
5609                 rsurface.mode = RSURFMODE_SKY;
5610         }
5611         if (skyrendernow)
5612         {
5613                 skyrendernow = false;
5614                 // we have to force off the water clipping plane while rendering sky
5615                 R_SetupView(false);
5616                 R_Sky();
5617                 R_SetupView(true);
5618                 // restore entity matrix
5619                 R_Mesh_Matrix(&rsurface.matrix);
5620         }
5621         RSurf_SetupDepthAndCulling();
5622         GL_DepthMask(true);
5623         // LordHavoc: HalfLife maps have freaky skypolys so don't use
5624         // skymasking on them, and Quake3 never did sky masking (unlike
5625         // software Quake and software Quake2), so disable the sky masking
5626         // in Quake3 maps as it causes problems with q3map2 sky tricks,
5627         // and skymasking also looks very bad when noclipping outside the
5628         // level, so don't use it then either.
5629         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
5630         {
5631                 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
5632                 R_Mesh_ColorPointer(NULL, 0, 0);
5633                 R_Mesh_ResetTextureState();
5634                 if (skyrendermasked)
5635                 {
5636                         // depth-only (masking)
5637                         GL_ColorMask(0,0,0,0);
5638                         // just to make sure that braindead drivers don't draw
5639                         // anything despite that colormask...
5640                         GL_BlendFunc(GL_ZERO, GL_ONE);
5641                 }
5642                 else
5643                 {
5644                         // fog sky
5645                         GL_BlendFunc(GL_ONE, GL_ZERO);
5646                 }
5647                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
5648                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5649                 if (skyrendermasked)
5650                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
5651         }
5652 }
5653
5654 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, msurface_t **texturesurfacelist)
5655 {
5656         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION)))
5657                 return;
5658
5659         if (rsurface.mode != RSURFMODE_GLSL)
5660         {
5661                 rsurface.mode = RSURFMODE_GLSL;
5662                 R_Mesh_ResetTextureState();
5663                 GL_Color(1, 1, 1, 1);
5664         }
5665
5666         R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix);
5667         R_Mesh_TexBind(GL20TU_NORMAL, R_GetTexture(rsurface.texture->currentskinframe->nmap));
5668         R_Mesh_TexBind(GL20TU_COLOR, R_GetTexture(rsurface.texture->basetexture));
5669         R_Mesh_TexBind(GL20TU_GLOSS, R_GetTexture(rsurface.texture->glosstexture));
5670         R_Mesh_TexBind(GL20TU_GLOW, R_GetTexture(rsurface.texture->currentskinframe->glow));
5671         if (rsurface.texture->backgroundcurrentskinframe)
5672         {
5673                 R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->nmap));
5674                 R_Mesh_TexBind(GL20TU_SECONDARY_COLOR, R_GetTexture(rsurface.texture->backgroundbasetexture));
5675                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS, R_GetTexture(rsurface.texture->backgroundglosstexture));
5676                 R_Mesh_TexBind(GL20TU_SECONDARY_GLOW, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->glow));
5677         }
5678         R_Mesh_TexBind(GL20TU_PANTS, R_GetTexture(rsurface.texture->currentskinframe->pants));
5679         R_Mesh_TexBind(GL20TU_SHIRT, R_GetTexture(rsurface.texture->currentskinframe->shirt));
5680         R_Mesh_TexBind(GL20TU_FOGMASK, R_GetTexture(r_texture_fogattenuation));
5681         if ((rsurface.uselightmaptexture || (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND))
5682                 R_Mesh_ColorPointer(NULL, 0, 0);
5683         else
5684                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5685
5686         if (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
5687         {
5688                 // render background
5689                 GL_BlendFunc(GL_ONE, GL_ZERO);
5690                 GL_DepthMask(true);
5691                 GL_AlphaTest(false);
5692
5693                 GL_Color(1, 1, 1, 1);
5694                 R_Mesh_ColorPointer(NULL, 0, 0);
5695
5696                 R_SetupSurfaceShader(vec3_origin, rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND);
5697                 if (r_glsl_permutation)
5698                 {
5699                         RSurf_PrepareVerticesForBatch(true, true, texturenumsurfaces, texturesurfacelist);
5700                         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
5701                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
5702                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
5703                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
5704                         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5705                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist, -1, -1, r_glsl_permutation->loc_Texture_Refraction >= 0 ? GL20TU_REFRACTION : -1, r_glsl_permutation->loc_Texture_Reflection >= 0 ? GL20TU_REFLECTION : -1);
5706                 }
5707
5708                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5709                 GL_DepthMask(false);
5710                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5711                 if ((rsurface.uselightmaptexture || (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND))
5712                         R_Mesh_ColorPointer(NULL, 0, 0);
5713                 else
5714                         R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5715                 R_Mesh_TexBind(GL20TU_REFRACTION, R_GetTexture(r_texture_white)); // changed per surface
5716                 R_Mesh_TexBind(GL20TU_REFLECTION, R_GetTexture(r_texture_white)); // changed per surface
5717         }
5718
5719         R_SetupSurfaceShader(vec3_origin, rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
5720         if (!r_glsl_permutation)
5721                 return;
5722
5723         RSurf_PrepareVerticesForBatch(r_glsl_permutation->loc_Texture_Normal >= 0 || r_glsl_permutation->loc_LightDir >= 0, r_glsl_permutation->loc_Texture_Normal >= 0, texturenumsurfaces, texturesurfacelist);
5724         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
5725         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
5726         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
5727         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
5728         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5729
5730         if (r_glsl_permutation->loc_Texture_Refraction >= 0)
5731         {
5732                 GL_BlendFunc(GL_ONE, GL_ZERO);
5733                 GL_DepthMask(true);
5734                 GL_AlphaTest(false);
5735         }
5736
5737         if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
5738         {
5739                 if (r_glsl_permutation->loc_Texture_Refraction >= 0 || r_glsl_permutation->loc_Texture_Reflection >= 0)
5740                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist, GL20TU_LIGHTMAP, r_glsl_permutation->loc_Texture_Deluxemap >= 0 ? GL20TU_DELUXEMAP : -1, r_glsl_permutation->loc_Texture_Refraction >= 0 ? GL20TU_REFRACTION : -1, r_glsl_permutation->loc_Texture_Reflection >= 0 ? GL20TU_REFLECTION : -1);
5741                 else
5742                         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist, GL20TU_LIGHTMAP, r_glsl_permutation->loc_Texture_Deluxemap >= 0 ? GL20TU_DELUXEMAP : -1);
5743         }
5744         else
5745         {
5746                 if (r_glsl_permutation->loc_Texture_Refraction >= 0 || r_glsl_permutation->loc_Texture_Reflection >= 0)
5747                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist, -1, -1, r_glsl_permutation->loc_Texture_Refraction >= 0 ? GL20TU_REFRACTION : -1, r_glsl_permutation->loc_Texture_Reflection >= 0 ? GL20TU_REFLECTION : -1);
5748                 else
5749                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5750         }
5751 }
5752
5753 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, msurface_t **texturesurfacelist)
5754 {
5755         // OpenGL 1.3 path - anything not completely ancient
5756         int texturesurfaceindex;
5757         qboolean applycolor;
5758         qboolean applyfog;
5759         rmeshstate_t m;
5760         int layerindex;
5761         const texturelayer_t *layer;
5762         if (rsurface.mode != RSURFMODE_MULTIPASS)
5763                 rsurface.mode = RSURFMODE_MULTIPASS;
5764         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
5765
5766         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
5767         {
5768                 vec4_t layercolor;
5769                 int layertexrgbscale;
5770                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5771                 {
5772                         if (layerindex == 0)
5773                                 GL_AlphaTest(true);
5774                         else
5775                         {
5776                                 GL_AlphaTest(false);
5777                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
5778                         }
5779                 }
5780                 GL_DepthMask(layer->depthmask);
5781                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
5782                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
5783                 {
5784                         layertexrgbscale = 4;
5785                         VectorScale(layer->color, 0.25f, layercolor);
5786                 }
5787                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
5788                 {
5789                         layertexrgbscale = 2;
5790                         VectorScale(layer->color, 0.5f, layercolor);
5791                 }
5792                 else
5793                 {
5794                         layertexrgbscale = 1;
5795                         VectorScale(layer->color, 1.0f, layercolor);
5796                 }
5797                 layercolor[3] = layer->color[3];
5798                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
5799                 R_Mesh_ColorPointer(NULL, 0, 0);
5800                 applyfog = (layer->flags & TEXTURELAYERFLAG_FOGDARKEN) != 0;
5801                 switch (layer->type)
5802                 {
5803                 case TEXTURELAYERTYPE_LITTEXTURE:
5804                         memset(&m, 0, sizeof(m));
5805                         m.tex[0] = R_GetTexture(r_texture_white);
5806                         m.pointer_texcoord[0] = rsurface.modeltexcoordlightmap2f;
5807                         m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
5808                         m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
5809                         m.tex[1] = R_GetTexture(layer->texture);
5810                         m.texmatrix[1] = layer->texmatrix;
5811                         m.texrgbscale[1] = layertexrgbscale;
5812                         m.pointer_texcoord[1] = rsurface.texcoordtexture2f;
5813                         m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject;
5814                         m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset;
5815                         R_Mesh_TextureState(&m);
5816                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5817                                 RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5818                         else if (rsurface.uselightmaptexture)
5819                                 RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5820                         else
5821                                 RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5822                         break;
5823                 case TEXTURELAYERTYPE_TEXTURE:
5824                         memset(&m, 0, sizeof(m));
5825                         m.tex[0] = R_GetTexture(layer->texture);
5826                         m.texmatrix[0] = layer->texmatrix;
5827                         m.texrgbscale[0] = layertexrgbscale;
5828                         m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5829                         m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5830                         m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5831                         R_Mesh_TextureState(&m);
5832                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
5833                         break;
5834                 case TEXTURELAYERTYPE_FOG:
5835                         memset(&m, 0, sizeof(m));
5836                         m.texrgbscale[0] = layertexrgbscale;
5837                         if (layer->texture)
5838                         {
5839                                 m.tex[0] = R_GetTexture(layer->texture);
5840                                 m.texmatrix[0] = layer->texmatrix;
5841                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5842                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5843                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5844                         }
5845                         R_Mesh_TextureState(&m);
5846                         // generate a color array for the fog pass
5847                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
5848                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5849                         {
5850                                 int i;
5851                                 float f, *v, *c;
5852                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5853                                 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)
5854                                 {
5855                                         f = 1 - FogPoint_Model(v);
5856                                         c[0] = layercolor[0];
5857                                         c[1] = layercolor[1];
5858                                         c[2] = layercolor[2];
5859                                         c[3] = f * layercolor[3];
5860                                 }
5861                         }
5862                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5863                         break;
5864                 default:
5865                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
5866                 }
5867                 GL_LockArrays(0, 0);
5868         }
5869         CHECKGLERROR
5870         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5871         {
5872                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
5873                 GL_AlphaTest(false);
5874         }
5875 }
5876
5877 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, msurface_t **texturesurfacelist)
5878 {
5879         // OpenGL 1.1 - crusty old voodoo path
5880         int texturesurfaceindex;
5881         qboolean applyfog;
5882         rmeshstate_t m;
5883         int layerindex;
5884         const texturelayer_t *layer;
5885         if (rsurface.mode != RSURFMODE_MULTIPASS)
5886                 rsurface.mode = RSURFMODE_MULTIPASS;
5887         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
5888
5889         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
5890         {
5891                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5892                 {
5893                         if (layerindex == 0)
5894                                 GL_AlphaTest(true);
5895                         else
5896                         {
5897                                 GL_AlphaTest(false);
5898                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
5899                         }
5900                 }
5901                 GL_DepthMask(layer->depthmask);
5902                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
5903                 R_Mesh_ColorPointer(NULL, 0, 0);
5904                 applyfog = (layer->flags & TEXTURELAYERFLAG_FOGDARKEN) != 0;
5905                 switch (layer->type)
5906                 {
5907                 case TEXTURELAYERTYPE_LITTEXTURE:
5908                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
5909                         {
5910                                 // two-pass lit texture with 2x rgbscale
5911                                 // first the lightmap pass
5912                                 memset(&m, 0, sizeof(m));
5913                                 m.tex[0] = R_GetTexture(r_texture_white);
5914                                 m.pointer_texcoord[0] = rsurface.modeltexcoordlightmap2f;
5915                                 m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
5916                                 m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
5917                                 R_Mesh_TextureState(&m);
5918                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5919                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
5920                                 else if (rsurface.uselightmaptexture)
5921                                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
5922                                 else
5923                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
5924                                 GL_LockArrays(0, 0);
5925                                 // then apply the texture to it
5926                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
5927                                 memset(&m, 0, sizeof(m));
5928                                 m.tex[0] = R_GetTexture(layer->texture);
5929                                 m.texmatrix[0] = layer->texmatrix;
5930                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5931                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5932                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5933                                 R_Mesh_TextureState(&m);
5934                                 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);
5935                         }
5936                         else
5937                         {
5938                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
5939                                 memset(&m, 0, sizeof(m));
5940                                 m.tex[0] = R_GetTexture(layer->texture);
5941                                 m.texmatrix[0] = layer->texmatrix;
5942                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5943                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5944                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5945                                 R_Mesh_TextureState(&m);
5946                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5947                                         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);
5948                                 else
5949                                         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);
5950                         }
5951                         break;
5952                 case TEXTURELAYERTYPE_TEXTURE:
5953                         // singletexture unlit texture with transparency support
5954                         memset(&m, 0, sizeof(m));
5955                         m.tex[0] = R_GetTexture(layer->texture);
5956                         m.texmatrix[0] = layer->texmatrix;
5957                         m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5958                         m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5959                         m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5960                         R_Mesh_TextureState(&m);
5961                         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);
5962                         break;
5963                 case TEXTURELAYERTYPE_FOG:
5964                         // singletexture fogging
5965                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
5966                         if (layer->texture)
5967                         {
5968                                 memset(&m, 0, sizeof(m));
5969                                 m.tex[0] = R_GetTexture(layer->texture);
5970                                 m.texmatrix[0] = layer->texmatrix;
5971                                 m.pointer_texcoord[0] = rsurface.texcoordtexture2f;
5972                                 m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject;
5973                                 m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset;
5974                                 R_Mesh_TextureState(&m);
5975                         }
5976                         else
5977                                 R_Mesh_ResetTextureState();
5978                         // generate a color array for the fog pass
5979                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
5980                         {
5981                                 int i;
5982                                 float f, *v, *c;
5983                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
5984                                 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)
5985                                 {
5986                                         f = 1 - FogPoint_Model(v);
5987                                         c[0] = layer->color[0];
5988                                         c[1] = layer->color[1];
5989                                         c[2] = layer->color[2];
5990                                         c[3] = f * layer->color[3];
5991                                 }
5992                         }
5993                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
5994                         break;
5995                 default:
5996                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
5997                 }
5998                 GL_LockArrays(0, 0);
5999         }
6000         CHECKGLERROR
6001         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
6002         {
6003                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
6004                 GL_AlphaTest(false);
6005         }
6006 }
6007
6008 static void R_DrawTextureSurfaceList(int texturenumsurfaces, msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly)
6009 {
6010         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW)
6011                 return;
6012         rsurface.rtlight = NULL;
6013         CHECKGLERROR
6014         if (depthonly)
6015         {
6016                 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
6017                         return;
6018                 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
6019                         return;
6020                 if (rsurface.mode != RSURFMODE_MULTIPASS)
6021                         rsurface.mode = RSURFMODE_MULTIPASS;
6022                 if (r_depthfirst.integer == 3)
6023                 {
6024                         int i = (int)(texturesurfacelist[0] - rsurface.modelsurfaces);
6025                         if (!r_refdef.view.showdebug)
6026                                 GL_Color(0, 0, 0, 1);
6027                         else
6028                                 GL_Color(((i >> 6) & 7) / 7.0f, ((i >> 3) & 7) / 7.0f, (i & 7) / 7.0f,1);
6029                 }
6030                 else
6031                 {
6032                         GL_ColorMask(0,0,0,0);
6033                         GL_Color(1,1,1,1);
6034                 }
6035                 RSurf_SetupDepthAndCulling();
6036                 GL_DepthTest(true);
6037                 GL_BlendFunc(GL_ONE, GL_ZERO);
6038                 GL_DepthMask(true);
6039                 GL_AlphaTest(false);
6040                 R_Mesh_ColorPointer(NULL, 0, 0);
6041                 R_Mesh_ResetTextureState();
6042                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
6043                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
6044                 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
6045         }
6046         else if (r_depthfirst.integer == 3)
6047                 return;
6048         else if (!r_refdef.view.showdebug && (r_showsurfaces.integer || gl_lightmaps.integer))
6049         {
6050                 GL_Color(0, 0, 0, 1);
6051                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
6052         }
6053         else if (r_showsurfaces.integer)
6054         {
6055                 if (rsurface.mode != RSURFMODE_MULTIPASS)
6056                         rsurface.mode = RSURFMODE_MULTIPASS;
6057                 RSurf_SetupDepthAndCulling();
6058                 GL_DepthTest(true);
6059                 GL_BlendFunc(GL_ONE, GL_ZERO);
6060                 GL_DepthMask(writedepth);
6061                 GL_Color(1,1,1,1);
6062                 GL_AlphaTest(false);
6063                 R_Mesh_ColorPointer(NULL, 0, 0);
6064                 R_Mesh_ResetTextureState();
6065                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
6066                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
6067         }
6068         else if (gl_lightmaps.integer)
6069         {
6070                 rmeshstate_t m;
6071                 if (rsurface.mode != RSURFMODE_MULTIPASS)
6072                         rsurface.mode = RSURFMODE_MULTIPASS;
6073                 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
6074                 GL_DepthTest(true);
6075                 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
6076                 GL_BlendFunc(GL_ONE, GL_ZERO);
6077                 GL_DepthMask(writedepth);
6078                 GL_Color(1,1,1,1);
6079                 GL_AlphaTest(false);
6080                 R_Mesh_ColorPointer(NULL, 0, 0);
6081                 memset(&m, 0, sizeof(m));
6082                 m.tex[0] = R_GetTexture(r_texture_white);
6083                 m.pointer_texcoord[0] = rsurface.modeltexcoordlightmap2f;
6084                 m.pointer_texcoord_bufferobject[0] = rsurface.modeltexcoordlightmap2f_bufferobject;
6085                 m.pointer_texcoord_bufferoffset[0] = rsurface.modeltexcoordlightmap2f_bufferoffset;
6086                 R_Mesh_TextureState(&m);
6087                 RSurf_PrepareVerticesForBatch(rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT, false, texturenumsurfaces, texturesurfacelist);
6088                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
6089                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
6090                 else if (rsurface.uselightmaptexture)
6091                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
6092                 else
6093                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
6094         }
6095         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
6096                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
6097         else if (rsurface.texture->currentnumlayers)
6098         {
6099                 // write depth for anything we skipped on the depth-only pass earlier
6100                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
6101                         writedepth = true;
6102                 RSurf_SetupDepthAndCulling();
6103                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
6104                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
6105                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
6106                 if (r_glsl.integer && gl_support_fragment_shader)
6107                         R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist);
6108                 else if (gl_combine.integer && r_textureunits.integer >= 2)
6109                         R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist);
6110                 else
6111                         R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist);
6112         }
6113         CHECKGLERROR
6114         GL_LockArrays(0, 0);
6115 }
6116
6117 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
6118 {
6119         int i, j;
6120         int texturenumsurfaces, endsurface;
6121         texture_t *texture;
6122         msurface_t *surface;
6123         msurface_t *texturesurfacelist[1024];
6124
6125         // if the model is static it doesn't matter what value we give for
6126         // wantnormals and wanttangents, so this logic uses only rules applicable
6127         // to a model, knowing that they are meaningless otherwise
6128         if (ent == r_refdef.scene.worldentity)
6129                 RSurf_ActiveWorldEntity();
6130         else if ((ent->effects & EF_FULLBRIGHT) || r_showsurfaces.integer || VectorLength2(ent->modellight_diffuse) < (1.0f / 256.0f))
6131                 RSurf_ActiveModelEntity(ent, false, false);
6132         else
6133                 RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader);
6134
6135         for (i = 0;i < numsurfaces;i = j)
6136         {
6137                 j = i + 1;
6138                 surface = rsurface.modelsurfaces + surfacelist[i];
6139                 texture = surface->texture;
6140                 R_UpdateTextureInfo(ent, texture);
6141                 rsurface.texture = texture->currentframe;
6142                 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
6143                 // scan ahead until we find a different texture
6144                 endsurface = min(i + 1024, numsurfaces);
6145                 texturenumsurfaces = 0;
6146                 texturesurfacelist[texturenumsurfaces++] = surface;
6147                 for (;j < endsurface;j++)
6148                 {
6149                         surface = rsurface.modelsurfaces + surfacelist[j];
6150                         if (texture != surface->texture || rsurface.uselightmaptexture != (surface->lightmaptexture != NULL))
6151                                 break;
6152                         texturesurfacelist[texturenumsurfaces++] = surface;
6153                 }
6154                 // render the range of surfaces
6155                 R_DrawTextureSurfaceList(texturenumsurfaces, texturesurfacelist, true, false);
6156         }
6157
6158         RSurf_CleanUp();
6159 }
6160
6161 void R_QueueSurfaceList(entity_render_t *ent, int numsurfaces, msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes)
6162 {
6163         int i, j;
6164         vec3_t tempcenter, center;
6165         texture_t *texture;
6166         // if we're rendering water textures (extra scene renders), use a separate loop to avoid burdening the main one
6167         if (addwaterplanes)
6168         {
6169                 for (i = 0;i < numsurfaces;i++)
6170                         if (surfacelist[i]->texture->currentframe->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION))
6171                                 R_Water_AddWaterPlane(surfacelist[i]);
6172                 return;
6173         }
6174         // break the surface list down into batches by texture and use of lightmapping
6175         for (i = 0;i < numsurfaces;i = j)
6176         {
6177                 j = i + 1;
6178                 // texture is the base texture pointer, rsurface.texture is the
6179                 // current frame/skin the texture is directing us to use (for example
6180                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
6181                 // use skin 1 instead)
6182                 texture = surfacelist[i]->texture;
6183                 rsurface.texture = texture->currentframe;
6184                 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
6185                 if (!(rsurface.texture->currentmaterialflags & flagsmask))
6186                 {
6187                         // if this texture is not the kind we want, skip ahead to the next one
6188                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
6189                                 ;
6190                         continue;
6191                 }
6192                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
6193                 {
6194                         // transparent surfaces get pushed off into the transparent queue
6195                         const msurface_t *surface = surfacelist[i];
6196                         if (depthonly)
6197                                 continue;
6198                         tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
6199                         tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
6200                         tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
6201                         Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
6202                         R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, ent, surface - rsurface.modelsurfaces, rsurface.rtlight);
6203                 }
6204                 else
6205                 {
6206                         // simply scan ahead until we find a different texture or lightmap state
6207                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
6208                                 ;
6209                         // render the range of surfaces
6210                         R_DrawTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly);
6211                 }
6212         }
6213 }
6214
6215 float locboxvertex3f[6*4*3] =
6216 {
6217         1,0,1, 1,0,0, 1,1,0, 1,1,1,
6218         0,1,1, 0,1,0, 0,0,0, 0,0,1,
6219         1,1,1, 1,1,0, 0,1,0, 0,1,1,
6220         0,0,1, 0,0,0, 1,0,0, 1,0,1,
6221         0,0,1, 1,0,1, 1,1,1, 0,1,1,
6222         1,0,0, 0,0,0, 0,1,0, 1,1,0
6223 };
6224
6225 int locboxelement3i[6*2*3] =
6226 {
6227          0, 1, 2, 0, 2, 3,
6228          4, 5, 6, 4, 6, 7,
6229          8, 9,10, 8,10,11,
6230         12,13,14, 12,14,15,
6231         16,17,18, 16,18,19,
6232         20,21,22, 20,22,23
6233 };
6234
6235 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
6236 {
6237         int i, j;
6238         cl_locnode_t *loc = (cl_locnode_t *)ent;
6239         vec3_t mins, size;
6240         float vertex3f[6*4*3];
6241         CHECKGLERROR
6242         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6243         GL_DepthMask(false);
6244         GL_DepthRange(0, 1);
6245         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
6246         GL_DepthTest(true);
6247         GL_CullFace(GL_NONE);
6248         R_Mesh_Matrix(&identitymatrix);
6249
6250         R_Mesh_VertexPointer(vertex3f, 0, 0);
6251         R_Mesh_ColorPointer(NULL, 0, 0);
6252         R_Mesh_ResetTextureState();
6253
6254         i = surfacelist[0];
6255         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
6256                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
6257                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
6258                         surfacelist[0] < 0 ? 0.5f : 0.125f);
6259
6260         if (VectorCompare(loc->mins, loc->maxs))
6261         {
6262                 VectorSet(size, 2, 2, 2);
6263                 VectorMA(loc->mins, -0.5f, size, mins);
6264         }
6265         else
6266         {
6267                 VectorCopy(loc->mins, mins);
6268                 VectorSubtract(loc->maxs, loc->mins, size);
6269         }
6270
6271         for (i = 0;i < 6*4*3;)
6272                 for (j = 0;j < 3;j++, i++)
6273                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
6274
6275         R_Mesh_Draw(0, 6*4, 6*2, locboxelement3i, 0, 0);
6276 }
6277
6278 void R_DrawLocs(void)
6279 {
6280         int index;
6281         cl_locnode_t *loc, *nearestloc;
6282         vec3_t center;
6283         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
6284         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
6285         {
6286                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
6287                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
6288         }
6289 }
6290
6291 void R_DrawDebugModel(entity_render_t *ent)
6292 {
6293         int i, j, k, l, flagsmask;
6294         const int *elements;
6295         q3mbrush_t *brush;
6296         msurface_t *surface;
6297         model_t *model = ent->model;
6298         vec3_t v;
6299
6300         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WATER | MATERIALFLAG_WALL;
6301
6302         R_Mesh_ColorPointer(NULL, 0, 0);
6303         R_Mesh_ResetTextureState();
6304         GL_DepthRange(0, 1);
6305         GL_DepthTest(!r_showdisabledepthtest.integer);
6306         GL_DepthMask(false);
6307         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6308
6309         if (r_showcollisionbrushes.value > 0 && model->brush.num_brushes)
6310         {
6311                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
6312                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6313                 {
6314                         if (brush->colbrushf && brush->colbrushf->numtriangles)
6315                         {
6316                                 R_Mesh_VertexPointer(brush->colbrushf->points->v, 0, 0);
6317                                 GL_Color((i & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
6318                                 R_Mesh_Draw(0, brush->colbrushf->numpoints, brush->colbrushf->numtriangles, brush->colbrushf->elements, 0, 0);
6319                         }
6320                 }
6321                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6322                 {
6323                         if (surface->num_collisiontriangles)
6324                         {
6325                                 R_Mesh_VertexPointer(surface->data_collisionvertex3f, 0, 0);
6326                                 GL_Color((i & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((i >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
6327                                 R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i, 0, 0);
6328                         }
6329                 }
6330         }
6331
6332         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
6333
6334         if (r_showtris.integer || r_shownormals.integer)
6335         {
6336                 if (r_showdisabledepthtest.integer)
6337                 {
6338                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
6339                         GL_DepthMask(false);
6340                 }
6341                 else
6342                 {
6343                         GL_BlendFunc(GL_ONE, GL_ZERO);
6344                         GL_DepthMask(true);
6345                 }
6346                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
6347                 {
6348                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
6349                                 continue;
6350                         rsurface.texture = surface->texture->currentframe;
6351                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
6352                         {
6353                                 RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
6354                                 if (r_showtris.value > 0)
6355                                 {
6356                                         if (!rsurface.texture->currentlayers->depthmask)
6357                                                 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
6358                                         else if (ent == r_refdef.scene.worldentity)
6359                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
6360                                         else
6361                                                 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
6362                                         elements = (ent->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);
6363                                         CHECKGLERROR
6364                                         qglBegin(GL_LINES);
6365                                         for (k = 0;k < surface->num_triangles;k++, elements += 3)
6366                                         {
6367 #define GLVERTEXELEMENT(n) qglVertex3f(rsurface.vertex3f[elements[n]*3+0], rsurface.vertex3f[elements[n]*3+1], rsurface.vertex3f[elements[n]*3+2])
6368                                                 GLVERTEXELEMENT(0);GLVERTEXELEMENT(1);
6369                                                 GLVERTEXELEMENT(1);GLVERTEXELEMENT(2);
6370                                                 GLVERTEXELEMENT(2);GLVERTEXELEMENT(0);
6371                                         }
6372                                         qglEnd();
6373                                         CHECKGLERROR
6374                                 }
6375                                 if (r_shownormals.value > 0)
6376                                 {
6377                                         qglBegin(GL_LINES);
6378                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
6379                                         {
6380                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
6381                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
6382                                                 qglVertex3f(v[0], v[1], v[2]);
6383                                                 VectorMA(v, r_shownormals.value, rsurface.svector3f + l * 3, v);
6384                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
6385                                                 qglVertex3f(v[0], v[1], v[2]);
6386                                         }
6387                                         qglEnd();
6388                                         CHECKGLERROR
6389                                         qglBegin(GL_LINES);
6390                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
6391                                         {
6392                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
6393                                                 GL_Color(0, r_refdef.view.colorscale, 0, 1);
6394                                                 qglVertex3f(v[0], v[1], v[2]);
6395                                                 VectorMA(v, r_shownormals.value, rsurface.tvector3f + l * 3, v);
6396                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
6397                                                 qglVertex3f(v[0], v[1], v[2]);
6398                                         }
6399                                         qglEnd();
6400                                         CHECKGLERROR
6401                                         qglBegin(GL_LINES);
6402                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
6403                                         {
6404                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
6405                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
6406                                                 qglVertex3f(v[0], v[1], v[2]);
6407                                                 VectorMA(v, r_shownormals.value, rsurface.normal3f + l * 3, v);
6408                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
6409                                                 qglVertex3f(v[0], v[1], v[2]);
6410                                         }
6411                                         qglEnd();
6412                                         CHECKGLERROR
6413                                 }
6414                         }
6415                 }
6416                 rsurface.texture = NULL;
6417         }
6418 }
6419
6420 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
6421 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes, qboolean debug)
6422 {
6423         int i, j, endj, f, flagsmask;
6424         msurface_t *surface;
6425         texture_t *t;
6426         model_t *model = r_refdef.scene.worldmodel;
6427         const int maxsurfacelist = 1024;
6428         int numsurfacelist = 0;
6429         msurface_t *surfacelist[1024];
6430         if (model == NULL)
6431                 return;
6432
6433         RSurf_ActiveWorldEntity();
6434
6435         // update light styles on this submodel
6436         if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
6437         {
6438                 model_brush_lightstyleinfo_t *style;
6439                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
6440                 {
6441                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
6442                         {
6443                                 msurface_t *surfaces = model->data_surfaces;
6444                                 int *list = style->surfacelist;
6445                                 style->value = r_refdef.scene.lightstylevalue[style->style];
6446                                 for (j = 0;j < style->numsurfaces;j++)
6447                                         surfaces[list[j]].cached_dlight = true;
6448                         }
6449                 }
6450         }
6451
6452         R_UpdateAllTextureInfo(r_refdef.scene.worldentity);
6453         flagsmask = addwaterplanes ? (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) : (skysurfaces ? MATERIALFLAG_SKY : (MATERIALFLAG_WATER | MATERIALFLAG_WALL));
6454
6455         if (debug)
6456         {
6457                 R_DrawDebugModel(r_refdef.scene.worldentity);
6458                 return;
6459         }
6460
6461         f = 0;
6462         t = NULL;
6463         rsurface.uselightmaptexture = false;
6464         rsurface.texture = NULL;
6465         numsurfacelist = 0;
6466         j = model->firstmodelsurface;
6467         endj = j + model->nummodelsurfaces;
6468         while (j < endj)
6469         {
6470                 // quickly skip over non-visible surfaces
6471                 for (;j < endj && !r_refdef.viewcache.world_surfacevisible[j];j++)
6472                         ;
6473                 // quickly iterate over visible surfaces
6474                 for (;j < endj && r_refdef.viewcache.world_surfacevisible[j];j++)
6475                 {
6476                         // process this surface
6477                         surface = model->data_surfaces + j;
6478                         // if this surface fits the criteria, add it to the list
6479                         if (surface->num_triangles)
6480                         {
6481                                 // if lightmap parameters changed, rebuild lightmap texture
6482                                 if (surface->cached_dlight)
6483                                         R_BuildLightMap(r_refdef.scene.worldentity, surface);
6484                                 // add face to draw list
6485                                 surfacelist[numsurfacelist++] = surface;
6486                                 r_refdef.stats.world_triangles += surface->num_triangles;
6487                                 if (numsurfacelist >= maxsurfacelist)
6488                                 {
6489                                         r_refdef.stats.world_surfaces += numsurfacelist;
6490                                         R_QueueSurfaceList(r_refdef.scene.worldentity, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6491                                         numsurfacelist = 0;
6492                                 }
6493                         }
6494                 }
6495         }
6496         r_refdef.stats.world_surfaces += numsurfacelist;
6497         if (numsurfacelist)
6498                 R_QueueSurfaceList(r_refdef.scene.worldentity, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6499         RSurf_CleanUp();
6500 }
6501
6502 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean addwaterplanes, qboolean debug)
6503 {
6504         int i, j, f, flagsmask;
6505         msurface_t *surface, *endsurface;
6506         texture_t *t;
6507         model_t *model = ent->model;
6508         const int maxsurfacelist = 1024;
6509         int numsurfacelist = 0;
6510         msurface_t *surfacelist[1024];
6511         if (model == NULL)
6512                 return;
6513
6514         // if the model is static it doesn't matter what value we give for
6515         // wantnormals and wanttangents, so this logic uses only rules applicable
6516         // to a model, knowing that they are meaningless otherwise
6517         if (ent == r_refdef.scene.worldentity)
6518                 RSurf_ActiveWorldEntity();
6519         else if ((ent->effects & EF_FULLBRIGHT) || r_showsurfaces.integer || VectorLength2(ent->modellight_diffuse) < (1.0f / 256.0f))
6520                 RSurf_ActiveModelEntity(ent, false, false);
6521         else
6522                 RSurf_ActiveModelEntity(ent, true, r_glsl.integer && gl_support_fragment_shader && !depthonly);
6523
6524         // update light styles
6525         if (!skysurfaces && !depthonly && !addwaterplanes && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
6526         {
6527                 model_brush_lightstyleinfo_t *style;
6528                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
6529                 {
6530                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
6531                         {
6532                                 msurface_t *surfaces = model->data_surfaces;
6533                                 int *list = style->surfacelist;
6534                                 style->value = r_refdef.scene.lightstylevalue[style->style];
6535                                 for (j = 0;j < style->numsurfaces;j++)
6536                                         surfaces[list[j]].cached_dlight = true;
6537                         }
6538                 }
6539         }
6540
6541         R_UpdateAllTextureInfo(ent);
6542         flagsmask = addwaterplanes ? (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION) : (skysurfaces ? MATERIALFLAG_SKY : (MATERIALFLAG_WATER | MATERIALFLAG_WALL));
6543
6544         if (debug)
6545         {
6546                 R_DrawDebugModel(ent);
6547                 return;
6548         }
6549
6550         f = 0;
6551         t = NULL;
6552         rsurface.uselightmaptexture = false;
6553         rsurface.texture = NULL;
6554         numsurfacelist = 0;
6555         surface = model->data_surfaces + model->firstmodelsurface;
6556         endsurface = surface + model->nummodelsurfaces;
6557         for (;surface < endsurface;surface++)
6558         {
6559                 // if this surface fits the criteria, add it to the list
6560                 if (surface->num_triangles)
6561                 {
6562                         // if lightmap parameters changed, rebuild lightmap texture
6563                         if (surface->cached_dlight)
6564                                 R_BuildLightMap(ent, surface);
6565                         // add face to draw list
6566                         surfacelist[numsurfacelist++] = surface;
6567                         r_refdef.stats.entities_triangles += surface->num_triangles;
6568                         if (numsurfacelist >= maxsurfacelist)
6569                         {
6570                                 r_refdef.stats.entities_surfaces += numsurfacelist;
6571                                 R_QueueSurfaceList(ent, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6572                                 numsurfacelist = 0;
6573                         }
6574                 }
6575         }
6576         r_refdef.stats.entities_surfaces += numsurfacelist;
6577         if (numsurfacelist)
6578                 R_QueueSurfaceList(ent, numsurfacelist, surfacelist, flagsmask, writedepth, depthonly, addwaterplanes);
6579         RSurf_CleanUp();
6580 }