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