]> git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_rmain.c
r_water_scissormode: 0 = none, 1 = scissor only, 2 = cull only, 3 = both
[xonotic/darkplaces.git] / gl_rmain.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_main.c
21
22 #include "quakedef.h"
23 #include "cl_dyntexture.h"
24 #include "r_shadow.h"
25 #include "polygon.h"
26 #include "image.h"
27 #include "ft2.h"
28 #include "csprogs.h"
29 #include "cl_video.h"
30
31 mempool_t *r_main_mempool;
32 rtexturepool_t *r_main_texturepool;
33
34 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
35
36 static qboolean r_loadnormalmap;
37 static qboolean r_loadgloss;
38 qboolean r_loadfog;
39 static qboolean r_loaddds;
40 static qboolean r_savedds;
41
42 //
43 // screen size info
44 //
45 r_refdef_t r_refdef;
46
47 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
48 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
49 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
50 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
51 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
52 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
53 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
54 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
55
56 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
57 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
58 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
59 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
60 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
61
62 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "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"};
63 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
64 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
65 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
66 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
67 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
68 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)"};
69 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
70 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
71 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"};
72 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"};
73 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
74 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"};
75 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"};
76 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"};
77 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
78 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
79 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
80 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
81 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
82 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
83 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
84 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
85 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
86 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
87 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
88 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
89 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
90
91 cvar_t r_fakelight = {0, "r_fakelight","0", "render 'fake' lighting instead of real lightmaps"};
92 cvar_t r_fakelight_intensity = {0, "r_fakelight_intensity","0.75", "fakelight intensity modifier"};
93 #define FAKELIGHT_ENABLED (r_fakelight.integer >= 2 || (r_fakelight.integer && r_refdef.scene.worldmodel && !r_refdef.scene.worldmodel->lit))
94
95 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
96 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
97 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
98 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
99 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
100 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
101 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
102 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
103 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
104 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
105 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
106 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
107 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"};
108 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
109 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
110 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
111 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
112 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
113 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
114
115 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
116 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
117 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
118 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
119 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
120 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
121 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
122 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
123
124 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
125 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
126
127 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
128 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
129 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
130 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
131 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
132
133 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
134 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
135 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
136
137 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)"};
138 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
139 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
140 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
141 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
142 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
143 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
144 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
145 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
146
147 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)"};
148 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
149 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"};
150 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
151 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
152 cvar_t r_water_scissormode = {CVAR_SAVE, "r_water_scissormode", "3", "scissor (1) or cull (2) or both (3) water renders"};
153
154 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
155 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
156 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
157 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
158
159 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
160 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
161 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
162 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
163 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
164 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
165 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
166
167 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
168 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
169 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
170 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)"};
171
172 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"};
173
174 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"};
175
176 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
177
178 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
179 cvar_t r_batchmode = {0, "r_batchmode", "1", "selects method of rendering multiple surfaces with one driver call (values are 0, 1, 2, etc...)"};
180 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"};
181 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
182 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
183 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
184 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
185 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "16", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
186
187 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
188
189 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "1", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
190
191 extern cvar_t v_glslgamma;
192
193 extern qboolean v_flipped_state;
194
195 static struct r_bloomstate_s
196 {
197         qboolean enabled;
198         qboolean hdr;
199
200         int bloomwidth, bloomheight;
201
202         int screentexturewidth, screentextureheight;
203         rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
204
205         int bloomtexturewidth, bloomtextureheight;
206         rtexture_t *texture_bloom;
207
208         // arrays for rendering the screen passes
209         float screentexcoord2f[8];
210         float bloomtexcoord2f[8];
211         float offsettexcoord2f[8];
212
213         r_viewport_t viewport;
214 }
215 r_bloomstate;
216
217 r_waterstate_t r_waterstate;
218
219 /// shadow volume bsp struct with automatically growing nodes buffer
220 svbsp_t r_svbsp;
221
222 rtexture_t *r_texture_blanknormalmap;
223 rtexture_t *r_texture_white;
224 rtexture_t *r_texture_grey128;
225 rtexture_t *r_texture_black;
226 rtexture_t *r_texture_notexture;
227 rtexture_t *r_texture_whitecube;
228 rtexture_t *r_texture_normalizationcube;
229 rtexture_t *r_texture_fogattenuation;
230 rtexture_t *r_texture_fogheighttexture;
231 rtexture_t *r_texture_gammaramps;
232 unsigned int r_texture_gammaramps_serial;
233 //rtexture_t *r_texture_fogintensity;
234 rtexture_t *r_texture_reflectcube;
235
236 // TODO: hash lookups?
237 typedef struct cubemapinfo_s
238 {
239         char basename[64];
240         rtexture_t *texture;
241 }
242 cubemapinfo_t;
243
244 int r_texture_numcubemaps;
245 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
246
247 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
248 unsigned int r_numqueries;
249 unsigned int r_maxqueries;
250
251 typedef struct r_qwskincache_s
252 {
253         char name[MAX_QPATH];
254         skinframe_t *skinframe;
255 }
256 r_qwskincache_t;
257
258 static r_qwskincache_t *r_qwskincache;
259 static int r_qwskincache_size;
260
261 /// vertex coordinates for a quad that covers the screen exactly
262 const float r_screenvertex3f[12] =
263 {
264         0, 0, 0,
265         1, 0, 0,
266         1, 1, 0,
267         0, 1, 0
268 };
269
270 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
271 {
272         int i;
273         for (i = 0;i < verts;i++)
274         {
275                 out[0] = in[0] * r;
276                 out[1] = in[1] * g;
277                 out[2] = in[2] * b;
278                 out[3] = in[3];
279                 in += 4;
280                 out += 4;
281         }
282 }
283
284 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
285 {
286         int i;
287         for (i = 0;i < verts;i++)
288         {
289                 out[0] = r;
290                 out[1] = g;
291                 out[2] = b;
292                 out[3] = a;
293                 out += 4;
294         }
295 }
296
297 // FIXME: move this to client?
298 void FOG_clear(void)
299 {
300         if (gamemode == GAME_NEHAHRA)
301         {
302                 Cvar_Set("gl_fogenable", "0");
303                 Cvar_Set("gl_fogdensity", "0.2");
304                 Cvar_Set("gl_fogred", "0.3");
305                 Cvar_Set("gl_foggreen", "0.3");
306                 Cvar_Set("gl_fogblue", "0.3");
307         }
308         r_refdef.fog_density = 0;
309         r_refdef.fog_red = 0;
310         r_refdef.fog_green = 0;
311         r_refdef.fog_blue = 0;
312         r_refdef.fog_alpha = 1;
313         r_refdef.fog_start = 0;
314         r_refdef.fog_end = 16384;
315         r_refdef.fog_height = 1<<30;
316         r_refdef.fog_fadedepth = 128;
317         memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
318 }
319
320 static void R_BuildBlankTextures(void)
321 {
322         unsigned char data[4];
323         data[2] = 128; // normal X
324         data[1] = 128; // normal Y
325         data[0] = 255; // normal Z
326         data[3] = 128; // height
327         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
328         data[0] = 255;
329         data[1] = 255;
330         data[2] = 255;
331         data[3] = 255;
332         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
333         data[0] = 128;
334         data[1] = 128;
335         data[2] = 128;
336         data[3] = 255;
337         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
338         data[0] = 0;
339         data[1] = 0;
340         data[2] = 0;
341         data[3] = 255;
342         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
343 }
344
345 static void R_BuildNoTexture(void)
346 {
347         int x, y;
348         unsigned char pix[16][16][4];
349         // this makes a light grey/dark grey checkerboard texture
350         for (y = 0;y < 16;y++)
351         {
352                 for (x = 0;x < 16;x++)
353                 {
354                         if ((y < 8) ^ (x < 8))
355                         {
356                                 pix[y][x][0] = 128;
357                                 pix[y][x][1] = 128;
358                                 pix[y][x][2] = 128;
359                                 pix[y][x][3] = 255;
360                         }
361                         else
362                         {
363                                 pix[y][x][0] = 64;
364                                 pix[y][x][1] = 64;
365                                 pix[y][x][2] = 64;
366                                 pix[y][x][3] = 255;
367                         }
368                 }
369         }
370         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
371 }
372
373 static void R_BuildWhiteCube(void)
374 {
375         unsigned char data[6*1*1*4];
376         memset(data, 255, sizeof(data));
377         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
378 }
379
380 static void R_BuildNormalizationCube(void)
381 {
382         int x, y, side;
383         vec3_t v;
384         vec_t s, t, intensity;
385 #define NORMSIZE 64
386         unsigned char *data;
387         data = Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
388         for (side = 0;side < 6;side++)
389         {
390                 for (y = 0;y < NORMSIZE;y++)
391                 {
392                         for (x = 0;x < NORMSIZE;x++)
393                         {
394                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
395                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
396                                 switch(side)
397                                 {
398                                 default:
399                                 case 0:
400                                         v[0] = 1;
401                                         v[1] = -t;
402                                         v[2] = -s;
403                                         break;
404                                 case 1:
405                                         v[0] = -1;
406                                         v[1] = -t;
407                                         v[2] = s;
408                                         break;
409                                 case 2:
410                                         v[0] = s;
411                                         v[1] = 1;
412                                         v[2] = t;
413                                         break;
414                                 case 3:
415                                         v[0] = s;
416                                         v[1] = -1;
417                                         v[2] = -t;
418                                         break;
419                                 case 4:
420                                         v[0] = s;
421                                         v[1] = -t;
422                                         v[2] = 1;
423                                         break;
424                                 case 5:
425                                         v[0] = -s;
426                                         v[1] = -t;
427                                         v[2] = -1;
428                                         break;
429                                 }
430                                 intensity = 127.0f / sqrt(DotProduct(v, v));
431                                 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
432                                 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
433                                 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
434                                 data[((side*64+y)*64+x)*4+3] = 255;
435                         }
436                 }
437         }
438         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
439         Mem_Free(data);
440 }
441
442 static void R_BuildFogTexture(void)
443 {
444         int x, b;
445 #define FOGWIDTH 256
446         unsigned char data1[FOGWIDTH][4];
447         //unsigned char data2[FOGWIDTH][4];
448         double d, r, alpha;
449
450         r_refdef.fogmasktable_start = r_refdef.fog_start;
451         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
452         r_refdef.fogmasktable_range = r_refdef.fogrange;
453         r_refdef.fogmasktable_density = r_refdef.fog_density;
454
455         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
456         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
457         {
458                 d = (x * r - r_refdef.fogmasktable_start);
459                 if(developer_extra.integer)
460                         Con_DPrintf("%f ", d);
461                 d = max(0, d);
462                 if (r_fog_exp2.integer)
463                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
464                 else
465                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
466                 if(developer_extra.integer)
467                         Con_DPrintf(" : %f ", alpha);
468                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
469                 if(developer_extra.integer)
470                         Con_DPrintf(" = %f\n", alpha);
471                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
472         }
473
474         for (x = 0;x < FOGWIDTH;x++)
475         {
476                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
477                 data1[x][0] = b;
478                 data1[x][1] = b;
479                 data1[x][2] = b;
480                 data1[x][3] = 255;
481                 //data2[x][0] = 255 - b;
482                 //data2[x][1] = 255 - b;
483                 //data2[x][2] = 255 - b;
484                 //data2[x][3] = 255;
485         }
486         if (r_texture_fogattenuation)
487         {
488                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
489                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
490         }
491         else
492         {
493                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
494                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
495         }
496 }
497
498 static void R_BuildFogHeightTexture(void)
499 {
500         unsigned char *inpixels;
501         int size;
502         int x;
503         int y;
504         int j;
505         float c[4];
506         float f;
507         inpixels = NULL;
508         strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
509         if (r_refdef.fogheighttexturename[0])
510                 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
511         if (!inpixels)
512         {
513                 r_refdef.fog_height_tablesize = 0;
514                 if (r_texture_fogheighttexture)
515                         R_FreeTexture(r_texture_fogheighttexture);
516                 r_texture_fogheighttexture = NULL;
517                 if (r_refdef.fog_height_table2d)
518                         Mem_Free(r_refdef.fog_height_table2d);
519                 r_refdef.fog_height_table2d = NULL;
520                 if (r_refdef.fog_height_table1d)
521                         Mem_Free(r_refdef.fog_height_table1d);
522                 r_refdef.fog_height_table1d = NULL;
523                 return;
524         }
525         size = image_width;
526         r_refdef.fog_height_tablesize = size;
527         r_refdef.fog_height_table1d = Mem_Alloc(r_main_mempool, size * 4);
528         r_refdef.fog_height_table2d = Mem_Alloc(r_main_mempool, size * size * 4);
529         memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
530         Mem_Free(inpixels);
531         // LordHavoc: now the magic - what is that table2d for?  it is a cooked
532         // average fog color table accounting for every fog layer between a point
533         // and the camera.  (Note: attenuation is handled separately!)
534         for (y = 0;y < size;y++)
535         {
536                 for (x = 0;x < size;x++)
537                 {
538                         Vector4Clear(c);
539                         f = 0;
540                         if (x < y)
541                         {
542                                 for (j = x;j <= y;j++)
543                                 {
544                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
545                                         f++;
546                                 }
547                         }
548                         else
549                         {
550                                 for (j = x;j >= y;j--)
551                                 {
552                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
553                                         f++;
554                                 }
555                         }
556                         f = 1.0f / f;
557                         r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
558                         r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
559                         r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
560                         r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
561                 }
562         }
563         r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
564 }
565
566 //=======================================================================================================================================================
567
568 static const char *builtinshaderstring =
569 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
570 "// written by Forest 'LordHavoc' Hale\n"
571 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
572 "\n"
573 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
574 "# define USEFOG\n"
575 "#endif\n"
576 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
577 "#define USELIGHTMAP\n"
578 "#endif\n"
579 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
580 "#define USEEYEVECTOR\n"
581 "#endif\n"
582 "\n"
583 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
584 "# extension GL_ARB_texture_rectangle : enable\n"
585 "#endif\n"
586 "\n"
587 "#ifdef USESHADOWMAP2D\n"
588 "# ifdef GL_EXT_gpu_shader4\n"
589 "#   extension GL_EXT_gpu_shader4 : enable\n"
590 "# endif\n"
591 "# ifdef GL_ARB_texture_gather\n"
592 "#   extension GL_ARB_texture_gather : enable\n"
593 "# else\n"
594 "#   ifdef GL_AMD_texture_texture4\n"
595 "#     extension GL_AMD_texture_texture4 : enable\n"
596 "#   endif\n"
597 "# endif\n"
598 "#endif\n"
599 "\n"
600 "#ifdef USESHADOWMAPCUBE\n"
601 "# extension GL_EXT_gpu_shader4 : enable\n"
602 "#endif\n"
603 "\n"
604 "//#ifdef USESHADOWSAMPLER\n"
605 "//# extension GL_ARB_shadow : enable\n"
606 "//#endif\n"
607 "\n"
608 "//#ifdef __GLSL_CG_DATA_TYPES\n"
609 "//# define myhalf half\n"
610 "//# define myhalf2 half2\n"
611 "//# define myhalf3 half3\n"
612 "//# define myhalf4 half4\n"
613 "//#else\n"
614 "# define myhalf float\n"
615 "# define myhalf2 vec2\n"
616 "# define myhalf3 vec3\n"
617 "# define myhalf4 vec4\n"
618 "//#endif\n"
619 "\n"
620 "#ifdef VERTEX_SHADER\n"
621 "uniform mat4 ModelViewProjectionMatrix;\n"
622 "#endif\n"
623 "\n"
624 "#ifdef MODE_DEPTH_OR_SHADOW\n"
625 "#ifdef VERTEX_SHADER\n"
626 "void main(void)\n"
627 "{\n"
628 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
629 "}\n"
630 "#endif\n"
631 "#else // !MODE_DEPTH_ORSHADOW\n"
632 "\n"
633 "\n"
634 "\n"
635 "\n"
636 "#ifdef MODE_SHOWDEPTH\n"
637 "#ifdef VERTEX_SHADER\n"
638 "void main(void)\n"
639 "{\n"
640 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
641 "       gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
642 "}\n"
643 "#endif\n"
644 "\n"
645 "#ifdef FRAGMENT_SHADER\n"
646 "void main(void)\n"
647 "{\n"
648 "       gl_FragColor = gl_Color;\n"
649 "}\n"
650 "#endif\n"
651 "#else // !MODE_SHOWDEPTH\n"
652 "\n"
653 "\n"
654 "\n"
655 "\n"
656 "#ifdef MODE_POSTPROCESS\n"
657 "varying vec2 TexCoord1;\n"
658 "varying vec2 TexCoord2;\n"
659 "\n"
660 "#ifdef VERTEX_SHADER\n"
661 "void main(void)\n"
662 "{\n"
663 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
664 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
665 "#ifdef USEBLOOM\n"
666 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
667 "#endif\n"
668 "}\n"
669 "#endif\n"
670 "\n"
671 "#ifdef FRAGMENT_SHADER\n"
672 "uniform sampler2D Texture_First;\n"
673 "#ifdef USEBLOOM\n"
674 "uniform sampler2D Texture_Second;\n"
675 "#endif\n"
676 "#ifdef USEGAMMARAMPS\n"
677 "uniform sampler2D Texture_GammaRamps;\n"
678 "#endif\n"
679 "#ifdef USESATURATION\n"
680 "uniform float Saturation;\n"
681 "#endif\n"
682 "#ifdef USEVIEWTINT\n"
683 "uniform vec4 ViewTintColor;\n"
684 "#endif\n"
685 "//uncomment these if you want to use them:\n"
686 "uniform vec4 UserVec1;\n"
687 "uniform vec4 UserVec2;\n"
688 "// uniform vec4 UserVec3;\n"
689 "// uniform vec4 UserVec4;\n"
690 "// uniform float ClientTime;\n"
691 "uniform vec2 PixelSize;\n"
692 "void main(void)\n"
693 "{\n"
694 "       gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
695 "#ifdef USEBLOOM\n"
696 "       gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
697 "#endif\n"
698 "#ifdef USEVIEWTINT\n"
699 "       gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
700 "#endif\n"
701 "\n"
702 "#ifdef USEPOSTPROCESSING\n"
703 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
704 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
705 "       float sobel = 1.0;\n"
706 "       // vec2 ts = textureSize(Texture_First, 0);\n"
707 "       // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
708 "       vec2 px = PixelSize;\n"
709 "       vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
710 "       vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,  0.0)).rgb;\n"
711 "       vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
712 "       vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
713 "       vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x,  0.0)).rgb;\n"
714 "       vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
715 "       vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
716 "       vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2(  0.0,-px.y)).rgb;\n"
717 "       vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
718 "       vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
719 "       vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2(  0.0, px.y)).rgb;\n"
720 "       vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
721 "       float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
722 "       float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
723 "       float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
724 "       float px4 =  1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
725 "       float px5 =  2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
726 "       float px6 =  1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
727 "       float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
728 "       float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
729 "       float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
730 "       float py4 =  1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
731 "       float py5 =  2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
732 "       float py6 =  1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
733 "       sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
734 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
735 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
736 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
737 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107,  0.707107)) * UserVec1.y;\n"
738 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990,  0.891007)) * UserVec1.y;\n"
739 "       gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
740 "       gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
741 "#endif\n"
742 "\n"
743 "#ifdef USESATURATION\n"
744 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
745 "       float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
746 "       //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
747 "       gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
748 "#endif\n"
749 "\n"
750 "#ifdef USEGAMMARAMPS\n"
751 "       gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
752 "       gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
753 "       gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
754 "#endif\n"
755 "}\n"
756 "#endif\n"
757 "#else // !MODE_POSTPROCESS\n"
758 "\n"
759 "\n"
760 "\n"
761 "\n"
762 "#ifdef MODE_GENERIC\n"
763 "#ifdef USEDIFFUSE\n"
764 "varying vec2 TexCoord1;\n"
765 "#endif\n"
766 "#ifdef USESPECULAR\n"
767 "varying vec2 TexCoord2;\n"
768 "#endif\n"
769 "#ifdef VERTEX_SHADER\n"
770 "void main(void)\n"
771 "{\n"
772 "       gl_FrontColor = gl_Color;\n"
773 "#ifdef USEDIFFUSE\n"
774 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
775 "#endif\n"
776 "#ifdef USESPECULAR\n"
777 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
778 "#endif\n"
779 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
780 "}\n"
781 "#endif\n"
782 "\n"
783 "#ifdef FRAGMENT_SHADER\n"
784 "#ifdef USEDIFFUSE\n"
785 "uniform sampler2D Texture_First;\n"
786 "#endif\n"
787 "#ifdef USESPECULAR\n"
788 "uniform sampler2D Texture_Second;\n"
789 "#endif\n"
790 "\n"
791 "void main(void)\n"
792 "{\n"
793 "       gl_FragColor = gl_Color;\n"
794 "#ifdef USEDIFFUSE\n"
795 "       gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
796 "#endif\n"
797 "\n"
798 "#ifdef USESPECULAR\n"
799 "       vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
800 "# ifdef USECOLORMAPPING\n"
801 "       gl_FragColor *= tex2;\n"
802 "# endif\n"
803 "# ifdef USEGLOW\n"
804 "       gl_FragColor += tex2;\n"
805 "# endif\n"
806 "# ifdef USEVERTEXTEXTUREBLEND\n"
807 "       gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
808 "# endif\n"
809 "#endif\n"
810 "}\n"
811 "#endif\n"
812 "#else // !MODE_GENERIC\n"
813 "\n"
814 "\n"
815 "\n"
816 "\n"
817 "#ifdef MODE_BLOOMBLUR\n"
818 "varying TexCoord;\n"
819 "#ifdef VERTEX_SHADER\n"
820 "void main(void)\n"
821 "{\n"
822 "       gl_FrontColor = gl_Color;\n"
823 "       TexCoord = gl_MultiTexCoord0.xy;\n"
824 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
825 "}\n"
826 "#endif\n"
827 "\n"
828 "#ifdef FRAGMENT_SHADER\n"
829 "uniform sampler2D Texture_First;\n"
830 "uniform vec4 BloomBlur_Parameters;\n"
831 "\n"
832 "void main(void)\n"
833 "{\n"
834 "       int i;\n"
835 "       vec2 tc = TexCoord;\n"
836 "       vec3 color = texture2D(Texture_First, tc).rgb;\n"
837 "       tc += BloomBlur_Parameters.xy;\n"
838 "       for (i = 1;i < SAMPLES;i++)\n"
839 "       {\n"
840 "               color += texture2D(Texture_First, tc).rgb;\n"
841 "               tc += BloomBlur_Parameters.xy;\n"
842 "       }\n"
843 "       gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
844 "}\n"
845 "#endif\n"
846 "#else // !MODE_BLOOMBLUR\n"
847 "#ifdef MODE_REFRACTION\n"
848 "varying vec2 TexCoord;\n"
849 "varying vec4 ModelViewProjectionPosition;\n"
850 "uniform mat4 TexMatrix;\n"
851 "#ifdef VERTEX_SHADER\n"
852 "\n"
853 "void main(void)\n"
854 "{\n"
855 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
856 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
857 "       ModelViewProjectionPosition = gl_Position;\n"
858 "}\n"
859 "#endif\n"
860 "\n"
861 "#ifdef FRAGMENT_SHADER\n"
862 "uniform sampler2D Texture_Normal;\n"
863 "uniform sampler2D Texture_Refraction;\n"
864 "uniform sampler2D Texture_Reflection;\n"
865 "\n"
866 "uniform vec4 DistortScaleRefractReflect;\n"
867 "uniform vec4 ScreenScaleRefractReflect;\n"
868 "uniform vec4 ScreenCenterRefractReflect;\n"
869 "uniform vec4 RefractColor;\n"
870 "uniform vec4 ReflectColor;\n"
871 "uniform float ReflectFactor;\n"
872 "uniform float ReflectOffset;\n"
873 "\n"
874 "void main(void)\n"
875 "{\n"
876 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
877 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
878 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
879 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
880 "       // FIXME temporary hack to detect the case that the reflection\n"
881 "       // gets blackened at edges due to leaving the area that contains actual\n"
882 "       // content.\n"
883 "       // Remove this 'ack once we have a better way to stop this thing from\n"
884 "       // 'appening.\n"
885 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
886 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
887 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
888 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
889 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
890 "       gl_FragColor = vec4(texture2D(Texture_Refraction, ScreenTexCoord).rgb, 1.0) * RefractColor;\n"
891 "}\n"
892 "#endif\n"
893 "#else // !MODE_REFRACTION\n"
894 "\n"
895 "\n"
896 "\n"
897 "\n"
898 "#ifdef MODE_WATER\n"
899 "varying vec2 TexCoord;\n"
900 "varying vec3 EyeVector;\n"
901 "varying vec4 ModelViewProjectionPosition;\n"
902 "#ifdef VERTEX_SHADER\n"
903 "uniform vec3 EyePosition;\n"
904 "uniform mat4 TexMatrix;\n"
905 "\n"
906 "void main(void)\n"
907 "{\n"
908 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
909 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
910 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
911 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
912 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
913 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
914 "       ModelViewProjectionPosition = gl_Position;\n"
915 "}\n"
916 "#endif\n"
917 "\n"
918 "#ifdef FRAGMENT_SHADER\n"
919 "uniform sampler2D Texture_Normal;\n"
920 "uniform sampler2D Texture_Refraction;\n"
921 "uniform sampler2D Texture_Reflection;\n"
922 "\n"
923 "uniform vec4 DistortScaleRefractReflect;\n"
924 "uniform vec4 ScreenScaleRefractReflect;\n"
925 "uniform vec4 ScreenCenterRefractReflect;\n"
926 "uniform vec4 RefractColor;\n"
927 "uniform vec4 ReflectColor;\n"
928 "uniform float ReflectFactor;\n"
929 "uniform float ReflectOffset;\n"
930 "\n"
931 "void main(void)\n"
932 "{\n"
933 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
934 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
935 "       vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
936 "       //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
937 "       vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
938 "       // FIXME temporary hack to detect the case that the reflection\n"
939 "       // gets blackened at edges due to leaving the area that contains actual\n"
940 "       // content.\n"
941 "       // Remove this 'ack once we have a better way to stop this thing from\n"
942 "       // 'appening.\n"
943 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
944 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
945 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
946 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
947 "       ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
948 "       f       = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
949 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
950 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
951 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
952 "       ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
953 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
954 "       gl_FragColor = mix(vec4(texture2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, vec4(texture2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
955 "}\n"
956 "#endif\n"
957 "#else // !MODE_WATER\n"
958 "\n"
959 "\n"
960 "\n"
961 "\n"
962 "// common definitions between vertex shader and fragment shader:\n"
963 "\n"
964 "varying vec2 TexCoord;\n"
965 "#ifdef USEVERTEXTEXTUREBLEND\n"
966 "varying vec2 TexCoord2;\n"
967 "#endif\n"
968 "#ifdef USELIGHTMAP\n"
969 "varying vec2 TexCoordLightmap;\n"
970 "#endif\n"
971 "\n"
972 "#ifdef MODE_LIGHTSOURCE\n"
973 "varying vec3 CubeVector;\n"
974 "#endif\n"
975 "\n"
976 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
977 "varying vec3 LightVector;\n"
978 "#endif\n"
979 "\n"
980 "#ifdef USEEYEVECTOR\n"
981 "varying vec3 EyeVector;\n"
982 "#endif\n"
983 "#ifdef USEFOG\n"
984 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
985 "#endif\n"
986 "\n"
987 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
988 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
989 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
990 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
991 "#endif\n"
992 "\n"
993 "#ifdef USEREFLECTION\n"
994 "varying vec4 ModelViewProjectionPosition;\n"
995 "#endif\n"
996 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
997 "uniform vec3 LightPosition;\n"
998 "varying vec4 ModelViewPosition;\n"
999 "#endif\n"
1000 "\n"
1001 "#ifdef MODE_LIGHTSOURCE\n"
1002 "uniform vec3 LightPosition;\n"
1003 "#endif\n"
1004 "uniform vec3 EyePosition;\n"
1005 "#ifdef MODE_LIGHTDIRECTION\n"
1006 "uniform vec3 LightDir;\n"
1007 "#endif\n"
1008 "uniform vec4 FogPlane;\n"
1009 "\n"
1010 "#ifdef USESHADOWMAPORTHO\n"
1011 "varying vec3 ShadowMapTC;\n"
1012 "#endif\n"
1013 "\n"
1014 "\n"
1015 "\n"
1016 "\n"
1017 "\n"
1018 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
1019 "\n"
1020 "// fragment shader specific:\n"
1021 "#ifdef FRAGMENT_SHADER\n"
1022 "\n"
1023 "uniform sampler2D Texture_Normal;\n"
1024 "uniform sampler2D Texture_Color;\n"
1025 "uniform sampler2D Texture_Gloss;\n"
1026 "#ifdef USEGLOW\n"
1027 "uniform sampler2D Texture_Glow;\n"
1028 "#endif\n"
1029 "#ifdef USEVERTEXTEXTUREBLEND\n"
1030 "uniform sampler2D Texture_SecondaryNormal;\n"
1031 "uniform sampler2D Texture_SecondaryColor;\n"
1032 "uniform sampler2D Texture_SecondaryGloss;\n"
1033 "#ifdef USEGLOW\n"
1034 "uniform sampler2D Texture_SecondaryGlow;\n"
1035 "#endif\n"
1036 "#endif\n"
1037 "#ifdef USECOLORMAPPING\n"
1038 "uniform sampler2D Texture_Pants;\n"
1039 "uniform sampler2D Texture_Shirt;\n"
1040 "#endif\n"
1041 "#ifdef USEFOG\n"
1042 "#ifdef USEFOGHEIGHTTEXTURE\n"
1043 "uniform sampler2D Texture_FogHeightTexture;\n"
1044 "#endif\n"
1045 "uniform sampler2D Texture_FogMask;\n"
1046 "#endif\n"
1047 "#ifdef USELIGHTMAP\n"
1048 "uniform sampler2D Texture_Lightmap;\n"
1049 "#endif\n"
1050 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1051 "uniform sampler2D Texture_Deluxemap;\n"
1052 "#endif\n"
1053 "#ifdef USEREFLECTION\n"
1054 "uniform sampler2D Texture_Reflection;\n"
1055 "#endif\n"
1056 "\n"
1057 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1058 "uniform sampler2D Texture_ScreenDepth;\n"
1059 "uniform sampler2D Texture_ScreenNormalMap;\n"
1060 "#endif\n"
1061 "#ifdef USEDEFERREDLIGHTMAP\n"
1062 "uniform sampler2D Texture_ScreenDiffuse;\n"
1063 "uniform sampler2D Texture_ScreenSpecular;\n"
1064 "#endif\n"
1065 "\n"
1066 "uniform myhalf3 Color_Pants;\n"
1067 "uniform myhalf3 Color_Shirt;\n"
1068 "uniform myhalf3 FogColor;\n"
1069 "\n"
1070 "#ifdef USEFOG\n"
1071 "uniform float FogRangeRecip;\n"
1072 "uniform float FogPlaneViewDist;\n"
1073 "uniform float FogHeightFade;\n"
1074 "vec3 FogVertex(vec3 surfacecolor)\n"
1075 "{\n"
1076 "       vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1077 "       float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1078 "       float fogfrac;\n"
1079 "#ifdef USEFOGHEIGHTTEXTURE\n"
1080 "       vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1081 "       fogfrac = fogheightpixel.a;\n"
1082 "       return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1083 "#else\n"
1084 "# ifdef USEFOGOUTSIDE\n"
1085 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1086 "# else\n"
1087 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1088 "# endif\n"
1089 "       return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1090 "#endif\n"
1091 "}\n"
1092 "#endif\n"
1093 "\n"
1094 "#ifdef USEOFFSETMAPPING\n"
1095 "uniform float OffsetMapping_Scale;\n"
1096 "vec2 OffsetMapping(vec2 TexCoord)\n"
1097 "{\n"
1098 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1099 "       // 14 sample relief mapping: linear search and then binary search\n"
1100 "       // this basically steps forward a small amount repeatedly until it finds\n"
1101 "       // itself inside solid, then jitters forward and back using decreasing\n"
1102 "       // amounts to find the impact\n"
1103 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1104 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1105 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1106 "       vec3 RT = vec3(TexCoord, 1);\n"
1107 "       OffsetVector *= 0.1;\n"
1108 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1109 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1110 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1111 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1112 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1113 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1114 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1115 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1116 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1117 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
1118 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
1119 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
1120 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
1121 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1122 "       return RT.xy;\n"
1123 "#else\n"
1124 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1125 "       // this basically moves forward the full distance, and then backs up based\n"
1126 "       // on height of samples\n"
1127 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1128 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1129 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1130 "       TexCoord += OffsetVector;\n"
1131 "       OffsetVector *= 0.333;\n"
1132 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1133 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1134 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1135 "       return TexCoord;\n"
1136 "#endif\n"
1137 "}\n"
1138 "#endif // USEOFFSETMAPPING\n"
1139 "\n"
1140 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1141 "uniform sampler2D Texture_Attenuation;\n"
1142 "uniform samplerCube Texture_Cube;\n"
1143 "#endif\n"
1144 "\n"
1145 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1146 "\n"
1147 "#ifdef USESHADOWMAPRECT\n"
1148 "# ifdef USESHADOWSAMPLER\n"
1149 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1150 "# else\n"
1151 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1152 "# endif\n"
1153 "#endif\n"
1154 "\n"
1155 "#ifdef USESHADOWMAP2D\n"
1156 "# ifdef USESHADOWSAMPLER\n"
1157 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1158 "# else\n"
1159 "uniform sampler2D Texture_ShadowMap2D;\n"
1160 "# endif\n"
1161 "#endif\n"
1162 "\n"
1163 "#ifdef USESHADOWMAPVSDCT\n"
1164 "uniform samplerCube Texture_CubeProjection;\n"
1165 "#endif\n"
1166 "\n"
1167 "#ifdef USESHADOWMAPCUBE\n"
1168 "# ifdef USESHADOWSAMPLER\n"
1169 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1170 "# else\n"
1171 "uniform samplerCube Texture_ShadowMapCube;\n"
1172 "# endif\n"
1173 "#endif\n"
1174 "\n"
1175 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1176 "uniform vec2 ShadowMap_TextureScale;\n"
1177 "uniform vec4 ShadowMap_Parameters;\n"
1178 "#endif\n"
1179 "\n"
1180 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1181 "# ifdef USESHADOWMAPORTHO\n"
1182 "#  define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1183 "# else\n"
1184 "#  ifdef USESHADOWMAPVSDCT\n"
1185 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1186 "{\n"
1187 "       vec3 adir = abs(dir);\n"
1188 "       vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1189 "       vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1190 "       return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1191 "}\n"
1192 "#  else\n"
1193 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1194 "{\n"
1195 "       vec3 adir = abs(dir);\n"
1196 "       float ma = adir.z;\n"
1197 "       vec4 proj = vec4(dir, 2.5);\n"
1198 "       if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1199 "       if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1200 "       vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1201 "       return vec3(proj.xy * aparams.x + vec2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1202 "}\n"
1203 "#  endif\n"
1204 "# endif\n"
1205 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1206 "\n"
1207 "#ifdef USESHADOWMAPCUBE\n"
1208 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1209 "{\n"
1210 "       vec3 adir = abs(dir);\n"
1211 "       return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1212 "}\n"
1213 "#endif\n"
1214 "\n"
1215 "# ifdef USESHADOWMAPRECT\n"
1216 "float ShadowMapCompare(vec3 dir)\n"
1217 "{\n"
1218 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1219 "       float f;\n"
1220 "#  ifdef USESHADOWSAMPLER\n"
1221 "\n"
1222 "#    ifdef USESHADOWMAPPCF\n"
1223 "#      define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1224 "       f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1225 "#    else\n"
1226 "       f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1227 "#    endif\n"
1228 "\n"
1229 "#  else\n"
1230 "\n"
1231 "#    ifdef USESHADOWMAPPCF\n"
1232 "#      if USESHADOWMAPPCF > 1\n"
1233 "#        define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1234 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1235 "       vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1236 "       vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1237 "       vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1238 "       vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1239 "       vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1240 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1241 "#      else\n"
1242 "#        define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1243 "       vec2 offset = fract(shadowmaptc.xy);\n"
1244 "       vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1245 "       vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1246 "       vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1247 "       vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1248 "       f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1249 "#      endif\n"
1250 "#    else\n"
1251 "       f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1252 "#    endif\n"
1253 "\n"
1254 "#  endif\n"
1255 "#  ifdef USESHADOWMAPORTHO\n"
1256 "       return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1257 "#  else\n"
1258 "       return f;\n"
1259 "#  endif\n"
1260 "}\n"
1261 "# endif\n"
1262 "\n"
1263 "# ifdef USESHADOWMAP2D\n"
1264 "float ShadowMapCompare(vec3 dir)\n"
1265 "{\n"
1266 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1267 "       float f;\n"
1268 "\n"
1269 "#  ifdef USESHADOWSAMPLER\n"
1270 "#    ifdef USESHADOWMAPPCF\n"
1271 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
1272 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1273 "       f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1274 "#    else\n"
1275 "       f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1276 "#    endif\n"
1277 "#  else\n"
1278 "#    ifdef USESHADOWMAPPCF\n"
1279 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1280 "#      ifdef GL_ARB_texture_gather\n"
1281 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1282 "#      else\n"
1283 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1284 "#      endif\n"
1285 "       vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1286 "#      if USESHADOWMAPPCF > 1\n"
1287 "   vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1288 "   vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1289 "   vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1290 "   vec4 group4 = step(shadowmaptc.z, texval(-2.0,  0.0));\n"
1291 "   vec4 group5 = step(shadowmaptc.z, texval( 0.0,  0.0));\n"
1292 "   vec4 group6 = step(shadowmaptc.z, texval( 2.0,  0.0));\n"
1293 "   vec4 group7 = step(shadowmaptc.z, texval(-2.0,  2.0));\n"
1294 "   vec4 group8 = step(shadowmaptc.z, texval( 0.0,  2.0));\n"
1295 "   vec4 group9 = step(shadowmaptc.z, texval( 2.0,  2.0));\n"
1296 "       vec4 locols = vec4(group1.ab, group3.ab);\n"
1297 "       vec4 hicols = vec4(group7.rg, group9.rg);\n"
1298 "       locols.yz += group2.ab;\n"
1299 "       hicols.yz += group8.rg;\n"
1300 "       vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1301 "                               vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1302 "                               mix(locols, hicols, offset.y);\n"
1303 "       vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1304 "       cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1305 "       f = dot(cols, vec4(1.0/25.0));\n"
1306 "#      else\n"
1307 "       vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1308 "       vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1309 "       vec4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
1310 "       vec4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
1311 "       vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1312 "                               mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1313 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1314 "#      endif\n"
1315 "#     else\n"
1316 "#      ifdef GL_EXT_gpu_shader4\n"
1317 "#        define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1318 "#      else\n"
1319 "#        define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r  \n"
1320 "#      endif\n"
1321 "#      if USESHADOWMAPPCF > 1\n"
1322 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1323 "       center *= ShadowMap_TextureScale;\n"
1324 "       vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1325 "       vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
1326 "       vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
1327 "       vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
1328 "       vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1329 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1330 "#      else\n"
1331 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1332 "       vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1333 "       vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1334 "       vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1335 "       vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1336 "       f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1337 "#      endif\n"
1338 "#     endif\n"
1339 "#    else\n"
1340 "       f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1341 "#    endif\n"
1342 "#  endif\n"
1343 "#  ifdef USESHADOWMAPORTHO\n"
1344 "       return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1345 "#  else\n"
1346 "       return f;\n"
1347 "#  endif\n"
1348 "}\n"
1349 "# endif\n"
1350 "\n"
1351 "# ifdef USESHADOWMAPCUBE\n"
1352 "float ShadowMapCompare(vec3 dir)\n"
1353 "{\n"
1354 "       // apply depth texture cubemap as light filter\n"
1355 "       vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1356 "       float f;\n"
1357 "#  ifdef USESHADOWSAMPLER\n"
1358 "       f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1359 "#  else\n"
1360 "       f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1361 "#  endif\n"
1362 "       return f;\n"
1363 "}\n"
1364 "# endif\n"
1365 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1366 "#endif // FRAGMENT_SHADER\n"
1367 "\n"
1368 "\n"
1369 "\n"
1370 "\n"
1371 "#ifdef MODE_DEFERREDGEOMETRY\n"
1372 "#ifdef VERTEX_SHADER\n"
1373 "uniform mat4 TexMatrix;\n"
1374 "#ifdef USEVERTEXTEXTUREBLEND\n"
1375 "uniform mat4 BackgroundTexMatrix;\n"
1376 "#endif\n"
1377 "uniform mat4 ModelViewMatrix;\n"
1378 "void main(void)\n"
1379 "{\n"
1380 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1381 "#ifdef USEVERTEXTEXTUREBLEND\n"
1382 "       gl_FrontColor = gl_Color;\n"
1383 "       TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1384 "#endif\n"
1385 "\n"
1386 "       // transform unnormalized eye direction into tangent space\n"
1387 "#ifdef USEOFFSETMAPPING\n"
1388 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1389 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1390 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1391 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1392 "#endif\n"
1393 "\n"
1394 "       VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1395 "       VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1396 "       VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1397 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1398 "}\n"
1399 "#endif // VERTEX_SHADER\n"
1400 "\n"
1401 "#ifdef FRAGMENT_SHADER\n"
1402 "void main(void)\n"
1403 "{\n"
1404 "#ifdef USEOFFSETMAPPING\n"
1405 "       // apply offsetmapping\n"
1406 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1407 "#define TexCoord TexCoordOffset\n"
1408 "#endif\n"
1409 "\n"
1410 "#ifdef USEALPHAKILL\n"
1411 "       if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1412 "               discard;\n"
1413 "#endif\n"
1414 "\n"
1415 "#ifdef USEVERTEXTEXTUREBLEND\n"
1416 "       float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1417 "       float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1418 "       //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1419 "       //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1420 "#endif\n"
1421 "\n"
1422 "#ifdef USEVERTEXTEXTUREBLEND\n"
1423 "       vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1424 "       float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1425 "#else\n"
1426 "       vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1427 "       float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1428 "#endif\n"
1429 "\n"
1430 "       gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1431 "}\n"
1432 "#endif // FRAGMENT_SHADER\n"
1433 "#else // !MODE_DEFERREDGEOMETRY\n"
1434 "\n"
1435 "\n"
1436 "\n"
1437 "\n"
1438 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1439 "#ifdef VERTEX_SHADER\n"
1440 "uniform mat4 ModelViewMatrix;\n"
1441 "void main(void)\n"
1442 "{\n"
1443 "       ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1444 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1445 "}\n"
1446 "#endif // VERTEX_SHADER\n"
1447 "\n"
1448 "#ifdef FRAGMENT_SHADER\n"
1449 "uniform mat4 ViewToLight;\n"
1450 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1451 "uniform vec2 ScreenToDepth;\n"
1452 "uniform myhalf3 DeferredColor_Ambient;\n"
1453 "uniform myhalf3 DeferredColor_Diffuse;\n"
1454 "#ifdef USESPECULAR\n"
1455 "uniform myhalf3 DeferredColor_Specular;\n"
1456 "uniform myhalf SpecularPower;\n"
1457 "#endif\n"
1458 "uniform myhalf2 PixelToScreenTexCoord;\n"
1459 "void main(void)\n"
1460 "{\n"
1461 "       // calculate viewspace pixel position\n"
1462 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1463 "       vec3 position;\n"
1464 "       position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1465 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1466 "       // decode viewspace pixel normal\n"
1467 "       myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1468 "       myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1469 "       // surfacenormal = pixel normal in viewspace\n"
1470 "       // LightVector = pixel to light in viewspace\n"
1471 "       // CubeVector = position in lightspace\n"
1472 "       // eyevector = pixel to view in viewspace\n"
1473 "       vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1474 "       myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1475 "#ifdef USEDIFFUSE\n"
1476 "       // calculate diffuse shading\n"
1477 "       myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1478 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1479 "#endif\n"
1480 "#ifdef USESPECULAR\n"
1481 "       // calculate directional shading\n"
1482 "       vec3 eyevector = position * -1.0;\n"
1483 "#  ifdef USEEXACTSPECULARMATH\n"
1484 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1485 "#  else\n"
1486 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1487 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1488 "#  endif\n"
1489 "#endif\n"
1490 "\n"
1491 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1492 "       fade *= ShadowMapCompare(CubeVector);\n"
1493 "#endif\n"
1494 "\n"
1495 "#ifdef USEDIFFUSE\n"
1496 "       gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1497 "#else\n"
1498 "       gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1499 "#endif\n"
1500 "#ifdef USESPECULAR\n"
1501 "       gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1502 "#else\n"
1503 "       gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1504 "#endif\n"
1505 "\n"
1506 "# ifdef USECUBEFILTER\n"
1507 "       vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1508 "       gl_FragData[0].rgb *= cubecolor;\n"
1509 "       gl_FragData[1].rgb *= cubecolor;\n"
1510 "# endif\n"
1511 "}\n"
1512 "#endif // FRAGMENT_SHADER\n"
1513 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1514 "\n"
1515 "\n"
1516 "\n"
1517 "\n"
1518 "#ifdef VERTEX_SHADER\n"
1519 "uniform mat4 TexMatrix;\n"
1520 "#ifdef USEVERTEXTEXTUREBLEND\n"
1521 "uniform mat4 BackgroundTexMatrix;\n"
1522 "#endif\n"
1523 "#ifdef MODE_LIGHTSOURCE\n"
1524 "uniform mat4 ModelToLight;\n"
1525 "#endif\n"
1526 "#ifdef USESHADOWMAPORTHO\n"
1527 "uniform mat4 ShadowMapMatrix;\n"
1528 "#endif\n"
1529 "void main(void)\n"
1530 "{\n"
1531 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1532 "       gl_FrontColor = gl_Color;\n"
1533 "#endif\n"
1534 "       // copy the surface texcoord\n"
1535 "       TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1536 "#ifdef USEVERTEXTEXTUREBLEND\n"
1537 "       TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1538 "#endif\n"
1539 "#ifdef USELIGHTMAP\n"
1540 "       TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1541 "#endif\n"
1542 "\n"
1543 "#ifdef MODE_LIGHTSOURCE\n"
1544 "       // transform vertex position into light attenuation/cubemap space\n"
1545 "       // (-1 to +1 across the light box)\n"
1546 "       CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1547 "\n"
1548 "# ifdef USEDIFFUSE\n"
1549 "       // transform unnormalized light direction into tangent space\n"
1550 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
1551 "       //  normalize it per pixel)\n"
1552 "       vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1553 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1554 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1555 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1556 "# endif\n"
1557 "#endif\n"
1558 "\n"
1559 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1560 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1561 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1562 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1563 "#endif\n"
1564 "\n"
1565 "       // transform unnormalized eye direction into tangent space\n"
1566 "#ifdef USEEYEVECTOR\n"
1567 "       vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1568 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1569 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1570 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1571 "#endif\n"
1572 "\n"
1573 "#ifdef USEFOG\n"
1574 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1575 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1576 "#endif\n"
1577 "\n"
1578 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1579 "       VectorS = gl_MultiTexCoord1.xyz;\n"
1580 "       VectorT = gl_MultiTexCoord2.xyz;\n"
1581 "       VectorR = gl_MultiTexCoord3.xyz;\n"
1582 "#endif\n"
1583 "\n"
1584 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1585 "       gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1586 "\n"
1587 "#ifdef USESHADOWMAPORTHO\n"
1588 "       ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1589 "#endif\n"
1590 "\n"
1591 "#ifdef USEREFLECTION\n"
1592 "       ModelViewProjectionPosition = gl_Position;\n"
1593 "#endif\n"
1594 "}\n"
1595 "#endif // VERTEX_SHADER\n"
1596 "\n"
1597 "\n"
1598 "\n"
1599 "\n"
1600 "#ifdef FRAGMENT_SHADER\n"
1601 "#ifdef USEDEFERREDLIGHTMAP\n"
1602 "uniform myhalf2 PixelToScreenTexCoord;\n"
1603 "uniform myhalf3 DeferredMod_Diffuse;\n"
1604 "uniform myhalf3 DeferredMod_Specular;\n"
1605 "#endif\n"
1606 "uniform myhalf3 Color_Ambient;\n"
1607 "uniform myhalf3 Color_Diffuse;\n"
1608 "uniform myhalf3 Color_Specular;\n"
1609 "uniform myhalf SpecularPower;\n"
1610 "#ifdef USEGLOW\n"
1611 "uniform myhalf3 Color_Glow;\n"
1612 "#endif\n"
1613 "uniform myhalf Alpha;\n"
1614 "#ifdef USEREFLECTION\n"
1615 "uniform vec4 DistortScaleRefractReflect;\n"
1616 "uniform vec4 ScreenScaleRefractReflect;\n"
1617 "uniform vec4 ScreenCenterRefractReflect;\n"
1618 "uniform myhalf4 ReflectColor;\n"
1619 "#endif\n"
1620 "#ifdef USEREFLECTCUBE\n"
1621 "uniform mat4 ModelToReflectCube;\n"
1622 "uniform sampler2D Texture_ReflectMask;\n"
1623 "uniform samplerCube Texture_ReflectCube;\n"
1624 "#endif\n"
1625 "#ifdef MODE_LIGHTDIRECTION\n"
1626 "uniform myhalf3 LightColor;\n"
1627 "#endif\n"
1628 "#ifdef MODE_LIGHTSOURCE\n"
1629 "uniform myhalf3 LightColor;\n"
1630 "#endif\n"
1631 "void main(void)\n"
1632 "{\n"
1633 "#ifdef USEOFFSETMAPPING\n"
1634 "       // apply offsetmapping\n"
1635 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1636 "#define TexCoord TexCoordOffset\n"
1637 "#endif\n"
1638 "\n"
1639 "       // combine the diffuse textures (base, pants, shirt)\n"
1640 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1641 "#ifdef USEALPHAKILL\n"
1642 "       if (color.a < 0.5)\n"
1643 "               discard;\n"
1644 "#endif\n"
1645 "       color.a *= Alpha;\n"
1646 "#ifdef USECOLORMAPPING\n"
1647 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1648 "#endif\n"
1649 "#ifdef USEVERTEXTEXTUREBLEND\n"
1650 "       myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1651 "       //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1652 "       //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1653 "       color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1654 "       color.a = 1.0;\n"
1655 "       //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1656 "#endif\n"
1657 "\n"
1658 "       // get the surface normal\n"
1659 "#ifdef USEVERTEXTEXTUREBLEND\n"
1660 "       myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1661 "#else\n"
1662 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1663 "#endif\n"
1664 "\n"
1665 "       // get the material colors\n"
1666 "       myhalf3 diffusetex = color.rgb;\n"
1667 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1668 "# ifdef USEVERTEXTEXTUREBLEND\n"
1669 "       myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1670 "# else\n"
1671 "       myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1672 "# endif\n"
1673 "#endif\n"
1674 "\n"
1675 "#ifdef USEREFLECTCUBE\n"
1676 "       vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1677 "       vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1678 "       vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1679 "       diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1680 "#endif\n"
1681 "\n"
1682 "\n"
1683 "\n"
1684 "\n"
1685 "#ifdef MODE_LIGHTSOURCE\n"
1686 "       // light source\n"
1687 "#ifdef USEDIFFUSE\n"
1688 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1689 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1690 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1691 "#ifdef USESPECULAR\n"
1692 "#ifdef USEEXACTSPECULARMATH\n"
1693 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1694 "#else\n"
1695 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1696 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1697 "#endif\n"
1698 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1699 "#endif\n"
1700 "#else\n"
1701 "       color.rgb = diffusetex * Color_Ambient;\n"
1702 "#endif\n"
1703 "       color.rgb *= LightColor;\n"
1704 "       color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1705 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1706 "       color.rgb *= ShadowMapCompare(CubeVector);\n"
1707 "#endif\n"
1708 "# ifdef USECUBEFILTER\n"
1709 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1710 "# endif\n"
1711 "#endif // MODE_LIGHTSOURCE\n"
1712 "\n"
1713 "\n"
1714 "\n"
1715 "\n"
1716 "#ifdef MODE_LIGHTDIRECTION\n"
1717 "#define SHADING\n"
1718 "#ifdef USEDIFFUSE\n"
1719 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1720 "#endif\n"
1721 "#define lightcolor LightColor\n"
1722 "#endif // MODE_LIGHTDIRECTION\n"
1723 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1724 "#define SHADING\n"
1725 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1726 "       myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1727 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1728 "       // convert modelspace light vector to tangentspace\n"
1729 "       myhalf3 lightnormal;\n"
1730 "       lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1731 "       lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1732 "       lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1733 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1734 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1735 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1736 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1737 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1738 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1739 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1740 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1741 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1742 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1743 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1744 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1745 "#define SHADING\n"
1746 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1747 "       myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1748 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1749 "#endif\n"
1750 "\n"
1751 "\n"
1752 "\n"
1753 "\n"
1754 "#ifdef MODE_FAKELIGHT\n"
1755 "#define SHADING\n"
1756 "myhalf3 lightnormal = myhalf3(normalize(EyeVector));\n"
1757 "myhalf3 lightcolor = myhalf3(1.0);\n"
1758 "#endif // MODE_FAKELIGHT\n"
1759 "\n"
1760 "\n"
1761 "\n"
1762 "\n"
1763 "#ifdef MODE_LIGHTMAP\n"
1764 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1765 "#endif // MODE_LIGHTMAP\n"
1766 "#ifdef MODE_VERTEXCOLOR\n"
1767 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1768 "#endif // MODE_VERTEXCOLOR\n"
1769 "#ifdef MODE_FLATCOLOR\n"
1770 "       color.rgb = diffusetex * Color_Ambient;\n"
1771 "#endif // MODE_FLATCOLOR\n"
1772 "\n"
1773 "\n"
1774 "\n"
1775 "\n"
1776 "#ifdef SHADING\n"
1777 "# ifdef USEDIFFUSE\n"
1778 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1779 "#  ifdef USESPECULAR\n"
1780 "#   ifdef USEEXACTSPECULARMATH\n"
1781 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1782 "#   else\n"
1783 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1784 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1785 "#   endif\n"
1786 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1787 "#  else\n"
1788 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1789 "#  endif\n"
1790 "# else\n"
1791 "       color.rgb = diffusetex * Color_Ambient;\n"
1792 "# endif\n"
1793 "#endif\n"
1794 "\n"
1795 "#ifdef USESHADOWMAPORTHO\n"
1796 "       color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1797 "#endif\n"
1798 "\n"
1799 "#ifdef USEDEFERREDLIGHTMAP\n"
1800 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1801 "       color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1802 "       color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1803 "#endif\n"
1804 "\n"
1805 "#ifdef USEGLOW\n"
1806 "#ifdef USEVERTEXTEXTUREBLEND\n"
1807 "       color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1808 "#else\n"
1809 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1810 "#endif\n"
1811 "#endif\n"
1812 "\n"
1813 "#ifdef USEFOG\n"
1814 "       color.rgb = FogVertex(color.rgb);\n"
1815 "#endif\n"
1816 "\n"
1817 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
1818 "#ifdef USEREFLECTION\n"
1819 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1820 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1821 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1822 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1823 "       // FIXME temporary hack to detect the case that the reflection\n"
1824 "       // gets blackened at edges due to leaving the area that contains actual\n"
1825 "       // content.\n"
1826 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1827 "       // 'appening.\n"
1828 "       float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1829 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1830 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1831 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1832 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1833 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1834 "#endif\n"
1835 "\n"
1836 "       gl_FragColor = vec4(color);\n"
1837 "}\n"
1838 "#endif // FRAGMENT_SHADER\n"
1839 "\n"
1840 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1841 "#endif // !MODE_DEFERREDGEOMETRY\n"
1842 "#endif // !MODE_WATER\n"
1843 "#endif // !MODE_REFRACTION\n"
1844 "#endif // !MODE_BLOOMBLUR\n"
1845 "#endif // !MODE_GENERIC\n"
1846 "#endif // !MODE_POSTPROCESS\n"
1847 "#endif // !MODE_SHOWDEPTH\n"
1848 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1849 ;
1850
1851 /*
1852 =========================================================================================================================================================
1853
1854
1855
1856 =========================================================================================================================================================
1857
1858
1859
1860 =========================================================================================================================================================
1861
1862
1863
1864 =========================================================================================================================================================
1865
1866
1867
1868 =========================================================================================================================================================
1869
1870
1871
1872 =========================================================================================================================================================
1873
1874
1875
1876 =========================================================================================================================================================
1877 */
1878
1879 const char *builtincgshaderstring =
1880 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1881 "// written by Forest 'LordHavoc' Hale\n"
1882 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1883 "\n"
1884 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1885 "#if defined(USEREFLECTION)\n"
1886 "#undef USESHADOWMAPORTHO\n"
1887 "#endif\n"
1888 "\n"
1889 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1890 "# define USEFOG\n"
1891 "#endif\n"
1892 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1893 "#define USELIGHTMAP\n"
1894 "#endif\n"
1895 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
1896 "#define USEEYEVECTOR\n"
1897 "#endif\n"
1898 "\n"
1899 "#ifdef FRAGMENT_SHADER\n"
1900 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1901 "#endif\n"
1902 "\n"
1903 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1904 "#ifdef VERTEX_SHADER\n"
1905 "void main\n"
1906 "(\n"
1907 "float4 gl_Vertex : POSITION,\n"
1908 "uniform float4x4 ModelViewProjectionMatrix,\n"
1909 "out float4 gl_Position : POSITION\n"
1910 ")\n"
1911 "{\n"
1912 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1913 "}\n"
1914 "#endif\n"
1915 "#else // !MODE_DEPTH_ORSHADOW\n"
1916 "\n"
1917 "\n"
1918 "\n"
1919 "\n"
1920 "#ifdef MODE_SHOWDEPTH\n"
1921 "#ifdef VERTEX_SHADER\n"
1922 "void main\n"
1923 "(\n"
1924 "float4 gl_Vertex : POSITION,\n"
1925 "uniform float4x4 ModelViewProjectionMatrix,\n"
1926 "out float4 gl_Position : POSITION,\n"
1927 "out float4 gl_FrontColor : COLOR0\n"
1928 ")\n"
1929 "{\n"
1930 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1931 "       gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1932 "}\n"
1933 "#endif\n"
1934 "\n"
1935 "#ifdef FRAGMENT_SHADER\n"
1936 "void main\n"
1937 "(\n"
1938 "float4 gl_FrontColor : COLOR0,\n"
1939 "out float4 gl_FragColor : COLOR\n"
1940 ")\n"
1941 "{\n"
1942 "       gl_FragColor = gl_FrontColor;\n"
1943 "}\n"
1944 "#endif\n"
1945 "#else // !MODE_SHOWDEPTH\n"
1946 "\n"
1947 "\n"
1948 "\n"
1949 "\n"
1950 "#ifdef MODE_POSTPROCESS\n"
1951 "\n"
1952 "#ifdef VERTEX_SHADER\n"
1953 "void main\n"
1954 "(\n"
1955 "float4 gl_Vertex : POSITION,\n"
1956 "uniform float4x4 ModelViewProjectionMatrix,\n"
1957 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1958 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
1959 "out float4 gl_Position : POSITION,\n"
1960 "out float2 TexCoord1 : TEXCOORD0,\n"
1961 "out float2 TexCoord2 : TEXCOORD1\n"
1962 ")\n"
1963 "{\n"
1964 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1965 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
1966 "#ifdef USEBLOOM\n"
1967 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
1968 "#endif\n"
1969 "}\n"
1970 "#endif\n"
1971 "\n"
1972 "#ifdef FRAGMENT_SHADER\n"
1973 "void main\n"
1974 "(\n"
1975 "float2 TexCoord1 : TEXCOORD0,\n"
1976 "float2 TexCoord2 : TEXCOORD1,\n"
1977 "uniform sampler2D Texture_First,\n"
1978 "#ifdef USEBLOOM\n"
1979 "uniform sampler2D Texture_Second,\n"
1980 "#endif\n"
1981 "#ifdef USEGAMMARAMPS\n"
1982 "uniform sampler2D Texture_GammaRamps,\n"
1983 "#endif\n"
1984 "#ifdef USESATURATION\n"
1985 "uniform float Saturation,\n"
1986 "#endif\n"
1987 "#ifdef USEVIEWTINT\n"
1988 "uniform float4 ViewTintColor,\n"
1989 "#endif\n"
1990 "uniform float4 UserVec1,\n"
1991 "uniform float4 UserVec2,\n"
1992 "uniform float4 UserVec3,\n"
1993 "uniform float4 UserVec4,\n"
1994 "uniform float ClientTime,\n"
1995 "uniform float2 PixelSize,\n"
1996 "out float4 gl_FragColor : COLOR\n"
1997 ")\n"
1998 "{\n"
1999 "       gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
2000 "#ifdef USEBLOOM\n"
2001 "       gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
2002 "#endif\n"
2003 "#ifdef USEVIEWTINT\n"
2004 "       gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
2005 "#endif\n"
2006 "\n"
2007 "#ifdef USEPOSTPROCESSING\n"
2008 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
2009 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
2010 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
2011 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
2012 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
2013 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107,  0.707107)) * UserVec1.y;\n"
2014 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990,  0.891007)) * UserVec1.y;\n"
2015 "       gl_FragColor /= (1 + 5 * UserVec1.y);\n"
2016 "#endif\n"
2017 "\n"
2018 "#ifdef USESATURATION\n"
2019 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2020 "       float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2021 "       //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2022 "       gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2023 "#endif\n"
2024 "\n"
2025 "#ifdef USEGAMMARAMPS\n"
2026 "       gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2027 "       gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2028 "       gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2029 "#endif\n"
2030 "}\n"
2031 "#endif\n"
2032 "#else // !MODE_POSTPROCESS\n"
2033 "\n"
2034 "\n"
2035 "\n"
2036 "\n"
2037 "#ifdef MODE_GENERIC\n"
2038 "#ifdef VERTEX_SHADER\n"
2039 "void main\n"
2040 "(\n"
2041 "float4 gl_Vertex : POSITION,\n"
2042 "uniform float4x4 ModelViewProjectionMatrix,\n"
2043 "float4 gl_Color : COLOR0,\n"
2044 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2045 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2046 "out float4 gl_Position : POSITION,\n"
2047 "out float4 gl_FrontColor : COLOR,\n"
2048 "out float2 TexCoord1 : TEXCOORD0,\n"
2049 "out float2 TexCoord2 : TEXCOORD1\n"
2050 ")\n"
2051 "{\n"
2052 "       gl_FrontColor = gl_Color;\n"
2053 "#ifdef USEDIFFUSE\n"
2054 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
2055 "#endif\n"
2056 "#ifdef USESPECULAR\n"
2057 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
2058 "#endif\n"
2059 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2060 "}\n"
2061 "#endif\n"
2062 "\n"
2063 "#ifdef FRAGMENT_SHADER\n"
2064 "\n"
2065 "void main\n"
2066 "(\n"
2067 "float4 gl_FrontColor : COLOR,\n"
2068 "float2 TexCoord1 : TEXCOORD0,\n"
2069 "float2 TexCoord2 : TEXCOORD1,\n"
2070 "#ifdef USEDIFFUSE\n"
2071 "uniform sampler2D Texture_First,\n"
2072 "#endif\n"
2073 "#ifdef USESPECULAR\n"
2074 "uniform sampler2D Texture_Second,\n"
2075 "#endif\n"
2076 "out float4 gl_FragColor : COLOR\n"
2077 ")\n"
2078 "{\n"
2079 "       gl_FragColor = gl_FrontColor;\n"
2080 "#ifdef USEDIFFUSE\n"
2081 "       gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2082 "#endif\n"
2083 "\n"
2084 "#ifdef USESPECULAR\n"
2085 "       float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2086 "# ifdef USECOLORMAPPING\n"
2087 "       gl_FragColor *= tex2;\n"
2088 "# endif\n"
2089 "# ifdef USEGLOW\n"
2090 "       gl_FragColor += tex2;\n"
2091 "# endif\n"
2092 "# ifdef USEVERTEXTEXTUREBLEND\n"
2093 "       gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2094 "# endif\n"
2095 "#endif\n"
2096 "}\n"
2097 "#endif\n"
2098 "#else // !MODE_GENERIC\n"
2099 "\n"
2100 "\n"
2101 "\n"
2102 "\n"
2103 "#ifdef MODE_BLOOMBLUR\n"
2104 "#ifdef VERTEX_SHADER\n"
2105 "void main\n"
2106 "(\n"
2107 "float4 gl_Vertex : POSITION,\n"
2108 "uniform float4x4 ModelViewProjectionMatrix,\n"
2109 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2110 "out float4 gl_Position : POSITION,\n"
2111 "out float2 TexCoord : TEXCOORD0\n"
2112 ")\n"
2113 "{\n"
2114 "       TexCoord = gl_MultiTexCoord0.xy;\n"
2115 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2116 "}\n"
2117 "#endif\n"
2118 "\n"
2119 "#ifdef FRAGMENT_SHADER\n"
2120 "\n"
2121 "void main\n"
2122 "(\n"
2123 "float2 TexCoord : TEXCOORD0,\n"
2124 "uniform sampler2D Texture_First,\n"
2125 "uniform float4 BloomBlur_Parameters,\n"
2126 "out float4 gl_FragColor : COLOR\n"
2127 ")\n"
2128 "{\n"
2129 "       int i;\n"
2130 "       float2 tc = TexCoord;\n"
2131 "       float3 color = tex2D(Texture_First, tc).rgb;\n"
2132 "       tc += BloomBlur_Parameters.xy;\n"
2133 "       for (i = 1;i < SAMPLES;i++)\n"
2134 "       {\n"
2135 "               color += tex2D(Texture_First, tc).rgb;\n"
2136 "               tc += BloomBlur_Parameters.xy;\n"
2137 "       }\n"
2138 "       gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2139 "}\n"
2140 "#endif\n"
2141 "#else // !MODE_BLOOMBLUR\n"
2142 "#ifdef MODE_REFRACTION\n"
2143 "#ifdef VERTEX_SHADER\n"
2144 "void main\n"
2145 "(\n"
2146 "float4 gl_Vertex : POSITION,\n"
2147 "uniform float4x4 ModelViewProjectionMatrix,\n"
2148 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2149 "uniform float4x4 TexMatrix,\n"
2150 "uniform float3 EyePosition,\n"
2151 "out float4 gl_Position : POSITION,\n"
2152 "out float2 TexCoord : TEXCOORD0,\n"
2153 "out float3 EyeVector : TEXCOORD1,\n"
2154 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2155 ")\n"
2156 "{\n"
2157 "       TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2158 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2159 "       ModelViewProjectionPosition = gl_Position;\n"
2160 "}\n"
2161 "#endif\n"
2162 "\n"
2163 "#ifdef FRAGMENT_SHADER\n"
2164 "void main\n"
2165 "(\n"
2166 "float2 TexCoord : TEXCOORD0,\n"
2167 "float3 EyeVector : TEXCOORD1,\n"
2168 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2169 "uniform sampler2D Texture_Normal,\n"
2170 "uniform sampler2D Texture_Refraction,\n"
2171 "uniform sampler2D Texture_Reflection,\n"
2172 "uniform float4 DistortScaleRefractReflect,\n"
2173 "uniform float4 ScreenScaleRefractReflect,\n"
2174 "uniform float4 ScreenCenterRefractReflect,\n"
2175 "uniform float4 RefractColor,\n"
2176 "out float4 gl_FragColor : COLOR\n"
2177 ")\n"
2178 "{\n"
2179 "       float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2180 "       //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2181 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2182 "       float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2183 "       // FIXME temporary hack to detect the case that the reflection\n"
2184 "       // gets blackened at edges due to leaving the area that contains actual\n"
2185 "       // content.\n"
2186 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2187 "       // 'appening.\n"
2188 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2189 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2190 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2191 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2192 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2193 "       gl_FragColor = float4(tex2D(Texture_Refraction, ScreenTexCoord).rgb, 1) * RefractColor;\n"
2194 "}\n"
2195 "#endif\n"
2196 "#else // !MODE_REFRACTION\n"
2197 "\n"
2198 "\n"
2199 "\n"
2200 "\n"
2201 "#ifdef MODE_WATER\n"
2202 "#ifdef VERTEX_SHADER\n"
2203 "\n"
2204 "void main\n"
2205 "(\n"
2206 "float4 gl_Vertex : POSITION,\n"
2207 "uniform float4x4 ModelViewProjectionMatrix,\n"
2208 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2209 "uniform float4x4 TexMatrix,\n"
2210 "uniform float3 EyePosition,\n"
2211 "out float4 gl_Position : POSITION,\n"
2212 "out float2 TexCoord : TEXCOORD0,\n"
2213 "out float3 EyeVector : TEXCOORD1,\n"
2214 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2215 ")\n"
2216 "{\n"
2217 "       TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2218 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2219 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2220 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2221 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2222 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2223 "       ModelViewProjectionPosition = gl_Position;\n"
2224 "}\n"
2225 "#endif\n"
2226 "\n"
2227 "#ifdef FRAGMENT_SHADER\n"
2228 "void main\n"
2229 "(\n"
2230 "float2 TexCoord : TEXCOORD0,\n"
2231 "float3 EyeVector : TEXCOORD1,\n"
2232 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2233 "uniform sampler2D Texture_Normal,\n"
2234 "uniform sampler2D Texture_Refraction,\n"
2235 "uniform sampler2D Texture_Reflection,\n"
2236 "uniform float4 DistortScaleRefractReflect,\n"
2237 "uniform float4 ScreenScaleRefractReflect,\n"
2238 "uniform float4 ScreenCenterRefractReflect,\n"
2239 "uniform float4 RefractColor,\n"
2240 "uniform float4 ReflectColor,\n"
2241 "uniform float ReflectFactor,\n"
2242 "uniform float ReflectOffset,\n"
2243 "out float4 gl_FragColor : COLOR\n"
2244 ")\n"
2245 "{\n"
2246 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2247 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2248 "       float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2249 "       float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2250 "       // FIXME temporary hack to detect the case that the reflection\n"
2251 "       // gets blackened at edges due to leaving the area that contains actual\n"
2252 "       // content.\n"
2253 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2254 "       // 'appening.\n"
2255 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2256 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2257 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2258 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2259 "       ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2260 "       f       = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2261 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2262 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2263 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2264 "       ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2265 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2266 "       gl_FragColor = lerp(float4(tex2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, float4(tex2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
2267 "}\n"
2268 "#endif\n"
2269 "#else // !MODE_WATER\n"
2270 "\n"
2271 "\n"
2272 "\n"
2273 "\n"
2274 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
2275 "\n"
2276 "// fragment shader specific:\n"
2277 "#ifdef FRAGMENT_SHADER\n"
2278 "\n"
2279 "#ifdef USEFOG\n"
2280 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask, sampler2D Texture_FogHeightTexture)\n"
2281 "{\n"
2282 "       float fogfrac;\n"
2283 "#ifdef USEFOGHEIGHTTEXTURE\n"
2284 "       float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2285 "       fogfrac = fogheightpixel.a;\n"
2286 "       return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2287 "#else\n"
2288 "# ifdef USEFOGOUTSIDE\n"
2289 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2290 "# else\n"
2291 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2292 "# endif\n"
2293 "       return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2294 "#endif\n"
2295 "}\n"
2296 "#endif\n"
2297 "\n"
2298 "#ifdef USEOFFSETMAPPING\n"
2299 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2300 "{\n"
2301 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2302 "       // 14 sample relief mapping: linear search and then binary search\n"
2303 "       // this basically steps forward a small amount repeatedly until it finds\n"
2304 "       // itself inside solid, then jitters forward and back using decreasing\n"
2305 "       // amounts to find the impact\n"
2306 "       //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2307 "       //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2308 "       float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2309 "       float3 RT = float3(TexCoord, 1);\n"
2310 "       OffsetVector *= 0.1;\n"
2311 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2312 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2313 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2314 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2315 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2316 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2317 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2318 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2319 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2320 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
2321 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
2322 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
2323 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
2324 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2325 "       return RT.xy;\n"
2326 "#else\n"
2327 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2328 "       // this basically moves forward the full distance, and then backs up based\n"
2329 "       // on height of samples\n"
2330 "       //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2331 "       //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2332 "       float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2333 "       TexCoord += OffsetVector;\n"
2334 "       OffsetVector *= 0.333;\n"
2335 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2336 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2337 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2338 "       return TexCoord;\n"
2339 "#endif\n"
2340 "}\n"
2341 "#endif // USEOFFSETMAPPING\n"
2342 "\n"
2343 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2344 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2345 "# ifdef USESHADOWMAPORTHO\n"
2346 "#  define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2347 "# else\n"
2348 "#  ifdef USESHADOWMAPVSDCT\n"
2349 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2350 "{\n"
2351 "       float3 adir = abs(dir);\n"
2352 "       float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2353 "       float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2354 "       return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2355 "}\n"
2356 "#  else\n"
2357 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2358 "{\n"
2359 "       float3 adir = abs(dir);\n"
2360 "       float ma = adir.z;\n"
2361 "       float4 proj = float4(dir, 2.5);\n"
2362 "       if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2363 "       if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2364 "       float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2365 "       return float3(proj.xy * aparams.x + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2366 "}\n"
2367 "#  endif\n"
2368 "# endif\n"
2369 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2370 "\n"
2371 "#ifdef USESHADOWMAPCUBE\n"
2372 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2373 "{\n"
2374 "    float3 adir = abs(dir);\n"
2375 "    return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2376 "}\n"
2377 "#endif\n"
2378 "\n"
2379 "# ifdef USESHADOWMAPRECT\n"
2380 "#ifdef USESHADOWMAPVSDCT\n"
2381 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2382 "#else\n"
2383 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2384 "#endif\n"
2385 "{\n"
2386 "#ifdef USESHADOWMAPVSDCT\n"
2387 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2388 "#else\n"
2389 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2390 "#endif\n"
2391 "       float f;\n"
2392 "#  ifdef USESHADOWSAMPLER\n"
2393 "\n"
2394 "#    ifdef USESHADOWMAPPCF\n"
2395 "#      define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2396 "    f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2397 "#    else\n"
2398 "    f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2399 "#    endif\n"
2400 "\n"
2401 "#  else\n"
2402 "\n"
2403 "#    ifdef USESHADOWMAPPCF\n"
2404 "#      if USESHADOWMAPPCF > 1\n"
2405 "#        define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2406 "    float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2407 "    float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2408 "    float4 row2 = step(shadowmaptc.z, float4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
2409 "    float4 row3 = step(shadowmaptc.z, float4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
2410 "    float4 row4 = step(shadowmaptc.z, float4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
2411 "    float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2412 "    f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2413 "#      else\n"
2414 "#        define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2415 "    float2 offset = frac(shadowmaptc.xy);\n"
2416 "    float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2417 "    float3 row2 = step(shadowmaptc.z, float3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
2418 "    float3 row3 = step(shadowmaptc.z, float3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
2419 "    float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2420 "    f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2421 "#      endif\n"
2422 "#    else\n"
2423 "    f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2424 "#    endif\n"
2425 "\n"
2426 "#  endif\n"
2427 "#  ifdef USESHADOWMAPORTHO\n"
2428 "       return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2429 "#  else\n"
2430 "       return f;\n"
2431 "#  endif\n"
2432 "}\n"
2433 "# endif\n"
2434 "\n"
2435 "# ifdef USESHADOWMAP2D\n"
2436 "#ifdef USESHADOWMAPVSDCT\n"
2437 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2438 "#else\n"
2439 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2440 "#endif\n"
2441 "{\n"
2442 "#ifdef USESHADOWMAPVSDCT\n"
2443 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2444 "#else\n"
2445 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2446 "#endif\n"
2447 "    float f;\n"
2448 "\n"
2449 "#  ifdef USESHADOWSAMPLER\n"
2450 "#    ifdef USESHADOWMAPPCF\n"
2451 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
2452 "    float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2453 "    f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2454 "#    else\n"
2455 "    f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2456 "#    endif\n"
2457 "#  else\n"
2458 "#    ifdef USESHADOWMAPPCF\n"
2459 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2460 "#      ifdef GL_ARB_texture_gather\n"
2461 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2462 "#      else\n"
2463 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2464 "#      endif\n"
2465 "    float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2466 "    center *= ShadowMap_TextureScale;\n"
2467 "    float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2468 "    float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2469 "    float4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
2470 "    float4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
2471 "    float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2472 "                lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2473 "    f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2474 "#     else\n"
2475 "#        define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale)  \n"
2476 "#      if USESHADOWMAPPCF > 1\n"
2477 "    float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2478 "    center *= ShadowMap_TextureScale;\n"
2479 "    float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2480 "    float4 row2 = step(shadowmaptc.z, float4(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0), texval( 2.0,  0.0)));\n"
2481 "    float4 row3 = step(shadowmaptc.z, float4(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0), texval( 2.0,  1.0)));\n"
2482 "    float4 row4 = step(shadowmaptc.z, float4(texval(-1.0,  2.0), texval( 0.0,  2.0), texval( 1.0,  2.0), texval( 2.0,  2.0)));\n"
2483 "    float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2484 "    f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2485 "#      else\n"
2486 "    float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2487 "    float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2488 "    float3 row2 = step(shadowmaptc.z, float3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
2489 "    float3 row3 = step(shadowmaptc.z, float3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
2490 "    float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2491 "    f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2492 "#      endif\n"
2493 "#     endif\n"
2494 "#    else\n"
2495 "    f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2496 "#    endif\n"
2497 "#  endif\n"
2498 "#  ifdef USESHADOWMAPORTHO\n"
2499 "       return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2500 "#  else\n"
2501 "       return f;\n"
2502 "#  endif\n"
2503 "}\n"
2504 "# endif\n"
2505 "\n"
2506 "# ifdef USESHADOWMAPCUBE\n"
2507 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2508 "{\n"
2509 "    // apply depth texture cubemap as light filter\n"
2510 "    float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2511 "    float f;\n"
2512 "#  ifdef USESHADOWSAMPLER\n"
2513 "    f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2514 "#  else\n"
2515 "    f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2516 "#  endif\n"
2517 "    return f;\n"
2518 "}\n"
2519 "# endif\n"
2520 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2521 "#endif // FRAGMENT_SHADER\n"
2522 "\n"
2523 "\n"
2524 "\n"
2525 "\n"
2526 "#ifdef MODE_DEFERREDGEOMETRY\n"
2527 "#ifdef VERTEX_SHADER\n"
2528 "void main\n"
2529 "(\n"
2530 "float4 gl_Vertex : POSITION,\n"
2531 "uniform float4x4 ModelViewProjectionMatrix,\n"
2532 "#ifdef USEVERTEXTEXTUREBLEND\n"
2533 "float4 gl_Color : COLOR0,\n"
2534 "#endif\n"
2535 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2536 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2537 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2538 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2539 "uniform float4x4 TexMatrix,\n"
2540 "#ifdef USEVERTEXTEXTUREBLEND\n"
2541 "uniform float4x4 BackgroundTexMatrix,\n"
2542 "#endif\n"
2543 "uniform float4x4 ModelViewMatrix,\n"
2544 "#ifdef USEOFFSETMAPPING\n"
2545 "uniform float3 EyePosition,\n"
2546 "#endif\n"
2547 "out float4 gl_Position : POSITION,\n"
2548 "out float4 gl_FrontColor : COLOR,\n"
2549 "out float4 TexCoordBoth : TEXCOORD0,\n"
2550 "#ifdef USEOFFSETMAPPING\n"
2551 "out float3 EyeVector : TEXCOORD2,\n"
2552 "#endif\n"
2553 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2554 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2555 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2556 ")\n"
2557 "{\n"
2558 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2559 "#ifdef USEVERTEXTEXTUREBLEND\n"
2560 "       gl_FrontColor = gl_Color;\n"
2561 "       TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2562 "#endif\n"
2563 "\n"
2564 "       // transform unnormalized eye direction into tangent space\n"
2565 "#ifdef USEOFFSETMAPPING\n"
2566 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2567 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2568 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2569 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2570 "#endif\n"
2571 "\n"
2572 "       VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2573 "       VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2574 "       VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2575 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2576 "}\n"
2577 "#endif // VERTEX_SHADER\n"
2578 "\n"
2579 "#ifdef FRAGMENT_SHADER\n"
2580 "void main\n"
2581 "(\n"
2582 "float4 TexCoordBoth : TEXCOORD0,\n"
2583 "float3 EyeVector : TEXCOORD2,\n"
2584 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2585 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2586 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2587 "uniform sampler2D Texture_Normal,\n"
2588 "#ifdef USEALPHAKILL\n"
2589 "uniform sampler2D Texture_Color,\n"
2590 "#endif\n"
2591 "uniform sampler2D Texture_Gloss,\n"
2592 "#ifdef USEVERTEXTEXTUREBLEND\n"
2593 "uniform sampler2D Texture_SecondaryNormal,\n"
2594 "uniform sampler2D Texture_SecondaryGloss,\n"
2595 "#endif\n"
2596 "#ifdef USEOFFSETMAPPING\n"
2597 "uniform float OffsetMapping_Scale,\n"
2598 "#endif\n"
2599 "uniform half SpecularPower,\n"
2600 "out float4 gl_FragColor : COLOR\n"
2601 ")\n"
2602 "{\n"
2603 "       float2 TexCoord = TexCoordBoth.xy;\n"
2604 "#ifdef USEOFFSETMAPPING\n"
2605 "       // apply offsetmapping\n"
2606 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2607 "#define TexCoord TexCoordOffset\n"
2608 "#endif\n"
2609 "\n"
2610 "#ifdef USEALPHAKILL\n"
2611 "       if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2612 "               discard;\n"
2613 "#endif\n"
2614 "\n"
2615 "#ifdef USEVERTEXTEXTUREBLEND\n"
2616 "       float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2617 "       float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2618 "       //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2619 "       //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2620 "#endif\n"
2621 "\n"
2622 "#ifdef USEVERTEXTEXTUREBLEND\n"
2623 "       float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2624 "       float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2625 "#else\n"
2626 "       float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2627 "       float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2628 "#endif\n"
2629 "\n"
2630 "       gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2631 "}\n"
2632 "#endif // FRAGMENT_SHADER\n"
2633 "#else // !MODE_DEFERREDGEOMETRY\n"
2634 "\n"
2635 "\n"
2636 "\n"
2637 "\n"
2638 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2639 "#ifdef VERTEX_SHADER\n"
2640 "void main\n"
2641 "(\n"
2642 "float4 gl_Vertex : POSITION,\n"
2643 "uniform float4x4 ModelViewProjectionMatrix,\n"
2644 "uniform float4x4 ModelViewMatrix,\n"
2645 "out float4 gl_Position : POSITION,\n"
2646 "out float4 ModelViewPosition : TEXCOORD0\n"
2647 ")\n"
2648 "{\n"
2649 "       ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2650 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2651 "}\n"
2652 "#endif // VERTEX_SHADER\n"
2653 "\n"
2654 "#ifdef FRAGMENT_SHADER\n"
2655 "void main\n"
2656 "(\n"
2657 "float2 Pixel : WPOS,\n"
2658 "float4 ModelViewPosition : TEXCOORD0,\n"
2659 "uniform float4x4 ViewToLight,\n"
2660 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2661 "uniform float3 LightPosition,\n"
2662 "uniform half2 PixelToScreenTexCoord,\n"
2663 "uniform half3 DeferredColor_Ambient,\n"
2664 "uniform half3 DeferredColor_Diffuse,\n"
2665 "#ifdef USESPECULAR\n"
2666 "uniform half3 DeferredColor_Specular,\n"
2667 "uniform half SpecularPower,\n"
2668 "#endif\n"
2669 "uniform sampler2D Texture_Attenuation,\n"
2670 "uniform sampler2D Texture_ScreenDepth,\n"
2671 "uniform sampler2D Texture_ScreenNormalMap,\n"
2672 "\n"
2673 "#ifdef USECUBEFILTER\n"
2674 "uniform samplerCUBE Texture_Cube,\n"
2675 "#endif\n"
2676 "\n"
2677 "#ifdef USESHADOWMAPRECT\n"
2678 "# ifdef USESHADOWSAMPLER\n"
2679 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2680 "# else\n"
2681 "uniform samplerRECT Texture_ShadowMapRect,\n"
2682 "# endif\n"
2683 "#endif\n"
2684 "\n"
2685 "#ifdef USESHADOWMAP2D\n"
2686 "# ifdef USESHADOWSAMPLER\n"
2687 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2688 "# else\n"
2689 "uniform sampler2D Texture_ShadowMap2D,\n"
2690 "# endif\n"
2691 "#endif\n"
2692 "\n"
2693 "#ifdef USESHADOWMAPVSDCT\n"
2694 "uniform samplerCUBE Texture_CubeProjection,\n"
2695 "#endif\n"
2696 "\n"
2697 "#ifdef USESHADOWMAPCUBE\n"
2698 "# ifdef USESHADOWSAMPLER\n"
2699 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2700 "# else\n"
2701 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2702 "# endif\n"
2703 "#endif\n"
2704 "\n"
2705 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2706 "uniform float2 ShadowMap_TextureScale,\n"
2707 "uniform float4 ShadowMap_Parameters,\n"
2708 "#endif\n"
2709 "\n"
2710 "out float4 gl_FragData0 : COLOR0,\n"
2711 "out float4 gl_FragData1 : COLOR1\n"
2712 ")\n"
2713 "{\n"
2714 "       // calculate viewspace pixel position\n"
2715 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2716 "       //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2717 "       float3 position;\n"
2718 "       position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2719 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2720 "       // decode viewspace pixel normal\n"
2721 "       half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2722 "       half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2723 "       // surfacenormal = pixel normal in viewspace\n"
2724 "       // LightVector = pixel to light in viewspace\n"
2725 "       // CubeVector = position in lightspace\n"
2726 "       // eyevector = pixel to view in viewspace\n"
2727 "       float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2728 "       half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2729 "#ifdef USEDIFFUSE\n"
2730 "       // calculate diffuse shading\n"
2731 "       half3 lightnormal = half3(normalize(LightPosition - position));\n"
2732 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2733 "#endif\n"
2734 "#ifdef USESPECULAR\n"
2735 "       // calculate directional shading\n"
2736 "       float3 eyevector = position * -1.0;\n"
2737 "#  ifdef USEEXACTSPECULARMATH\n"
2738 "       half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2739 "#  else\n"
2740 "       half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2741 "       half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2742 "#  endif\n"
2743 "#endif\n"
2744 "\n"
2745 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2746 "       fade *= ShadowMapCompare(CubeVector,\n"
2747 "# if defined(USESHADOWMAP2D)\n"
2748 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2749 "# endif\n"
2750 "# if defined(USESHADOWMAPRECT)\n"
2751 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2752 "# endif\n"
2753 "# if defined(USESHADOWMAPCUBE)\n"
2754 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2755 "# endif\n"
2756 "\n"
2757 "#ifdef USESHADOWMAPVSDCT\n"
2758 ", Texture_CubeProjection\n"
2759 "#endif\n"
2760 "       );\n"
2761 "#endif\n"
2762 "\n"
2763 "#ifdef USEDIFFUSE\n"
2764 "       gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2765 "#else\n"
2766 "       gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2767 "#endif\n"
2768 "#ifdef USESPECULAR\n"
2769 "       gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2770 "#else\n"
2771 "       gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2772 "#endif\n"
2773 "\n"
2774 "# ifdef USECUBEFILTER\n"
2775 "       float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2776 "       gl_FragData0.rgb *= cubecolor;\n"
2777 "       gl_FragData1.rgb *= cubecolor;\n"
2778 "# endif\n"
2779 "}\n"
2780 "#endif // FRAGMENT_SHADER\n"
2781 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2782 "\n"
2783 "\n"
2784 "\n"
2785 "\n"
2786 "#ifdef VERTEX_SHADER\n"
2787 "void main\n"
2788 "(\n"
2789 "float4 gl_Vertex : POSITION,\n"
2790 "uniform float4x4 ModelViewProjectionMatrix,\n"
2791 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2792 "float4 gl_Color : COLOR0,\n"
2793 "#endif\n"
2794 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2795 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2796 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2797 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2798 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2799 "\n"
2800 "uniform float3 EyePosition,\n"
2801 "uniform float4x4 TexMatrix,\n"
2802 "#ifdef USEVERTEXTEXTUREBLEND\n"
2803 "uniform float4x4 BackgroundTexMatrix,\n"
2804 "#endif\n"
2805 "#ifdef MODE_LIGHTSOURCE\n"
2806 "uniform float4x4 ModelToLight,\n"
2807 "#endif\n"
2808 "#ifdef MODE_LIGHTSOURCE\n"
2809 "uniform float3 LightPosition,\n"
2810 "#endif\n"
2811 "#ifdef MODE_LIGHTDIRECTION\n"
2812 "uniform float3 LightDir,\n"
2813 "#endif\n"
2814 "uniform float4 FogPlane,\n"
2815 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2816 "uniform float3 LightPosition,\n"
2817 "#endif\n"
2818 "#ifdef USESHADOWMAPORTHO\n"
2819 "uniform float4x4 ShadowMapMatrix,\n"
2820 "#endif\n"
2821 "\n"
2822 "out float4 gl_FrontColor : COLOR,\n"
2823 "out float4 TexCoordBoth : TEXCOORD0,\n"
2824 "#ifdef USELIGHTMAP\n"
2825 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2826 "#endif\n"
2827 "#ifdef USEEYEVECTOR\n"
2828 "out float3 EyeVector : TEXCOORD2,\n"
2829 "#endif\n"
2830 "#ifdef USEREFLECTION\n"
2831 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2832 "#endif\n"
2833 "#ifdef USEFOG\n"
2834 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2835 "#endif\n"
2836 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2837 "out float3 LightVector : TEXCOORD1,\n"
2838 "#endif\n"
2839 "#ifdef MODE_LIGHTSOURCE\n"
2840 "out float3 CubeVector : TEXCOORD3,\n"
2841 "#endif\n"
2842 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2843 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2844 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2845 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2846 "#endif\n"
2847 "#ifdef USESHADOWMAPORTHO\n"
2848 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2849 "#endif\n"
2850 "out float4 gl_Position : POSITION\n"
2851 ")\n"
2852 "{\n"
2853 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2854 "       gl_FrontColor = gl_Color;\n"
2855 "#endif\n"
2856 "       // copy the surface texcoord\n"
2857 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2858 "#ifdef USEVERTEXTEXTUREBLEND\n"
2859 "       TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2860 "#endif\n"
2861 "#ifdef USELIGHTMAP\n"
2862 "       TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2863 "#endif\n"
2864 "\n"
2865 "#ifdef MODE_LIGHTSOURCE\n"
2866 "       // transform vertex position into light attenuation/cubemap space\n"
2867 "       // (-1 to +1 across the light box)\n"
2868 "       CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2869 "\n"
2870 "# ifdef USEDIFFUSE\n"
2871 "       // transform unnormalized light direction into tangent space\n"
2872 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
2873 "       //  normalize it per pixel)\n"
2874 "       float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2875 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2876 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2877 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2878 "# endif\n"
2879 "#endif\n"
2880 "\n"
2881 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2882 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2883 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2884 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2885 "#endif\n"
2886 "\n"
2887 "       // transform unnormalized eye direction into tangent space\n"
2888 "#ifdef USEEYEVECTOR\n"
2889 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2890 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2891 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2892 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2893 "#endif\n"
2894 "\n"
2895 "#ifdef USEFOG\n"
2896 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2897 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2898 "#endif\n"
2899 "\n"
2900 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2901 "       VectorS = gl_MultiTexCoord1.xyz;\n"
2902 "       VectorT = gl_MultiTexCoord2.xyz;\n"
2903 "       VectorR = gl_MultiTexCoord3.xyz;\n"
2904 "#endif\n"
2905 "\n"
2906 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2907 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2908 "\n"
2909 "#ifdef USESHADOWMAPORTHO\n"
2910 "       ShadowMapTC = float3(mul(ShadowMapMatrix, gl_Position));\n"
2911 "#endif\n"
2912 "\n"
2913 "#ifdef USEREFLECTION\n"
2914 "       ModelViewProjectionPosition = gl_Position;\n"
2915 "#endif\n"
2916 "}\n"
2917 "#endif // VERTEX_SHADER\n"
2918 "\n"
2919 "\n"
2920 "\n"
2921 "\n"
2922 "#ifdef FRAGMENT_SHADER\n"
2923 "void main\n"
2924 "(\n"
2925 "#ifdef USEDEFERREDLIGHTMAP\n"
2926 "float2 Pixel : WPOS,\n"
2927 "#endif\n"
2928 "float4 gl_FrontColor : COLOR,\n"
2929 "float4 TexCoordBoth : TEXCOORD0,\n"
2930 "#ifdef USELIGHTMAP\n"
2931 "float2 TexCoordLightmap : TEXCOORD1,\n"
2932 "#endif\n"
2933 "#ifdef USEEYEVECTOR\n"
2934 "float3 EyeVector : TEXCOORD2,\n"
2935 "#endif\n"
2936 "#ifdef USEREFLECTION\n"
2937 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2938 "#endif\n"
2939 "#ifdef USEFOG\n"
2940 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2941 "#endif\n"
2942 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2943 "float3 LightVector : TEXCOORD1,\n"
2944 "#endif\n"
2945 "#ifdef MODE_LIGHTSOURCE\n"
2946 "float3 CubeVector : TEXCOORD3,\n"
2947 "#endif\n"
2948 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2949 "float4 ModelViewPosition : TEXCOORD0,\n"
2950 "#endif\n"
2951 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2952 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2953 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2954 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2955 "#endif\n"
2956 "#ifdef USESHADOWMAPORTHO\n"
2957 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2958 "#endif\n"
2959 "\n"
2960 "uniform sampler2D Texture_Normal,\n"
2961 "uniform sampler2D Texture_Color,\n"
2962 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2963 "uniform sampler2D Texture_Gloss,\n"
2964 "#endif\n"
2965 "#ifdef USEGLOW\n"
2966 "uniform sampler2D Texture_Glow,\n"
2967 "#endif\n"
2968 "#ifdef USEVERTEXTEXTUREBLEND\n"
2969 "uniform sampler2D Texture_SecondaryNormal,\n"
2970 "uniform sampler2D Texture_SecondaryColor,\n"
2971 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2972 "uniform sampler2D Texture_SecondaryGloss,\n"
2973 "#endif\n"
2974 "#ifdef USEGLOW\n"
2975 "uniform sampler2D Texture_SecondaryGlow,\n"
2976 "#endif\n"
2977 "#endif\n"
2978 "#ifdef USECOLORMAPPING\n"
2979 "uniform sampler2D Texture_Pants,\n"
2980 "uniform sampler2D Texture_Shirt,\n"
2981 "#endif\n"
2982 "#ifdef USEFOG\n"
2983 "uniform sampler2D Texture_FogHeightTexture,\n"
2984 "uniform sampler2D Texture_FogMask,\n"
2985 "#endif\n"
2986 "#ifdef USELIGHTMAP\n"
2987 "uniform sampler2D Texture_Lightmap,\n"
2988 "#endif\n"
2989 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2990 "uniform sampler2D Texture_Deluxemap,\n"
2991 "#endif\n"
2992 "#ifdef USEREFLECTION\n"
2993 "uniform sampler2D Texture_Reflection,\n"
2994 "#endif\n"
2995 "\n"
2996 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2997 "uniform sampler2D Texture_ScreenDepth,\n"
2998 "uniform sampler2D Texture_ScreenNormalMap,\n"
2999 "#endif\n"
3000 "#ifdef USEDEFERREDLIGHTMAP\n"
3001 "uniform sampler2D Texture_ScreenDiffuse,\n"
3002 "uniform sampler2D Texture_ScreenSpecular,\n"
3003 "#endif\n"
3004 "\n"
3005 "#ifdef USECOLORMAPPING\n"
3006 "uniform half3 Color_Pants,\n"
3007 "uniform half3 Color_Shirt,\n"
3008 "#endif\n"
3009 "#ifdef USEFOG\n"
3010 "uniform float3 FogColor,\n"
3011 "uniform float FogRangeRecip,\n"
3012 "uniform float FogPlaneViewDist,\n"
3013 "uniform float FogHeightFade,\n"
3014 "#endif\n"
3015 "\n"
3016 "#ifdef USEOFFSETMAPPING\n"
3017 "uniform float OffsetMapping_Scale,\n"
3018 "#endif\n"
3019 "\n"
3020 "#ifdef USEDEFERREDLIGHTMAP\n"
3021 "uniform half2 PixelToScreenTexCoord,\n"
3022 "uniform half3 DeferredMod_Diffuse,\n"
3023 "uniform half3 DeferredMod_Specular,\n"
3024 "#endif\n"
3025 "uniform half3 Color_Ambient,\n"
3026 "uniform half3 Color_Diffuse,\n"
3027 "uniform half3 Color_Specular,\n"
3028 "uniform half SpecularPower,\n"
3029 "#ifdef USEGLOW\n"
3030 "uniform half3 Color_Glow,\n"
3031 "#endif\n"
3032 "uniform half Alpha,\n"
3033 "#ifdef USEREFLECTION\n"
3034 "uniform float4 DistortScaleRefractReflect,\n"
3035 "uniform float4 ScreenScaleRefractReflect,\n"
3036 "uniform float4 ScreenCenterRefractReflect,\n"
3037 "uniform half4 ReflectColor,\n"
3038 "#endif\n"
3039 "#ifdef USEREFLECTCUBE\n"
3040 "uniform float4x4 ModelToReflectCube,\n"
3041 "uniform sampler2D Texture_ReflectMask,\n"
3042 "uniform samplerCUBE Texture_ReflectCube,\n"
3043 "#endif\n"
3044 "#ifdef MODE_LIGHTDIRECTION\n"
3045 "uniform half3 LightColor,\n"
3046 "#endif\n"
3047 "#ifdef MODE_LIGHTSOURCE\n"
3048 "uniform half3 LightColor,\n"
3049 "#endif\n"
3050 "\n"
3051 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3052 "uniform sampler2D Texture_Attenuation,\n"
3053 "uniform samplerCUBE Texture_Cube,\n"
3054 "#endif\n"
3055 "\n"
3056 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3057 "\n"
3058 "#ifdef USESHADOWMAPRECT\n"
3059 "# ifdef USESHADOWSAMPLER\n"
3060 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
3061 "# else\n"
3062 "uniform samplerRECT Texture_ShadowMapRect,\n"
3063 "# endif\n"
3064 "#endif\n"
3065 "\n"
3066 "#ifdef USESHADOWMAP2D\n"
3067 "# ifdef USESHADOWSAMPLER\n"
3068 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
3069 "# else\n"
3070 "uniform sampler2D Texture_ShadowMap2D,\n"
3071 "# endif\n"
3072 "#endif\n"
3073 "\n"
3074 "#ifdef USESHADOWMAPVSDCT\n"
3075 "uniform samplerCUBE Texture_CubeProjection,\n"
3076 "#endif\n"
3077 "\n"
3078 "#ifdef USESHADOWMAPCUBE\n"
3079 "# ifdef USESHADOWSAMPLER\n"
3080 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
3081 "# else\n"
3082 "uniform samplerCUBE Texture_ShadowMapCube,\n"
3083 "# endif\n"
3084 "#endif\n"
3085 "\n"
3086 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3087 "uniform float2 ShadowMap_TextureScale,\n"
3088 "uniform float4 ShadowMap_Parameters,\n"
3089 "#endif\n"
3090 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3091 "\n"
3092 "out float4 gl_FragColor : COLOR\n"
3093 ")\n"
3094 "{\n"
3095 "       float2 TexCoord = TexCoordBoth.xy;\n"
3096 "#ifdef USEVERTEXTEXTUREBLEND\n"
3097 "       float2 TexCoord2 = TexCoordBoth.zw;\n"
3098 "#endif\n"
3099 "#ifdef USEOFFSETMAPPING\n"
3100 "       // apply offsetmapping\n"
3101 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3102 "#define TexCoord TexCoordOffset\n"
3103 "#endif\n"
3104 "\n"
3105 "       // combine the diffuse textures (base, pants, shirt)\n"
3106 "       half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3107 "#ifdef USEALPHAKILL\n"
3108 "       if (color.a < 0.5)\n"
3109 "               discard;\n"
3110 "#endif\n"
3111 "       color.a *= Alpha;\n"
3112 "#ifdef USECOLORMAPPING\n"
3113 "       color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
3114 "#endif\n"
3115 "#ifdef USEVERTEXTEXTUREBLEND\n"
3116 "       float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3117 "       //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3118 "       //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3119 "       color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
3120 "       color.a = 1.0;\n"
3121 "       //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
3122 "#endif\n"
3123 "\n"
3124 "       // get the surface normal\n"
3125 "#ifdef USEVERTEXTEXTUREBLEND\n"
3126 "       half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3127 "#else\n"
3128 "       half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
3129 "#endif\n"
3130 "\n"
3131 "       // get the material colors\n"
3132 "       half3 diffusetex = color.rgb;\n"
3133 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3134 "# ifdef USEVERTEXTEXTUREBLEND\n"
3135 "       half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
3136 "# else\n"
3137 "       half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3138 "# endif\n"
3139 "#endif\n"
3140 "\n"
3141 "#ifdef USEREFLECTCUBE\n"
3142 "       float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3143 "       float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3144 "       float3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
3145 "       diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
3146 "#endif\n"
3147 "\n"
3148 "\n"
3149 "\n"
3150 "\n"
3151 "#ifdef MODE_LIGHTSOURCE\n"
3152 "       // light source\n"
3153 "#ifdef USEDIFFUSE\n"
3154 "       half3 lightnormal = half3(normalize(LightVector));\n"
3155 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3156 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3157 "#ifdef USESPECULAR\n"
3158 "#ifdef USEEXACTSPECULARMATH\n"
3159 "       half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3160 "#else\n"
3161 "       half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3162 "       half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3163 "#endif\n"
3164 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3165 "#endif\n"
3166 "#else\n"
3167 "       color.rgb = diffusetex * Color_Ambient;\n"
3168 "#endif\n"
3169 "       color.rgb *= LightColor;\n"
3170 "       color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3171 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3172 "       color.rgb *= ShadowMapCompare(CubeVector,\n"
3173 "# if defined(USESHADOWMAP2D)\n"
3174 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3175 "# endif\n"
3176 "# if defined(USESHADOWMAPRECT)\n"
3177 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3178 "# endif\n"
3179 "# if defined(USESHADOWMAPCUBE)\n"
3180 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3181 "# endif\n"
3182 "\n"
3183 "#ifdef USESHADOWMAPVSDCT\n"
3184 ", Texture_CubeProjection\n"
3185 "#endif\n"
3186 "       );\n"
3187 "\n"
3188 "#endif\n"
3189 "# ifdef USECUBEFILTER\n"
3190 "       color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3191 "# endif\n"
3192 "#endif // MODE_LIGHTSOURCE\n"
3193 "\n"
3194 "\n"
3195 "\n"
3196 "\n"
3197 "#ifdef MODE_LIGHTDIRECTION\n"
3198 "#define SHADING\n"
3199 "#ifdef USEDIFFUSE\n"
3200 "       half3 lightnormal = half3(normalize(LightVector));\n"
3201 "#endif\n"
3202 "#define lightcolor LightColor\n"
3203 "#endif // MODE_LIGHTDIRECTION\n"
3204 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3205 "#define SHADING\n"
3206 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3207 "       half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3208 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3209 "       // convert modelspace light vector to tangentspace\n"
3210 "       half3 lightnormal;\n"
3211 "       lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3212 "       lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3213 "       lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3214 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3215 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3216 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3217 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3218 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3219 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3220 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3221 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3222 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3223 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3224 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3225 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3226 "#define SHADING\n"
3227 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3228 "       half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3229 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3230 "#endif\n"
3231 "\n"
3232 "\n"
3233 "\n"
3234 "\n"
3235 "#ifdef MODE_FAKELIGHT\n"
3236 "#define SHADING\n"
3237 "half3 lightnormal = half3(normalize(EyeVector));\n"
3238 "half3 lightcolor = half3(1.0);\n"
3239 "#endif // MODE_FAKELIGHT\n"
3240 "\n"
3241 "\n"
3242 "\n"
3243 "\n"
3244 "#ifdef MODE_LIGHTMAP\n"
3245 "       color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3246 "#endif // MODE_LIGHTMAP\n"
3247 "#ifdef MODE_VERTEXCOLOR\n"
3248 "       color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3249 "#endif // MODE_VERTEXCOLOR\n"
3250 "#ifdef MODE_FLATCOLOR\n"
3251 "       color.rgb = diffusetex * Color_Ambient;\n"
3252 "#endif // MODE_FLATCOLOR\n"
3253 "\n"
3254 "\n"
3255 "\n"
3256 "\n"
3257 "#ifdef SHADING\n"
3258 "# ifdef USEDIFFUSE\n"
3259 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3260 "#  ifdef USESPECULAR\n"
3261 "#   ifdef USEEXACTSPECULARMATH\n"
3262 "       half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3263 "#   else\n"
3264 "       half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3265 "       half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3266 "#   endif\n"
3267 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3268 "#  else\n"
3269 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3270 "#  endif\n"
3271 "# else\n"
3272 "       color.rgb = diffusetex * Color_Ambient;\n"
3273 "# endif\n"
3274 "#endif\n"
3275 "\n"
3276 "#ifdef USESHADOWMAPORTHO\n"
3277 "       color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3278 "# if defined(USESHADOWMAP2D)\n"
3279 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3280 "# endif\n"
3281 "# if defined(USESHADOWMAPRECT)\n"
3282 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3283 "# endif\n"
3284 "       );\n"
3285 "#endif\n"
3286 "\n"
3287 "#ifdef USEDEFERREDLIGHTMAP\n"
3288 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3289 "       color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3290 "       color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3291 "#endif\n"
3292 "\n"
3293 "#ifdef USEGLOW\n"
3294 "#ifdef USEVERTEXTEXTUREBLEND\n"
3295 "       color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3296 "#else\n"
3297 "       color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3298 "#endif\n"
3299 "#endif\n"
3300 "\n"
3301 "#ifdef USEFOG\n"
3302 "       color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3303 "#endif\n"
3304 "\n"
3305 "       // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
3306 "#ifdef USEREFLECTION\n"
3307 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3308 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3309 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3310 "       float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3311 "       // FIXME temporary hack to detect the case that the reflection\n"
3312 "       // gets blackened at edges due to leaving the area that contains actual\n"
3313 "       // content.\n"
3314 "       // Remove this 'ack once we have a better way to stop this thing from\n"
3315 "       // 'appening.\n"
3316 "       float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3317 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3318 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3319 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3320 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3321 "       color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3322 "#endif\n"
3323 "\n"
3324 "       gl_FragColor = float4(color);\n"
3325 "}\n"
3326 "#endif // FRAGMENT_SHADER\n"
3327 "\n"
3328 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3329 "#endif // !MODE_DEFERREDGEOMETRY\n"
3330 "#endif // !MODE_WATER\n"
3331 "#endif // !MODE_REFRACTION\n"
3332 "#endif // !MODE_BLOOMBLUR\n"
3333 "#endif // !MODE_GENERIC\n"
3334 "#endif // !MODE_POSTPROCESS\n"
3335 "#endif // !MODE_SHOWDEPTH\n"
3336 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3337 ;
3338
3339 char *glslshaderstring = NULL;
3340 char *cgshaderstring = NULL;
3341
3342 //=======================================================================================================================================================
3343
3344 typedef struct shaderpermutationinfo_s
3345 {
3346         const char *pretext;
3347         const char *name;
3348 }
3349 shaderpermutationinfo_t;
3350
3351 typedef struct shadermodeinfo_s
3352 {
3353         const char *vertexfilename;
3354         const char *geometryfilename;
3355         const char *fragmentfilename;
3356         const char *pretext;
3357         const char *name;
3358 }
3359 shadermodeinfo_t;
3360
3361 typedef enum shaderpermutation_e
3362 {
3363         SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3364         SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3365         SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3366         SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3367         SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3368         SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3369         SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3370         SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3371         SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3372         SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3373         SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3374         SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3375         SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3376         SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3377         SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3378         SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3379         SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3380         SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3381         SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3382         SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3383         SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3384         SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3385         SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3386         SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3387         SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3388         SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3389         SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3390         SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3391         SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3392         SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3393         SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3394 }
3395 shaderpermutation_t;
3396
3397 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3398 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3399 {
3400         {"#define USEDIFFUSE\n", " diffuse"},
3401         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3402         {"#define USEVIEWTINT\n", " viewtint"},
3403         {"#define USECOLORMAPPING\n", " colormapping"},
3404         {"#define USESATURATION\n", " saturation"},
3405         {"#define USEFOGINSIDE\n", " foginside"},
3406         {"#define USEFOGOUTSIDE\n", " fogoutside"},
3407         {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3408         {"#define USEGAMMARAMPS\n", " gammaramps"},
3409         {"#define USECUBEFILTER\n", " cubefilter"},
3410         {"#define USEGLOW\n", " glow"},
3411         {"#define USEBLOOM\n", " bloom"},
3412         {"#define USESPECULAR\n", " specular"},
3413         {"#define USEPOSTPROCESSING\n", " postprocessing"},
3414         {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3415         {"#define USEREFLECTION\n", " reflection"},
3416         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3417         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3418         {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3419         {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3420         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3421         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3422         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3423         {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3424         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3425         {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3426         {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3427         {"#define USEALPHAKILL\n", " alphakill"},
3428         {"#define USEREFLECTCUBE\n", " reflectcube"},
3429 };
3430
3431 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3432 typedef enum shadermode_e
3433 {
3434         SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3435         SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3436         SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3437         SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3438         SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3439         SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3440         SHADERMODE_FAKELIGHT, ///< (fakelight) modulate texture by "fake" lighting (no lightmaps, no nothing)
3441         SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3442         SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3443         SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3444         SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3445         SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3446         SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3447         SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3448         SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3449         SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3450         SHADERMODE_COUNT
3451 }
3452 shadermode_t;
3453
3454 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3455 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3456 {
3457         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3458         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3459         {"glsl/default.glsl", NULL, NULL               , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3460         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3461         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3462         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3463         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FAKELIGHT\n", " fakelight"},
3464         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3465         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3466         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3467         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3468         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3469         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3470         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3471         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3472         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3473 };
3474
3475 #ifdef SUPPORTCG
3476 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3477 {
3478         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3479         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3480         {"cg/default.cg", NULL, NULL           , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3481         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3482         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3483         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3484         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FAKELIGHT\n", " fakelight"},
3485         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3486         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3487         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3488         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3489         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3490         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3491         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3492         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3493         {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3494 };
3495 #endif
3496
3497 struct r_glsl_permutation_s;
3498 typedef struct r_glsl_permutation_s
3499 {
3500         /// hash lookup data
3501         struct r_glsl_permutation_s *hashnext;
3502         unsigned int mode;
3503         unsigned int permutation;
3504
3505         /// indicates if we have tried compiling this permutation already
3506         qboolean compiled;
3507         /// 0 if compilation failed
3508         int program;
3509         /// locations of detected uniforms in program object, or -1 if not found
3510         int loc_Texture_First;
3511         int loc_Texture_Second;
3512         int loc_Texture_GammaRamps;
3513         int loc_Texture_Normal;
3514         int loc_Texture_Color;
3515         int loc_Texture_Gloss;
3516         int loc_Texture_Glow;
3517         int loc_Texture_SecondaryNormal;
3518         int loc_Texture_SecondaryColor;
3519         int loc_Texture_SecondaryGloss;
3520         int loc_Texture_SecondaryGlow;
3521         int loc_Texture_Pants;
3522         int loc_Texture_Shirt;
3523         int loc_Texture_FogHeightTexture;
3524         int loc_Texture_FogMask;
3525         int loc_Texture_Lightmap;
3526         int loc_Texture_Deluxemap;
3527         int loc_Texture_Attenuation;
3528         int loc_Texture_Cube;
3529         int loc_Texture_Refraction;
3530         int loc_Texture_Reflection;
3531         int loc_Texture_ShadowMapRect;
3532         int loc_Texture_ShadowMapCube;
3533         int loc_Texture_ShadowMap2D;
3534         int loc_Texture_CubeProjection;
3535         int loc_Texture_ScreenDepth;
3536         int loc_Texture_ScreenNormalMap;
3537         int loc_Texture_ScreenDiffuse;
3538         int loc_Texture_ScreenSpecular;
3539         int loc_Texture_ReflectMask;
3540         int loc_Texture_ReflectCube;
3541         int loc_Alpha;
3542         int loc_BloomBlur_Parameters;
3543         int loc_ClientTime;
3544         int loc_Color_Ambient;
3545         int loc_Color_Diffuse;
3546         int loc_Color_Specular;
3547         int loc_Color_Glow;
3548         int loc_Color_Pants;
3549         int loc_Color_Shirt;
3550         int loc_DeferredColor_Ambient;
3551         int loc_DeferredColor_Diffuse;
3552         int loc_DeferredColor_Specular;
3553         int loc_DeferredMod_Diffuse;
3554         int loc_DeferredMod_Specular;
3555         int loc_DistortScaleRefractReflect;
3556         int loc_EyePosition;
3557         int loc_FogColor;
3558         int loc_FogHeightFade;
3559         int loc_FogPlane;
3560         int loc_FogPlaneViewDist;
3561         int loc_FogRangeRecip;
3562         int loc_LightColor;
3563         int loc_LightDir;
3564         int loc_LightPosition;
3565         int loc_OffsetMapping_Scale;
3566         int loc_PixelSize;
3567         int loc_ReflectColor;
3568         int loc_ReflectFactor;
3569         int loc_ReflectOffset;
3570         int loc_RefractColor;
3571         int loc_Saturation;
3572         int loc_ScreenCenterRefractReflect;
3573         int loc_ScreenScaleRefractReflect;
3574         int loc_ScreenToDepth;
3575         int loc_ShadowMap_Parameters;
3576         int loc_ShadowMap_TextureScale;
3577         int loc_SpecularPower;
3578         int loc_UserVec1;
3579         int loc_UserVec2;
3580         int loc_UserVec3;
3581         int loc_UserVec4;
3582         int loc_ViewTintColor;
3583         int loc_ViewToLight;
3584         int loc_ModelToLight;
3585         int loc_TexMatrix;
3586         int loc_BackgroundTexMatrix;
3587         int loc_ModelViewProjectionMatrix;
3588         int loc_ModelViewMatrix;
3589         int loc_PixelToScreenTexCoord;
3590         int loc_ModelToReflectCube;
3591         int loc_ShadowMapMatrix;        
3592 }
3593 r_glsl_permutation_t;
3594
3595 #define SHADERPERMUTATION_HASHSIZE 256
3596
3597 /// information about each possible shader permutation
3598 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3599 /// currently selected permutation
3600 r_glsl_permutation_t *r_glsl_permutation;
3601 /// storage for permutations linked in the hash table
3602 memexpandablearray_t r_glsl_permutationarray;
3603
3604 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3605 {
3606         //unsigned int hashdepth = 0;
3607         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3608         r_glsl_permutation_t *p;
3609         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3610         {
3611                 if (p->mode == mode && p->permutation == permutation)
3612                 {
3613                         //if (hashdepth > 10)
3614                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3615                         return p;
3616                 }
3617                 //hashdepth++;
3618         }
3619         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3620         p->mode = mode;
3621         p->permutation = permutation;
3622         p->hashnext = r_glsl_permutationhash[mode][hashindex];
3623         r_glsl_permutationhash[mode][hashindex] = p;
3624         //if (hashdepth > 10)
3625         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3626         return p;
3627 }
3628
3629 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3630 {
3631         char *shaderstring;
3632         if (!filename || !filename[0])
3633                 return NULL;
3634         if (!strcmp(filename, "glsl/default.glsl"))
3635         {
3636                 if (!glslshaderstring)
3637                 {
3638                         glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3639                         if (glslshaderstring)
3640                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
3641                         else
3642                                 glslshaderstring = (char *)builtinshaderstring;
3643                 }
3644                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3645                 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3646                 return shaderstring;
3647         }
3648         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3649         if (shaderstring)
3650         {
3651                 if (printfromdisknotice)
3652                         Con_DPrintf("from disk %s... ", filename);
3653                 return shaderstring;
3654         }
3655         return shaderstring;
3656 }
3657
3658 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3659 {
3660         int i;
3661         shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3662         int vertstrings_count = 0;
3663         int geomstrings_count = 0;
3664         int fragstrings_count = 0;
3665         char *vertexstring, *geometrystring, *fragmentstring;
3666         const char *vertstrings_list[32+3];
3667         const char *geomstrings_list[32+3];
3668         const char *fragstrings_list[32+3];
3669         char permutationname[256];
3670
3671         if (p->compiled)
3672                 return;
3673         p->compiled = true;
3674         p->program = 0;
3675
3676         permutationname[0] = 0;
3677         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
3678         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3679         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3680
3681         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3682
3683         // the first pretext is which type of shader to compile as
3684         // (later these will all be bound together as a program object)
3685         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3686         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3687         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3688
3689         // the second pretext is the mode (for example a light source)
3690         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3691         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3692         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3693         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3694
3695         // now add all the permutation pretexts
3696         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3697         {
3698                 if (permutation & (1<<i))
3699                 {
3700                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3701                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3702                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3703                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3704                 }
3705                 else
3706                 {
3707                         // keep line numbers correct
3708                         vertstrings_list[vertstrings_count++] = "\n";
3709                         geomstrings_list[geomstrings_count++] = "\n";
3710                         fragstrings_list[fragstrings_count++] = "\n";
3711                 }
3712         }
3713
3714         // now append the shader text itself
3715         vertstrings_list[vertstrings_count++] = vertexstring;
3716         geomstrings_list[geomstrings_count++] = geometrystring;
3717         fragstrings_list[fragstrings_count++] = fragmentstring;
3718
3719         // if any sources were NULL, clear the respective list
3720         if (!vertexstring)
3721                 vertstrings_count = 0;
3722         if (!geometrystring)
3723                 geomstrings_count = 0;
3724         if (!fragmentstring)
3725                 fragstrings_count = 0;
3726
3727         // compile the shader program
3728         if (vertstrings_count + geomstrings_count + fragstrings_count)
3729                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3730         if (p->program)
3731         {
3732                 CHECKGLERROR
3733                 qglUseProgramObjectARB(p->program);CHECKGLERROR
3734                 // look up all the uniform variable names we care about, so we don't
3735                 // have to look them up every time we set them
3736
3737                 p->loc_Texture_First              = qglGetUniformLocationARB(p->program, "Texture_First");
3738                 p->loc_Texture_Second             = qglGetUniformLocationARB(p->program, "Texture_Second");
3739                 p->loc_Texture_GammaRamps         = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3740                 p->loc_Texture_Normal             = qglGetUniformLocationARB(p->program, "Texture_Normal");
3741                 p->loc_Texture_Color              = qglGetUniformLocationARB(p->program, "Texture_Color");
3742                 p->loc_Texture_Gloss              = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3743                 p->loc_Texture_Glow               = qglGetUniformLocationARB(p->program, "Texture_Glow");
3744                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3745                 p->loc_Texture_SecondaryColor     = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3746                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3747                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3748                 p->loc_Texture_Pants              = qglGetUniformLocationARB(p->program, "Texture_Pants");
3749                 p->loc_Texture_Shirt              = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3750                 p->loc_Texture_FogHeightTexture   = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3751                 p->loc_Texture_FogMask            = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3752                 p->loc_Texture_Lightmap           = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3753                 p->loc_Texture_Deluxemap          = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3754                 p->loc_Texture_Attenuation        = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3755                 p->loc_Texture_Cube               = qglGetUniformLocationARB(p->program, "Texture_Cube");
3756                 p->loc_Texture_Refraction         = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3757                 p->loc_Texture_Reflection         = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3758                 p->loc_Texture_ShadowMapRect      = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3759                 p->loc_Texture_ShadowMapCube      = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3760                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3761                 p->loc_Texture_CubeProjection     = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3762                 p->loc_Texture_ScreenDepth        = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3763                 p->loc_Texture_ScreenNormalMap    = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3764                 p->loc_Texture_ScreenDiffuse      = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3765                 p->loc_Texture_ScreenSpecular     = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3766                 p->loc_Texture_ReflectMask        = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3767                 p->loc_Texture_ReflectCube        = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3768                 p->loc_Alpha                      = qglGetUniformLocationARB(p->program, "Alpha");
3769                 p->loc_BloomBlur_Parameters       = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3770                 p->loc_ClientTime                 = qglGetUniformLocationARB(p->program, "ClientTime");
3771                 p->loc_Color_Ambient              = qglGetUniformLocationARB(p->program, "Color_Ambient");
3772                 p->loc_Color_Diffuse              = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3773                 p->loc_Color_Specular             = qglGetUniformLocationARB(p->program, "Color_Specular");
3774                 p->loc_Color_Glow                 = qglGetUniformLocationARB(p->program, "Color_Glow");
3775                 p->loc_Color_Pants                = qglGetUniformLocationARB(p->program, "Color_Pants");
3776                 p->loc_Color_Shirt                = qglGetUniformLocationARB(p->program, "Color_Shirt");
3777                 p->loc_DeferredColor_Ambient      = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3778                 p->loc_DeferredColor_Diffuse      = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3779                 p->loc_DeferredColor_Specular     = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3780                 p->loc_DeferredMod_Diffuse        = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3781                 p->loc_DeferredMod_Specular       = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3782                 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3783                 p->loc_EyePosition                = qglGetUniformLocationARB(p->program, "EyePosition");
3784                 p->loc_FogColor                   = qglGetUniformLocationARB(p->program, "FogColor");
3785                 p->loc_FogHeightFade              = qglGetUniformLocationARB(p->program, "FogHeightFade");
3786                 p->loc_FogPlane                   = qglGetUniformLocationARB(p->program, "FogPlane");
3787                 p->loc_FogPlaneViewDist           = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3788                 p->loc_FogRangeRecip              = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3789                 p->loc_LightColor                 = qglGetUniformLocationARB(p->program, "LightColor");
3790                 p->loc_LightDir                   = qglGetUniformLocationARB(p->program, "LightDir");
3791                 p->loc_LightPosition              = qglGetUniformLocationARB(p->program, "LightPosition");
3792                 p->loc_OffsetMapping_Scale        = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3793                 p->loc_PixelSize                  = qglGetUniformLocationARB(p->program, "PixelSize");
3794                 p->loc_ReflectColor               = qglGetUniformLocationARB(p->program, "ReflectColor");
3795                 p->loc_ReflectFactor              = qglGetUniformLocationARB(p->program, "ReflectFactor");
3796                 p->loc_ReflectOffset              = qglGetUniformLocationARB(p->program, "ReflectOffset");
3797                 p->loc_RefractColor               = qglGetUniformLocationARB(p->program, "RefractColor");
3798                 p->loc_Saturation                 = qglGetUniformLocationARB(p->program, "Saturation");
3799                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3800                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3801                 p->loc_ScreenToDepth              = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3802                 p->loc_ShadowMap_Parameters       = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3803                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3804                 p->loc_SpecularPower              = qglGetUniformLocationARB(p->program, "SpecularPower");
3805                 p->loc_UserVec1                   = qglGetUniformLocationARB(p->program, "UserVec1");
3806                 p->loc_UserVec2                   = qglGetUniformLocationARB(p->program, "UserVec2");
3807                 p->loc_UserVec3                   = qglGetUniformLocationARB(p->program, "UserVec3");
3808                 p->loc_UserVec4                   = qglGetUniformLocationARB(p->program, "UserVec4");
3809                 p->loc_ViewTintColor              = qglGetUniformLocationARB(p->program, "ViewTintColor");
3810                 p->loc_ViewToLight                = qglGetUniformLocationARB(p->program, "ViewToLight");
3811                 p->loc_ModelToLight               = qglGetUniformLocationARB(p->program, "ModelToLight");
3812                 p->loc_TexMatrix                  = qglGetUniformLocationARB(p->program, "TexMatrix");
3813                 p->loc_BackgroundTexMatrix        = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3814                 p->loc_ModelViewMatrix            = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3815                 p->loc_ModelViewProjectionMatrix  = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3816                 p->loc_PixelToScreenTexCoord      = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3817                 p->loc_ModelToReflectCube         = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3818                 p->loc_ShadowMapMatrix            = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");            
3819                 // initialize the samplers to refer to the texture units we use
3820                 if (p->loc_Texture_First           >= 0) qglUniform1iARB(p->loc_Texture_First          , GL20TU_FIRST);
3821                 if (p->loc_Texture_Second          >= 0) qglUniform1iARB(p->loc_Texture_Second         , GL20TU_SECOND);
3822                 if (p->loc_Texture_GammaRamps      >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps     , GL20TU_GAMMARAMPS);
3823                 if (p->loc_Texture_Normal          >= 0) qglUniform1iARB(p->loc_Texture_Normal         , GL20TU_NORMAL);
3824                 if (p->loc_Texture_Color           >= 0) qglUniform1iARB(p->loc_Texture_Color          , GL20TU_COLOR);
3825                 if (p->loc_Texture_Gloss           >= 0) qglUniform1iARB(p->loc_Texture_Gloss          , GL20TU_GLOSS);
3826                 if (p->loc_Texture_Glow            >= 0) qglUniform1iARB(p->loc_Texture_Glow           , GL20TU_GLOW);
3827                 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3828                 if (p->loc_Texture_SecondaryColor  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3829                 if (p->loc_Texture_SecondaryGloss  >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3830                 if (p->loc_Texture_SecondaryGlow   >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow  , GL20TU_SECONDARY_GLOW);
3831                 if (p->loc_Texture_Pants           >= 0) qglUniform1iARB(p->loc_Texture_Pants          , GL20TU_PANTS);
3832                 if (p->loc_Texture_Shirt           >= 0) qglUniform1iARB(p->loc_Texture_Shirt          , GL20TU_SHIRT);
3833                 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3834                 if (p->loc_Texture_FogMask         >= 0) qglUniform1iARB(p->loc_Texture_FogMask        , GL20TU_FOGMASK);
3835                 if (p->loc_Texture_Lightmap        >= 0) qglUniform1iARB(p->loc_Texture_Lightmap       , GL20TU_LIGHTMAP);
3836                 if (p->loc_Texture_Deluxemap       >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap      , GL20TU_DELUXEMAP);
3837                 if (p->loc_Texture_Attenuation     >= 0) qglUniform1iARB(p->loc_Texture_Attenuation    , GL20TU_ATTENUATION);
3838                 if (p->loc_Texture_Cube            >= 0) qglUniform1iARB(p->loc_Texture_Cube           , GL20TU_CUBE);
3839                 if (p->loc_Texture_Refraction      >= 0) qglUniform1iARB(p->loc_Texture_Refraction     , GL20TU_REFRACTION);
3840                 if (p->loc_Texture_Reflection      >= 0) qglUniform1iARB(p->loc_Texture_Reflection     , GL20TU_REFLECTION);
3841                 if (p->loc_Texture_ShadowMapRect   >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect  , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3842                 if (p->loc_Texture_ShadowMapCube   >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube  , GL20TU_SHADOWMAPCUBE);
3843                 if (p->loc_Texture_ShadowMap2D     >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D    , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3844                 if (p->loc_Texture_CubeProjection  >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3845                 if (p->loc_Texture_ScreenDepth     >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth    , GL20TU_SCREENDEPTH);
3846                 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3847                 if (p->loc_Texture_ScreenDiffuse   >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse  , GL20TU_SCREENDIFFUSE);
3848                 if (p->loc_Texture_ScreenSpecular  >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3849                 if (p->loc_Texture_ReflectMask     >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask    , GL20TU_REFLECTMASK);
3850                 if (p->loc_Texture_ReflectCube     >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube    , GL20TU_REFLECTCUBE);
3851                 CHECKGLERROR
3852                 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3853         }
3854         else
3855                 Con_Printf("^1GLSL shader %s failed!  some features may not work properly.\n", permutationname);
3856
3857         // free the strings
3858         if (vertexstring)
3859                 Mem_Free(vertexstring);
3860         if (geometrystring)
3861                 Mem_Free(geometrystring);
3862         if (fragmentstring)
3863                 Mem_Free(fragmentstring);
3864 }
3865
3866 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3867 {
3868         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3869         if (r_glsl_permutation != perm)
3870         {
3871                 r_glsl_permutation = perm;
3872                 if (!r_glsl_permutation->program)
3873                 {
3874                         if (!r_glsl_permutation->compiled)
3875                                 R_GLSL_CompilePermutation(perm, mode, permutation);
3876                         if (!r_glsl_permutation->program)
3877                         {
3878                                 // remove features until we find a valid permutation
3879                                 int i;
3880                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3881                                 {
3882                                         // reduce i more quickly whenever it would not remove any bits
3883                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3884                                         if (!(permutation & j))
3885                                                 continue;
3886                                         permutation -= j;
3887                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3888                                         if (!r_glsl_permutation->compiled)
3889                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
3890                                         if (r_glsl_permutation->program)
3891                                                 break;
3892                                 }
3893                                 if (i >= SHADERPERMUTATION_COUNT)
3894                                 {
3895                                         //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3896                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3897                                         qglUseProgramObjectARB(0);CHECKGLERROR
3898                                         return; // no bit left to clear, entire mode is broken
3899                                 }
3900                         }
3901                 }
3902                 CHECKGLERROR
3903                 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3904         }
3905         if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3906         if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3907         if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3908 }
3909
3910 #ifdef SUPPORTCG
3911 #include <Cg/cgGL.h>
3912 struct r_cg_permutation_s;
3913 typedef struct r_cg_permutation_s
3914 {
3915         /// hash lookup data
3916         struct r_cg_permutation_s *hashnext;
3917         unsigned int mode;
3918         unsigned int permutation;
3919
3920         /// indicates if we have tried compiling this permutation already
3921         qboolean compiled;
3922         /// 0 if compilation failed
3923         CGprogram vprogram;
3924         CGprogram fprogram;
3925         /// locations of detected parameters in programs, or NULL if not found
3926         CGparameter vp_EyePosition;
3927         CGparameter vp_FogPlane;
3928         CGparameter vp_LightDir;
3929         CGparameter vp_LightPosition;
3930         CGparameter vp_ModelToLight;
3931         CGparameter vp_TexMatrix;
3932         CGparameter vp_BackgroundTexMatrix;
3933         CGparameter vp_ModelViewProjectionMatrix;
3934         CGparameter vp_ModelViewMatrix;
3935         CGparameter vp_ShadowMapMatrix;
3936
3937         CGparameter fp_Texture_First;
3938         CGparameter fp_Texture_Second;
3939         CGparameter fp_Texture_GammaRamps;
3940         CGparameter fp_Texture_Normal;
3941         CGparameter fp_Texture_Color;
3942         CGparameter fp_Texture_Gloss;
3943         CGparameter fp_Texture_Glow;
3944         CGparameter fp_Texture_SecondaryNormal;
3945         CGparameter fp_Texture_SecondaryColor;
3946         CGparameter fp_Texture_SecondaryGloss;
3947         CGparameter fp_Texture_SecondaryGlow;
3948         CGparameter fp_Texture_Pants;
3949         CGparameter fp_Texture_Shirt;
3950         CGparameter fp_Texture_FogHeightTexture;
3951         CGparameter fp_Texture_FogMask;
3952         CGparameter fp_Texture_Lightmap;
3953         CGparameter fp_Texture_Deluxemap;
3954         CGparameter fp_Texture_Attenuation;
3955         CGparameter fp_Texture_Cube;
3956         CGparameter fp_Texture_Refraction;
3957         CGparameter fp_Texture_Reflection;
3958         CGparameter fp_Texture_ShadowMapRect;
3959         CGparameter fp_Texture_ShadowMapCube;
3960         CGparameter fp_Texture_ShadowMap2D;
3961         CGparameter fp_Texture_CubeProjection;
3962         CGparameter fp_Texture_ScreenDepth;
3963         CGparameter fp_Texture_ScreenNormalMap;
3964         CGparameter fp_Texture_ScreenDiffuse;
3965         CGparameter fp_Texture_ScreenSpecular;
3966         CGparameter fp_Texture_ReflectMask;
3967         CGparameter fp_Texture_ReflectCube;
3968         CGparameter fp_Alpha;
3969         CGparameter fp_BloomBlur_Parameters;
3970         CGparameter fp_ClientTime;
3971         CGparameter fp_Color_Ambient;
3972         CGparameter fp_Color_Diffuse;
3973         CGparameter fp_Color_Specular;
3974         CGparameter fp_Color_Glow;
3975         CGparameter fp_Color_Pants;
3976         CGparameter fp_Color_Shirt;
3977         CGparameter fp_DeferredColor_Ambient;
3978         CGparameter fp_DeferredColor_Diffuse;
3979         CGparameter fp_DeferredColor_Specular;
3980         CGparameter fp_DeferredMod_Diffuse;
3981         CGparameter fp_DeferredMod_Specular;
3982         CGparameter fp_DistortScaleRefractReflect;
3983         CGparameter fp_EyePosition;
3984         CGparameter fp_FogColor;
3985         CGparameter fp_FogHeightFade;
3986         CGparameter fp_FogPlane;
3987         CGparameter fp_FogPlaneViewDist;
3988         CGparameter fp_FogRangeRecip;
3989         CGparameter fp_LightColor;
3990         CGparameter fp_LightDir;
3991         CGparameter fp_LightPosition;
3992         CGparameter fp_OffsetMapping_Scale;
3993         CGparameter fp_PixelSize;
3994         CGparameter fp_ReflectColor;
3995         CGparameter fp_ReflectFactor;
3996         CGparameter fp_ReflectOffset;
3997         CGparameter fp_RefractColor;
3998         CGparameter fp_Saturation;
3999         CGparameter fp_ScreenCenterRefractReflect;
4000         CGparameter fp_ScreenScaleRefractReflect;
4001         CGparameter fp_ScreenToDepth;
4002         CGparameter fp_ShadowMap_Parameters;
4003         CGparameter fp_ShadowMap_TextureScale;
4004         CGparameter fp_SpecularPower;
4005         CGparameter fp_UserVec1;
4006         CGparameter fp_UserVec2;
4007         CGparameter fp_UserVec3;
4008         CGparameter fp_UserVec4;
4009         CGparameter fp_ViewTintColor;
4010         CGparameter fp_ViewToLight;
4011         CGparameter fp_PixelToScreenTexCoord;
4012         CGparameter fp_ModelToReflectCube;
4013 }
4014 r_cg_permutation_t;
4015
4016 /// information about each possible shader permutation
4017 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4018 /// currently selected permutation
4019 r_cg_permutation_t *r_cg_permutation;
4020 /// storage for permutations linked in the hash table
4021 memexpandablearray_t r_cg_permutationarray;
4022
4023 #define CHECKCGERROR {CGerror err = cgGetError(), err2 = err;if (err){Con_Printf("%s:%i CG error %i: %s : %s\n", __FILE__, __LINE__, err, cgGetErrorString(err), cgGetLastErrorString(&err2));if (err == 1) Con_Printf("last listing:\n%s\n", cgGetLastListing(vid.cgcontext));}}
4024
4025 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
4026 {
4027         //unsigned int hashdepth = 0;
4028         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4029         r_cg_permutation_t *p;
4030         for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4031         {
4032                 if (p->mode == mode && p->permutation == permutation)
4033                 {
4034                         //if (hashdepth > 10)
4035                         //      Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4036                         return p;
4037                 }
4038                 //hashdepth++;
4039         }
4040         p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4041         p->mode = mode;
4042         p->permutation = permutation;
4043         p->hashnext = r_cg_permutationhash[mode][hashindex];
4044         r_cg_permutationhash[mode][hashindex] = p;
4045         //if (hashdepth > 10)
4046         //      Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4047         return p;
4048 }
4049
4050 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4051 {
4052         char *shaderstring;
4053         if (!filename || !filename[0])
4054                 return NULL;
4055         if (!strcmp(filename, "cg/default.cg"))
4056         {
4057                 if (!cgshaderstring)
4058                 {
4059                         cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4060                         if (cgshaderstring)
4061                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
4062                         else
4063                                 cgshaderstring = (char *)builtincgshaderstring;
4064                 }
4065                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4066                 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4067                 return shaderstring;
4068         }
4069         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4070         if (shaderstring)
4071         {
4072                 if (printfromdisknotice)
4073                         Con_DPrintf("from disk %s... ", filename);
4074                 return shaderstring;
4075         }
4076         return shaderstring;
4077 }
4078
4079 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4080 {
4081         // TODO: load or create .fp and .vp shader files
4082 }
4083
4084 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4085 {
4086         int i;
4087         shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4088         int vertstrings_count = 0, vertstring_length = 0;
4089         int geomstrings_count = 0, geomstring_length = 0;
4090         int fragstrings_count = 0, fragstring_length = 0;
4091         char *t;
4092         char *vertexstring, *geometrystring, *fragmentstring;
4093         char *vertstring, *geomstring, *fragstring;
4094         const char *vertstrings_list[32+3];
4095         const char *geomstrings_list[32+3];
4096         const char *fragstrings_list[32+3];
4097         char permutationname[256];
4098         char cachename[256];
4099         CGprofile vertexProfile;
4100         CGprofile fragmentProfile;
4101
4102         if (p->compiled)
4103                 return;
4104         p->compiled = true;
4105         p->vprogram = NULL;
4106         p->fprogram = NULL;
4107
4108         permutationname[0] = 0;
4109         cachename[0] = 0;
4110         vertexstring   = R_CG_GetText(modeinfo->vertexfilename, true);
4111         geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4112         fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4113
4114         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4115         strlcat(cachename, "cg/", sizeof(cachename));
4116
4117         // the first pretext is which type of shader to compile as
4118         // (later these will all be bound together as a program object)
4119         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4120         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4121         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4122
4123         // the second pretext is the mode (for example a light source)
4124         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4125         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4126         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4127         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4128         strlcat(cachename, modeinfo->name, sizeof(cachename));
4129
4130         // now add all the permutation pretexts
4131         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4132         {
4133                 if (permutation & (1<<i))
4134                 {
4135                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4136                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4137                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4138                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4139                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4140                 }
4141                 else
4142                 {
4143                         // keep line numbers correct
4144                         vertstrings_list[vertstrings_count++] = "\n";
4145                         geomstrings_list[geomstrings_count++] = "\n";
4146                         fragstrings_list[fragstrings_count++] = "\n";
4147                 }
4148         }
4149
4150         // replace spaces in the cachename with _ characters
4151         for (i = 0;cachename[i];i++)
4152                 if (cachename[i] == ' ')
4153                         cachename[i] = '_';
4154
4155         // now append the shader text itself
4156         vertstrings_list[vertstrings_count++] = vertexstring;
4157         geomstrings_list[geomstrings_count++] = geometrystring;
4158         fragstrings_list[fragstrings_count++] = fragmentstring;
4159
4160         // if any sources were NULL, clear the respective list
4161         if (!vertexstring)
4162                 vertstrings_count = 0;
4163         if (!geometrystring)
4164                 geomstrings_count = 0;
4165         if (!fragmentstring)
4166                 fragstrings_count = 0;
4167
4168         vertstring_length = 0;
4169         for (i = 0;i < vertstrings_count;i++)
4170                 vertstring_length += strlen(vertstrings_list[i]);
4171         vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4172         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4173                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4174
4175         geomstring_length = 0;
4176         for (i = 0;i < geomstrings_count;i++)
4177                 geomstring_length += strlen(geomstrings_list[i]);
4178         geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4179         for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4180                 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4181
4182         fragstring_length = 0;
4183         for (i = 0;i < fragstrings_count;i++)
4184                 fragstring_length += strlen(fragstrings_list[i]);
4185         fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4186         for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4187                 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4188
4189         CHECKGLERROR
4190         CHECKCGERROR
4191         //vertexProfile = CG_PROFILE_ARBVP1;
4192         //fragmentProfile = CG_PROFILE_ARBFP1;
4193         vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4194         fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4195         //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4196         //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4197         //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4198         CHECKGLERROR
4199
4200         // try to load the cached shader, or generate one
4201         R_CG_CacheShader(p, cachename, vertstring, fragstring);
4202
4203         // if caching failed, do a dynamic compile for now
4204         CHECKCGERROR
4205         if (vertstring[0] && !p->vprogram)
4206                 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4207         CHECKCGERROR
4208         if (fragstring[0] && !p->fprogram)
4209                 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4210         CHECKCGERROR
4211
4212         // look up all the uniform variable names we care about, so we don't
4213         // have to look them up every time we set them
4214         if (p->vprogram)
4215         {
4216                 CHECKCGERROR
4217                 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4218                 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4219                 p->vp_EyePosition                = cgGetNamedParameter(p->vprogram, "EyePosition");
4220                 p->vp_FogPlane                   = cgGetNamedParameter(p->vprogram, "FogPlane");
4221                 p->vp_LightDir                   = cgGetNamedParameter(p->vprogram, "LightDir");
4222                 p->vp_LightPosition              = cgGetNamedParameter(p->vprogram, "LightPosition");
4223                 p->vp_ModelToLight               = cgGetNamedParameter(p->vprogram, "ModelToLight");
4224                 p->vp_TexMatrix                  = cgGetNamedParameter(p->vprogram, "TexMatrix");
4225                 p->vp_BackgroundTexMatrix        = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4226                 p->vp_ModelViewProjectionMatrix  = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4227                 p->vp_ModelViewMatrix            = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4228                 p->vp_ShadowMapMatrix            = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4229                 CHECKCGERROR
4230         }
4231         if (p->fprogram)
4232         {
4233                 CHECKCGERROR
4234                 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4235                 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4236                 p->fp_Texture_First              = cgGetNamedParameter(p->fprogram, "Texture_First");
4237                 p->fp_Texture_Second             = cgGetNamedParameter(p->fprogram, "Texture_Second");
4238                 p->fp_Texture_GammaRamps         = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4239                 p->fp_Texture_Normal             = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4240                 p->fp_Texture_Color              = cgGetNamedParameter(p->fprogram, "Texture_Color");
4241                 p->fp_Texture_Gloss              = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4242                 p->fp_Texture_Glow               = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4243                 p->fp_Texture_SecondaryNormal    = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4244                 p->fp_Texture_SecondaryColor     = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4245                 p->fp_Texture_SecondaryGloss     = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4246                 p->fp_Texture_SecondaryGlow      = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4247                 p->fp_Texture_Pants              = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4248                 p->fp_Texture_Shirt              = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4249                 p->fp_Texture_FogHeightTexture   = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4250                 p->fp_Texture_FogMask            = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4251                 p->fp_Texture_Lightmap           = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4252                 p->fp_Texture_Deluxemap          = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4253                 p->fp_Texture_Attenuation        = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4254                 p->fp_Texture_Cube               = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4255                 p->fp_Texture_Refraction         = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4256                 p->fp_Texture_Reflection         = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4257                 p->fp_Texture_ShadowMapRect      = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4258                 p->fp_Texture_ShadowMapCube      = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4259                 p->fp_Texture_ShadowMap2D        = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4260                 p->fp_Texture_CubeProjection     = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4261                 p->fp_Texture_ScreenDepth        = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4262                 p->fp_Texture_ScreenNormalMap    = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4263                 p->fp_Texture_ScreenDiffuse      = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4264                 p->fp_Texture_ScreenSpecular     = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4265                 p->fp_Texture_ReflectMask        = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4266                 p->fp_Texture_ReflectCube        = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4267                 p->fp_Alpha                      = cgGetNamedParameter(p->fprogram, "Alpha");
4268                 p->fp_BloomBlur_Parameters       = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4269                 p->fp_ClientTime                 = cgGetNamedParameter(p->fprogram, "ClientTime");
4270                 p->fp_Color_Ambient              = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4271                 p->fp_Color_Diffuse              = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4272                 p->fp_Color_Specular             = cgGetNamedParameter(p->fprogram, "Color_Specular");
4273                 p->fp_Color_Glow                 = cgGetNamedParameter(p->fprogram, "Color_Glow");
4274                 p->fp_Color_Pants                = cgGetNamedParameter(p->fprogram, "Color_Pants");
4275                 p->fp_Color_Shirt                = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4276                 p->fp_DeferredColor_Ambient      = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4277                 p->fp_DeferredColor_Diffuse      = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4278                 p->fp_DeferredColor_Specular     = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4279                 p->fp_DeferredMod_Diffuse        = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4280                 p->fp_DeferredMod_Specular       = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4281                 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4282                 p->fp_EyePosition                = cgGetNamedParameter(p->fprogram, "EyePosition");
4283                 p->fp_FogColor                   = cgGetNamedParameter(p->fprogram, "FogColor");
4284                 p->fp_FogHeightFade              = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4285                 p->fp_FogPlane                   = cgGetNamedParameter(p->fprogram, "FogPlane");
4286                 p->fp_FogPlaneViewDist           = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4287                 p->fp_FogRangeRecip              = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4288                 p->fp_LightColor                 = cgGetNamedParameter(p->fprogram, "LightColor");
4289                 p->fp_LightDir                   = cgGetNamedParameter(p->fprogram, "LightDir");
4290                 p->fp_LightPosition              = cgGetNamedParameter(p->fprogram, "LightPosition");
4291                 p->fp_OffsetMapping_Scale        = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4292                 p->fp_PixelSize                  = cgGetNamedParameter(p->fprogram, "PixelSize");
4293                 p->fp_ReflectColor               = cgGetNamedParameter(p->fprogram, "ReflectColor");
4294                 p->fp_ReflectFactor              = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4295                 p->fp_ReflectOffset              = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4296                 p->fp_RefractColor               = cgGetNamedParameter(p->fprogram, "RefractColor");
4297                 p->fp_Saturation                 = cgGetNamedParameter(p->fprogram, "Saturation");
4298                 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4299                 p->fp_ScreenScaleRefractReflect  = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4300                 p->fp_ScreenToDepth              = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4301                 p->fp_ShadowMap_Parameters       = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4302                 p->fp_ShadowMap_TextureScale     = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4303                 p->fp_SpecularPower              = cgGetNamedParameter(p->fprogram, "SpecularPower");
4304                 p->fp_UserVec1                   = cgGetNamedParameter(p->fprogram, "UserVec1");
4305                 p->fp_UserVec2                   = cgGetNamedParameter(p->fprogram, "UserVec2");
4306                 p->fp_UserVec3                   = cgGetNamedParameter(p->fprogram, "UserVec3");
4307                 p->fp_UserVec4                   = cgGetNamedParameter(p->fprogram, "UserVec4");
4308                 p->fp_ViewTintColor              = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4309                 p->fp_ViewToLight                = cgGetNamedParameter(p->fprogram, "ViewToLight");
4310                 p->fp_PixelToScreenTexCoord      = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4311                 p->fp_ModelToReflectCube         = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4312                 CHECKCGERROR
4313         }
4314
4315         if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4316                 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4317         else
4318                 Con_Printf("^1CG shader %s failed!  some features may not work properly.\n", permutationname);
4319
4320         // free the strings
4321         if (vertstring)
4322                 Mem_Free(vertstring);
4323         if (geomstring)
4324                 Mem_Free(geomstring);
4325         if (fragstring)
4326                 Mem_Free(fragstring);
4327         if (vertexstring)
4328                 Mem_Free(vertexstring);
4329         if (geometrystring)
4330                 Mem_Free(geometrystring);
4331         if (fragmentstring)
4332                 Mem_Free(fragmentstring);
4333 }
4334
4335 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4336 {
4337         r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4338         CHECKGLERROR
4339         CHECKCGERROR
4340         if (r_cg_permutation != perm)
4341         {
4342                 r_cg_permutation = perm;
4343                 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4344                 {
4345                         if (!r_cg_permutation->compiled)
4346                                 R_CG_CompilePermutation(perm, mode, permutation);
4347                         if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4348                         {
4349                                 // remove features until we find a valid permutation
4350                                 int i;
4351                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4352                                 {
4353                                         // reduce i more quickly whenever it would not remove any bits
4354                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4355                                         if (!(permutation & j))
4356                                                 continue;
4357                                         permutation -= j;
4358                                         r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4359                                         if (!r_cg_permutation->compiled)
4360                                                 R_CG_CompilePermutation(perm, mode, permutation);
4361                                         if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4362                                                 break;
4363                                 }
4364                                 if (i >= SHADERPERMUTATION_COUNT)
4365                                 {
4366                                         //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4367                                         r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4368                                         return; // no bit left to clear, entire mode is broken
4369                                 }
4370                         }
4371                 }
4372                 CHECKGLERROR
4373                 CHECKCGERROR
4374                 if (r_cg_permutation->vprogram)
4375                 {
4376                         cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4377                         cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4378                         cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4379                 }
4380                 else
4381                 {
4382                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4383                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4384                 }
4385                 if (r_cg_permutation->fprogram)
4386                 {
4387                         cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4388                         cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4389                         cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4390                 }
4391                 else
4392                 {
4393                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4394                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4395                 }
4396         }
4397         CHECKCGERROR
4398         if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4399         if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4400         if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4401 }
4402
4403 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4404 {
4405         cgGLSetTextureParameter(param, R_GetTexture(tex));
4406         cgGLEnableTextureParameter(param);
4407 }
4408 #endif
4409
4410 void R_GLSL_Restart_f(void)
4411 {
4412         unsigned int i, limit;
4413         if (glslshaderstring && glslshaderstring != builtinshaderstring)
4414                 Mem_Free(glslshaderstring);
4415         glslshaderstring = NULL;
4416         if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4417                 Mem_Free(cgshaderstring);
4418         cgshaderstring = NULL;
4419         switch(vid.renderpath)
4420         {
4421         case RENDERPATH_GL20:
4422                 {
4423                         r_glsl_permutation_t *p;
4424                         r_glsl_permutation = NULL;
4425                         limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4426                         for (i = 0;i < limit;i++)
4427                         {
4428                                 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4429                                 {
4430                                         GL_Backend_FreeProgram(p->program);
4431                                         Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4432                                 }
4433                         }
4434                         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4435                 }
4436                 break;
4437         case RENDERPATH_CGGL:
4438 #ifdef SUPPORTCG
4439                 {
4440                         r_cg_permutation_t *p;
4441                         r_cg_permutation = NULL;
4442                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4443                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4444                         cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4445                         cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4446                         limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4447                         for (i = 0;i < limit;i++)
4448                         {
4449                                 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4450                                 {
4451                                         if (p->vprogram)
4452                                                 cgDestroyProgram(p->vprogram);
4453                                         if (p->fprogram)
4454                                                 cgDestroyProgram(p->fprogram);
4455                                         Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4456                                 }
4457                         }
4458                         memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4459                 }
4460                 break;
4461 #endif
4462         case RENDERPATH_GL13:
4463         case RENDERPATH_GL11:
4464                 break;
4465         }
4466 }
4467
4468 void R_GLSL_DumpShader_f(void)
4469 {
4470         int i;
4471         qfile_t *file;
4472
4473         file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4474         if (file)
4475         {
4476                 FS_Print(file, "/* The engine may define the following macros:\n");
4477                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4478                 for (i = 0;i < SHADERMODE_COUNT;i++)
4479                         FS_Print(file, glslshadermodeinfo[i].pretext);
4480                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4481                         FS_Print(file, shaderpermutationinfo[i].pretext);
4482                 FS_Print(file, "*/\n");
4483                 FS_Print(file, builtinshaderstring);
4484                 FS_Close(file);
4485                 Con_Printf("glsl/default.glsl written\n");
4486         }
4487         else
4488                 Con_Printf("failed to write to glsl/default.glsl\n");
4489
4490 #ifdef SUPPORTCG
4491         file = FS_OpenRealFile("cg/default.cg", "w", false);
4492         if (file)
4493         {
4494                 FS_Print(file, "/* The engine may define the following macros:\n");
4495                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4496                 for (i = 0;i < SHADERMODE_COUNT;i++)
4497                         FS_Print(file, cgshadermodeinfo[i].pretext);
4498                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4499                         FS_Print(file, shaderpermutationinfo[i].pretext);
4500                 FS_Print(file, "*/\n");
4501                 FS_Print(file, builtincgshaderstring);
4502                 FS_Close(file);
4503                 Con_Printf("cg/default.cg written\n");
4504         }
4505         else
4506                 Con_Printf("failed to write to cg/default.cg\n");
4507 #endif
4508 }
4509
4510 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4511 {
4512         if (!second)
4513                 texturemode = GL_MODULATE;
4514         switch (vid.renderpath)
4515         {
4516         case RENDERPATH_GL20:
4517                 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4518                 if (r_glsl_permutation->loc_Texture_First ) R_Mesh_TexBind(GL20TU_FIRST , first );
4519                 if (r_glsl_permutation->loc_Texture_Second) R_Mesh_TexBind(GL20TU_SECOND, second);
4520                 break;
4521         case RENDERPATH_CGGL:
4522 #ifdef SUPPORTCG
4523                 CHECKCGERROR
4524                 R_SetupShader_SetPermutationCG(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4525                 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
4526                 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
4527 #endif
4528                 break;
4529         case RENDERPATH_GL13:
4530                 R_Mesh_TexBind(0, first );
4531                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4532                 R_Mesh_TexBind(1, second);
4533                 if (second)
4534                         R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4535                 break;
4536         case RENDERPATH_GL11:
4537                 R_Mesh_TexBind(0, first );
4538                 break;
4539         }
4540 }
4541
4542 void R_SetupShader_DepthOrShadow(void)
4543 {
4544         switch (vid.renderpath)
4545         {
4546         case RENDERPATH_GL20:
4547                 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4548                 break;
4549         case RENDERPATH_CGGL:
4550 #ifdef SUPPORTCG
4551                 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
4552 #endif
4553                 break;
4554         case RENDERPATH_GL13:
4555                 R_Mesh_TexBind(0, 0);
4556                 R_Mesh_TexBind(1, 0);
4557                 break;
4558         case RENDERPATH_GL11:
4559                 R_Mesh_TexBind(0, 0);
4560                 break;
4561         }
4562 }
4563
4564 void R_SetupShader_ShowDepth(void)
4565 {
4566         switch (vid.renderpath)
4567         {
4568         case RENDERPATH_GL20:
4569                 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4570                 break;
4571         case RENDERPATH_CGGL:
4572 #ifdef SUPPORTCG
4573                 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
4574 #endif
4575                 break;
4576         case RENDERPATH_GL13:
4577                 break;
4578         case RENDERPATH_GL11:
4579                 break;
4580         }
4581 }
4582
4583 extern qboolean r_shadow_usingdeferredprepass;
4584 extern cvar_t r_shadow_deferred_8bitrange;
4585 extern rtexture_t *r_shadow_attenuationgradienttexture;
4586 extern rtexture_t *r_shadow_attenuation2dtexture;
4587 extern rtexture_t *r_shadow_attenuation3dtexture;
4588 extern qboolean r_shadow_usingshadowmaprect;
4589 extern qboolean r_shadow_usingshadowmapcube;
4590 extern qboolean r_shadow_usingshadowmap2d;
4591 extern qboolean r_shadow_usingshadowmaportho;
4592 extern float r_shadow_shadowmap_texturescale[2];
4593 extern float r_shadow_shadowmap_parameters[4];
4594 extern qboolean r_shadow_shadowmapvsdct;
4595 extern qboolean r_shadow_shadowmapsampler;
4596 extern int r_shadow_shadowmappcf;
4597 extern rtexture_t *r_shadow_shadowmaprectangletexture;
4598 extern rtexture_t *r_shadow_shadowmap2dtexture;
4599 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
4600 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4601 extern matrix4x4_t r_shadow_shadowmapmatrix;
4602 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4603 extern int r_shadow_prepass_width;
4604 extern int r_shadow_prepass_height;
4605 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4606 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4607 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4608 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4609 static qboolean R_BlendFuncAllowsColormod(int src, int dst)
4610 {
4611         // a blendfunc allows colormod if:
4612         // a) it can never keep the destination pixel invariant, or
4613         // b) it can keep the destination pixel invariant, and still can do so if colormodded
4614         // this is to prevent unintended side effects from colormod
4615
4616         // in formulas:
4617         // IF there is a (s, sa) for which for all (d, da),
4618         //   s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4619         // THEN, for this (s, sa) and all (colormod, d, da):
4620         //   s*colormod * src(s*colormod, d, sa, da) + d * dst(s*colormod, d, sa, da) == d
4621         // OBVIOUSLY, this means that
4622         //   s*colormod * src(s*colormod, d, sa, da) = 0
4623         //   dst(s*colormod, d, sa, da)              = 1
4624
4625         // note: not caring about GL_SRC_ALPHA_SATURATE and following here, these are unused in DP code
4626
4627         // main condition to leave dst color invariant:
4628         //   s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4629         //   src == GL_ZERO:
4630         //     s * 0 + d * dst(s, d, sa, da) == d
4631         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4632         //       => colormod is a problem for GL_SRC_COLOR only
4633         //   src == GL_ONE:
4634         //     s + d * dst(s, d, sa, da) == d
4635         //       => s == 0
4636         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4637         //       => colormod is never problematic for these
4638         //   src == GL_SRC_COLOR:
4639         //     s*s + d * dst(s, d, sa, da) == d
4640         //       => s == 0
4641         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4642         //       => colormod is never problematic for these
4643         //   src == GL_ONE_MINUS_SRC_COLOR:
4644         //     s*(1-s) + d * dst(s, d, sa, da) == d
4645         //       => s == 0 or s == 1
4646         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4647         //       => colormod is a problem for GL_SRC_COLOR only
4648         //   src == GL_DST_COLOR
4649         //     s*d + d * dst(s, d, sa, da) == d
4650         //       => s == 1
4651         //       => dst == GL_ZERO/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4652         //       => colormod is always a problem
4653         //     or
4654         //       => s == 0
4655         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4656         //       => colormod is never problematic for these
4657         //       => BUT, we do not know s! We must assume it is problematic
4658         //       then... except in GL_ONE case, where we know all invariant
4659         //       cases are fine
4660         //   src == GL_ONE_MINUS_DST_COLOR
4661         //     s*(1-d) + d * dst(s, d, sa, da) == d
4662         //       => s == 0 (1-d is impossible to handle for our desired result)
4663         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4664         //       => colormod is never problematic for these
4665         //   src == GL_SRC_ALPHA
4666         //     s*sa + d * dst(s, d, sa, da) == d
4667         //       => s == 0, or sa == 0
4668         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4669         //       => colormod breaks in the case GL_SRC_COLOR only
4670         //   src == GL_ONE_MINUS_SRC_ALPHA
4671         //     s*(1-sa) + d * dst(s, d, sa, da) == d
4672         //       => s == 0, or sa == 1
4673         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4674         //       => colormod breaks in the case GL_SRC_COLOR only
4675         //   src == GL_DST_ALPHA
4676         //     s*da + d * dst(s, d, sa, da) == d
4677         //       => s == 0
4678         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4679         //       => colormod is never problematic for these
4680
4681         switch(src)
4682         {
4683                 case GL_ZERO:
4684                 case GL_ONE_MINUS_SRC_COLOR:
4685                 case GL_SRC_ALPHA:
4686                 case GL_ONE_MINUS_SRC_ALPHA:
4687                         if(dst == GL_SRC_COLOR)
4688                                 return false;
4689                         return true;
4690                 case GL_ONE:
4691                 case GL_SRC_COLOR:
4692                 case GL_ONE_MINUS_DST_COLOR:
4693                 case GL_DST_ALPHA:
4694                 case GL_ONE_MINUS_DST_ALPHA:
4695                         return true;
4696                 case GL_DST_COLOR:
4697                         if(dst == GL_ONE)
4698                                 return true;
4699                         return false;
4700                 default:
4701                         return false;
4702         }
4703 }
4704 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass)
4705 {
4706         // select a permutation of the lighting shader appropriate to this
4707         // combination of texture, entity, light source, and fogging, only use the
4708         // minimum features necessary to avoid wasting rendering time in the
4709         // fragment shader on features that are not being used
4710         unsigned int permutation = 0;
4711         unsigned int mode = 0;
4712         qboolean allow_colormod;
4713         static float dummy_colormod[3] = {1, 1, 1};
4714         float *colormod = rsurface.colormod;
4715         float m16f[16];
4716         if (rsurfacepass == RSURFPASS_BACKGROUND)
4717         {
4718                 // distorted background
4719                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4720                 {
4721                         mode = SHADERMODE_WATER;
4722                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4723                         allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4724                 }
4725                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4726                 {
4727                         mode = SHADERMODE_REFRACTION;
4728                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4729                         allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4730                 }
4731                 else
4732                 {
4733                         mode = SHADERMODE_GENERIC;
4734                         permutation |= SHADERPERMUTATION_DIFFUSE;
4735                         GL_BlendFunc(GL_ONE, GL_ZERO);
4736                         allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4737                 }
4738                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
4739                 R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
4740                 R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
4741                 R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
4742                 R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
4743                 R_Mesh_ColorPointer(NULL, 0, 0);
4744                 GL_AlphaTest(false);
4745         }
4746         else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4747         {
4748                 if (r_glsl_offsetmapping.integer)
4749                 {
4750                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4751                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4752                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4753                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4754                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4755                         {
4756                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4757                                 if (r_glsl_offsetmapping_reliefmapping.integer)
4758                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4759                         }
4760                 }
4761                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4762                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4763                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4764                         permutation |= SHADERPERMUTATION_ALPHAKILL;
4765                 // normalmap (deferred prepass), may use alpha test on diffuse
4766                 mode = SHADERMODE_DEFERREDGEOMETRY;
4767                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4768                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4769                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
4770                 R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
4771                 R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
4772                 R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
4773                 R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
4774                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
4775                         R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
4776                 else
4777                         R_Mesh_ColorPointer(NULL, 0, 0);
4778                 GL_AlphaTest(false);
4779                 GL_BlendFunc(GL_ONE, GL_ZERO);
4780                 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4781         }
4782         else if (rsurfacepass == RSURFPASS_RTLIGHT)
4783         {
4784                 if (r_glsl_offsetmapping.integer)
4785                 {
4786                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4787                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4788                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4789                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4790                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4791                         {
4792                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4793                                 if (r_glsl_offsetmapping_reliefmapping.integer)
4794                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4795                         }
4796                 }
4797                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4798                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4799                 // light source
4800                 mode = SHADERMODE_LIGHTSOURCE;
4801                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4802                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4803                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4804                         permutation |= SHADERPERMUTATION_CUBEFILTER;
4805                 if (diffusescale > 0)
4806                         permutation |= SHADERPERMUTATION_DIFFUSE;
4807                 if (specularscale > 0)
4808                 {
4809                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4810                         if (r_shadow_glossexact.integer)
4811                                 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4812                 }
4813                 if (r_refdef.fogenabled)
4814                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4815                 if (rsurface.texture->colormapping)
4816                         permutation |= SHADERPERMUTATION_COLORMAPPING;
4817                 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
4818                 {
4819                         if (r_shadow_usingshadowmaprect)
4820                                 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4821                         if (r_shadow_usingshadowmap2d)
4822                                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4823                         if (r_shadow_usingshadowmapcube)
4824                                 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
4825                         else if(r_shadow_shadowmapvsdct)
4826                                 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
4827
4828                         if (r_shadow_shadowmapsampler)
4829                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4830                         if (r_shadow_shadowmappcf > 1)
4831                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4832                         else if (r_shadow_shadowmappcf)
4833                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4834                 }
4835                 if (rsurface.texture->reflectmasktexture)
4836                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
4837                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
4838                 if (true || permutation & (SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_OFFSETMAPPING))
4839                 {
4840                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
4841                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
4842                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
4843                 }
4844                 else
4845                 {
4846                         R_Mesh_TexCoordPointer(1, 0, NULL, 0, 0);
4847                         R_Mesh_TexCoordPointer(2, 0, NULL, 0, 0);
4848                         R_Mesh_TexCoordPointer(3, 0, NULL, 0, 0);
4849                 }
4850                 //R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
4851                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
4852                         R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
4853                 else
4854                         R_Mesh_ColorPointer(NULL, 0, 0);
4855                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4856                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
4857                 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE);
4858         }
4859         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4860         {
4861                 if (r_glsl_offsetmapping.integer)
4862                 {
4863                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4864                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4865                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4866                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4867                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4868                         {
4869                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4870                                 if (r_glsl_offsetmapping_reliefmapping.integer)
4871                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4872                         }
4873                 }
4874                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4875                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4876                 // unshaded geometry (fullbright or ambient model lighting)
4877                 mode = SHADERMODE_FLATCOLOR;
4878                 ambientscale = diffusescale = specularscale = 0;
4879                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4880                         permutation |= SHADERPERMUTATION_GLOW;
4881                 if (r_refdef.fogenabled)
4882                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4883                 if (rsurface.texture->colormapping)
4884                         permutation |= SHADERPERMUTATION_COLORMAPPING;
4885                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4886                 {
4887                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4888                         if (r_shadow_usingshadowmaprect)
4889                                 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4890                         if (r_shadow_usingshadowmap2d)
4891                                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4892
4893                         if (r_shadow_shadowmapsampler)
4894                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4895                         if (r_shadow_shadowmappcf > 1)
4896                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4897                         else if (r_shadow_shadowmappcf)
4898                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4899                 }
4900                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4901                         permutation |= SHADERPERMUTATION_REFLECTION;
4902                 if (rsurface.texture->reflectmasktexture)
4903                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
4904                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
4905                 if (true || permutation & (SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_OFFSETMAPPING))
4906                 {
4907                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
4908                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
4909                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
4910                 }
4911                 else
4912                 {
4913                         R_Mesh_TexCoordPointer(1, 0, NULL, 0, 0);
4914                         R_Mesh_TexCoordPointer(2, 0, NULL, 0, 0);
4915                         R_Mesh_TexCoordPointer(3, 0, NULL, 0, 0);
4916                 }
4917                 R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
4918                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
4919                         R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
4920                 else
4921                         R_Mesh_ColorPointer(NULL, 0, 0);
4922                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4923                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4924                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4925         }
4926         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
4927         {
4928                 if (r_glsl_offsetmapping.integer)
4929                 {
4930                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4931                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4932                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4933                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4934                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4935                         {
4936                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4937                                 if (r_glsl_offsetmapping_reliefmapping.integer)
4938                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4939                         }
4940                 }
4941                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4942                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4943                 // directional model lighting
4944                 mode = SHADERMODE_LIGHTDIRECTION;
4945                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4946                         permutation |= SHADERPERMUTATION_GLOW;
4947                 permutation |= SHADERPERMUTATION_DIFFUSE;
4948                 if (specularscale > 0)
4949                 {
4950                         permutation |= SHADERPERMUTATION_SPECULAR;
4951                         if (r_shadow_glossexact.integer)
4952                                 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4953                 }
4954                 if (r_refdef.fogenabled)
4955                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4956                 if (rsurface.texture->colormapping)
4957                         permutation |= SHADERPERMUTATION_COLORMAPPING;
4958                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4959                 {
4960                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4961                         if (r_shadow_usingshadowmaprect)
4962                                 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4963                         if (r_shadow_usingshadowmap2d)
4964                                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4965
4966                         if (r_shadow_shadowmapsampler)
4967                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4968                         if (r_shadow_shadowmappcf > 1)
4969                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4970                         else if (r_shadow_shadowmappcf)
4971                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4972                 }
4973                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4974                         permutation |= SHADERPERMUTATION_REFLECTION;
4975                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4976                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4977                 if (rsurface.texture->reflectmasktexture)
4978                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
4979                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
4980                 if (true || permutation & (SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_OFFSETMAPPING))
4981                 {
4982                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
4983                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
4984                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
4985                 }
4986                 else
4987                 {
4988                         R_Mesh_TexCoordPointer(1, 0, NULL, 0, 0);
4989                         R_Mesh_TexCoordPointer(2, 0, NULL, 0, 0);
4990                         R_Mesh_TexCoordPointer(3, 0, NULL, 0, 0);
4991                 }
4992                 R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
4993                 R_Mesh_ColorPointer(NULL, 0, 0);
4994                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4995                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4996                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4997         }
4998         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
4999         {
5000                 if (r_glsl_offsetmapping.integer)
5001                 {
5002                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5003                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5004                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5005                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5006                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5007                         {
5008                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5009                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5010                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5011                         }
5012                 }
5013                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5014                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5015                 // ambient model lighting
5016                 mode = SHADERMODE_LIGHTDIRECTION;
5017                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5018                         permutation |= SHADERPERMUTATION_GLOW;
5019                 if (r_refdef.fogenabled)
5020                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5021                 if (rsurface.texture->colormapping)
5022                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5023                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5024                 {
5025                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5026                         if (r_shadow_usingshadowmaprect)
5027                                 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5028                         if (r_shadow_usingshadowmap2d)
5029                                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5030
5031                         if (r_shadow_shadowmapsampler)
5032                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5033                         if (r_shadow_shadowmappcf > 1)
5034                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5035                         else if (r_shadow_shadowmappcf)
5036                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5037                 }
5038                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5039                         permutation |= SHADERPERMUTATION_REFLECTION;
5040                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5041                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5042                 if (rsurface.texture->reflectmasktexture)
5043                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5044                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
5045                 if (true || permutation & (SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_OFFSETMAPPING))
5046                 {
5047                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
5048                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
5049                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
5050                 }
5051                 else
5052                 {
5053                         R_Mesh_TexCoordPointer(1, 0, NULL, 0, 0);
5054                         R_Mesh_TexCoordPointer(2, 0, NULL, 0, 0);
5055                         R_Mesh_TexCoordPointer(3, 0, NULL, 0, 0);
5056                 }
5057                 R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
5058                 R_Mesh_ColorPointer(NULL, 0, 0);
5059                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5060                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5061                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5062         }
5063         else
5064         {
5065                 if (r_glsl_offsetmapping.integer)
5066                 {
5067                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5068                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5069                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5070                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5071                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5072                         {
5073                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5074                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5075                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5076                         }
5077                 }
5078                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5079                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5080                 // lightmapped wall
5081                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5082                         permutation |= SHADERPERMUTATION_GLOW;
5083                 if (r_refdef.fogenabled)
5084                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5085                 if (rsurface.texture->colormapping)
5086                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5087                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5088                 {
5089                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5090                         if (r_shadow_usingshadowmaprect)
5091                                 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5092                         if (r_shadow_usingshadowmap2d)
5093                                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5094
5095                         if (r_shadow_shadowmapsampler)
5096                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5097                         if (r_shadow_shadowmappcf > 1)
5098                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5099                         else if (r_shadow_shadowmappcf)
5100                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5101                 }
5102                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5103                         permutation |= SHADERPERMUTATION_REFLECTION;
5104                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5105                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5106                 if (rsurface.texture->reflectmasktexture)
5107                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5108                 if (FAKELIGHT_ENABLED)
5109                 {
5110                         // fake lightmapping (q1bsp, q3bsp, fullbright map)
5111                         mode = SHADERMODE_FAKELIGHT;
5112                         permutation |= SHADERPERMUTATION_DIFFUSE;
5113                         if (specularscale > 0)
5114                         {
5115                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5116                                 if (r_shadow_glossexact.integer)
5117                                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5118                         }
5119                         if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
5120                                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5121                         else
5122                                 R_Mesh_ColorPointer(NULL, 0, 0);
5123                 }
5124                 else if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
5125                 {
5126                         // deluxemapping (light direction texture)
5127                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
5128                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
5129                         else
5130                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5131                         permutation |= SHADERPERMUTATION_DIFFUSE;
5132                         if (specularscale > 0)
5133                         {
5134                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5135                                 if (r_shadow_glossexact.integer)
5136                                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5137                         }
5138                         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5139                         if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
5140                                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5141                         else
5142                                 R_Mesh_ColorPointer(NULL, 0, 0);
5143                 }
5144                 else if (r_glsl_deluxemapping.integer >= 2 && rsurface.uselightmaptexture)
5145                 {
5146                         // fake deluxemapping (uniform light direction in tangentspace)
5147                         mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5148                         permutation |= SHADERPERMUTATION_DIFFUSE;
5149                         if (specularscale > 0)
5150                         {
5151                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5152                                 if (r_shadow_glossexact.integer)
5153                                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5154                         }
5155                         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5156                         if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
5157                                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5158                         else
5159                                 R_Mesh_ColorPointer(NULL, 0, 0);
5160                 }
5161                 else if (rsurface.uselightmaptexture)
5162                 {
5163                         // ordinary lightmapping (q1bsp, q3bsp)
5164                         mode = SHADERMODE_LIGHTMAP;
5165                         R_Mesh_TexCoordPointer(4, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
5166                         if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND)
5167                                 R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5168                         else
5169                                 R_Mesh_ColorPointer(NULL, 0, 0);
5170                 }
5171                 else
5172                 {
5173                         // ordinary vertex coloring (q3bsp)
5174                         mode = SHADERMODE_VERTEXCOLOR;
5175                         R_Mesh_TexCoordPointer(4, 0, NULL, 0, 0);
5176                         R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset);
5177                 }
5178                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
5179                 if (true || permutation & (SHADERPERMUTATION_DIFFUSE | SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_OFFSETMAPPING))
5180                 {
5181                         R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset);
5182                         R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset);
5183                         R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset);
5184                 }
5185                 else
5186                 {
5187                         R_Mesh_TexCoordPointer(1, 0, NULL, 0, 0);
5188                         R_Mesh_TexCoordPointer(2, 0, NULL, 0, 0);
5189                         R_Mesh_TexCoordPointer(3, 0, NULL, 0, 0);
5190                 }
5191                 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5192                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5193                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5194         }
5195         if(!allow_colormod)
5196                 colormod = dummy_colormod;
5197         switch(vid.renderpath)
5198         {
5199         case RENDERPATH_GL20:
5200                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5201                 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5202                 if (mode == SHADERMODE_LIGHTSOURCE)
5203                 {
5204                         if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5205                         if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5206                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5207                         if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5208                         if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5209                         if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5210         
5211                         // additive passes are only darkened by fog, not tinted
5212                         if (r_glsl_permutation->loc_FogColor >= 0)
5213                                 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5214                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5215                 }
5216                 else
5217                 {
5218                         if (mode == SHADERMODE_FLATCOLOR)
5219                         {
5220                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5221                         }
5222                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5223                         {
5224                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
5225                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5226                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5227                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5228                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5229                                 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5230                                 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5231                         }
5232                         else
5233                         {
5234                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5235                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5236                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5237                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5238                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5239                         }
5240                         // additive passes are only darkened by fog, not tinted
5241                         if (r_glsl_permutation->loc_FogColor >= 0)
5242                         {
5243                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5244                                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5245                                 else
5246                                         qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5247                         }
5248                         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);
5249                         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]);
5250                         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]);
5251                         if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5252                         if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5253                         if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5254                         if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5255                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5256                 }
5257                 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5258                 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5259                 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5260                 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5261                 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5262
5263                 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5264                 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5265                 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5266                 if (r_glsl_permutation->loc_Color_Pants >= 0)
5267                 {
5268                         if (rsurface.texture->pantstexture)
5269                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5270                         else
5271                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5272                 }
5273                 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5274                 {
5275                         if (rsurface.texture->shirttexture)
5276                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5277                         else
5278                                 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5279                 }
5280                 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4fARB(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5281                 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5282                 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5283                 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5284                 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5285                 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2fARB(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5286                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5287
5288         //      if (r_glsl_permutation->loc_Texture_First           >= 0) R_Mesh_TexBind(GL20TU_FIRST             , r_texture_white                                     );
5289         //      if (r_glsl_permutation->loc_Texture_Second          >= 0) R_Mesh_TexBind(GL20TU_SECOND            , r_texture_white                                     );
5290         //      if (r_glsl_permutation->loc_Texture_GammaRamps      >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS        , r_texture_gammaramps                                );
5291                 if (r_glsl_permutation->loc_Texture_Normal          >= 0) R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
5292                 if (r_glsl_permutation->loc_Texture_Color           >= 0) R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
5293                 if (r_glsl_permutation->loc_Texture_Gloss           >= 0) R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
5294                 if (r_glsl_permutation->loc_Texture_Glow            >= 0) R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
5295                 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
5296                 if (r_glsl_permutation->loc_Texture_SecondaryColor  >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
5297                 if (r_glsl_permutation->loc_Texture_SecondaryGloss  >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
5298                 if (r_glsl_permutation->loc_Texture_SecondaryGlow   >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
5299                 if (r_glsl_permutation->loc_Texture_Pants           >= 0) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
5300                 if (r_glsl_permutation->loc_Texture_Shirt           >= 0) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
5301                 if (r_glsl_permutation->loc_Texture_ReflectMask     >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
5302                 if (r_glsl_permutation->loc_Texture_ReflectCube     >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5303                 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
5304                 if (r_glsl_permutation->loc_Texture_FogMask         >= 0) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
5305                 if (r_glsl_permutation->loc_Texture_Lightmap        >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP          , r_texture_white                                     );
5306                 if (r_glsl_permutation->loc_Texture_Deluxemap       >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP         , r_texture_blanknormalmap                            );
5307                 if (r_glsl_permutation->loc_Texture_Attenuation     >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
5308                 if (r_glsl_permutation->loc_Texture_Refraction      >= 0) R_Mesh_TexBind(GL20TU_REFRACTION        , r_texture_white                                     );
5309                 if (r_glsl_permutation->loc_Texture_Reflection      >= 0) R_Mesh_TexBind(GL20TU_REFLECTION        , r_texture_white                                     );
5310                 if (r_glsl_permutation->loc_Texture_ScreenDepth     >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
5311                 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
5312                 if (r_glsl_permutation->loc_Texture_ScreenDiffuse   >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
5313                 if (r_glsl_permutation->loc_Texture_ScreenSpecular  >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
5314                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5315                 {
5316                         if (r_glsl_permutation->loc_Texture_ShadowMap2D     >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture                         );
5317                         if (r_glsl_permutation->loc_Texture_ShadowMapRect   >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture                  );
5318                         if (rsurface.rtlight)
5319                         {
5320                                 if (r_glsl_permutation->loc_Texture_Cube            >= 0) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
5321                                 if (r_shadow_usingshadowmapcube)
5322                                         if (r_glsl_permutation->loc_Texture_ShadowMapCube   >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE     , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5323                                 if (r_glsl_permutation->loc_Texture_CubeProjection  >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
5324                         }
5325                 }
5326                 CHECKGLERROR
5327                 break;
5328         case RENDERPATH_CGGL:
5329 #ifdef SUPPORTCG
5330                 R_SetupShader_SetPermutationCG(mode, permutation);
5331                 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5332                 if (mode == SHADERMODE_LIGHTSOURCE)
5333                 {
5334                         if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5335                         if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5336                 }
5337                 else
5338                 {
5339                         if (mode == SHADERMODE_LIGHTDIRECTION)
5340                         {
5341                                 if (r_cg_permutation->vp_LightDir) cgGLSetParameter3f(r_cg_permutation->vp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5342                         }
5343                 }
5344                 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5345                 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5346                 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5347                 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5348                 if (r_cg_permutation->vp_FogPlane) cgGLSetParameter4f(r_cg_permutation->vp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5349                 CHECKGLERROR
5350
5351                 if (mode == SHADERMODE_LIGHTSOURCE)
5352                 {
5353                         if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5354                         if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5355                         if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);CHECKCGERROR
5356                         if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);CHECKCGERROR
5357                         if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);CHECKCGERROR
5358
5359                         // additive passes are only darkened by fog, not tinted
5360                         if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5361                         if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5362                 }
5363                 else
5364                 {
5365                         if (mode == SHADERMODE_FLATCOLOR)
5366                         {
5367                                 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0], colormod[1], colormod[2]);CHECKCGERROR
5368                         }
5369                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5370                         {
5371                                 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);CHECKCGERROR
5372                                 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);CHECKCGERROR
5373                                 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5374                                 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5375                                 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5376                                 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);CHECKCGERROR
5377                                 if (r_cg_permutation->fp_LightDir) cgGLSetParameter3f(r_cg_permutation->fp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5378                         }
5379                         else
5380                         {
5381                                 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);CHECKCGERROR
5382                                 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);CHECKCGERROR
5383                                 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5384                                 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5385                                 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5386                         }
5387                         // additive passes are only darkened by fog, not tinted
5388                         if (r_cg_permutation->fp_FogColor)
5389                         {
5390                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5391                                         cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5392                                 else
5393                                         cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5394                                 CHECKCGERROR
5395                         }
5396                         if (r_cg_permutation->fp_DistortScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_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);CHECKCGERROR
5397                         if (r_cg_permutation->fp_ScreenScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);CHECKCGERROR
5398                         if (r_cg_permutation->fp_ScreenCenterRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);CHECKCGERROR
5399                         if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5400                         if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5401                         if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5402                         if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5403                         if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5404                 }
5405                 if (r_cg_permutation->fp_ShadowMap_TextureScale) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5406                 if (r_cg_permutation->fp_ShadowMap_Parameters) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5407                 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5408                 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));CHECKCGERROR
5409                 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5410                 if (r_cg_permutation->fp_Color_Pants)
5411                 {
5412                         if (rsurface.texture->pantstexture)
5413                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5414                         else
5415                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5416                         CHECKCGERROR
5417                 }
5418                 if (r_cg_permutation->fp_Color_Shirt)
5419                 {
5420                         if (rsurface.texture->shirttexture)
5421                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5422                         else
5423                                 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5424                         CHECKCGERROR
5425                 }
5426                 if (r_cg_permutation->fp_FogPlane) cgGLSetParameter4f(r_cg_permutation->fp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5427                 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
5428                 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
5429                 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
5430                 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
5431                 if (r_cg_permutation->fp_ScreenToDepth) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
5432                 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5433
5434         //      if (r_cg_permutation->fp_Texture_First          ) CG_BindTexture(r_cg_permutation->fp_Texture_First          , r_texture_white                                     );CHECKCGERROR
5435         //      if (r_cg_permutation->fp_Texture_Second         ) CG_BindTexture(r_cg_permutation->fp_Texture_Second         , r_texture_white                                     );CHECKCGERROR
5436         //      if (r_cg_permutation->fp_Texture_GammaRamps     ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps     , r_texture_gammaramps                                );CHECKCGERROR
5437                 if (r_cg_permutation->fp_Texture_Normal         ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal         , rsurface.texture->nmaptexture                       );CHECKCGERROR
5438                 if (r_cg_permutation->fp_Texture_Color          ) CG_BindTexture(r_cg_permutation->fp_Texture_Color          , rsurface.texture->basetexture                       );CHECKCGERROR
5439                 if (r_cg_permutation->fp_Texture_Gloss          ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss          , rsurface.texture->glosstexture                      );CHECKCGERROR
5440                 if (r_cg_permutation->fp_Texture_Glow           ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow           , rsurface.texture->glowtexture                       );CHECKCGERROR
5441                 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture             );CHECKCGERROR
5442                 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture             );CHECKCGERROR
5443                 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture            );CHECKCGERROR
5444                 if (r_cg_permutation->fp_Texture_SecondaryGlow  ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow  , rsurface.texture->backgroundglowtexture             );CHECKCGERROR
5445                 if (r_cg_permutation->fp_Texture_Pants          ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants          , rsurface.texture->pantstexture                      );CHECKCGERROR
5446                 if (r_cg_permutation->fp_Texture_Shirt          ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt          , rsurface.texture->shirttexture                      );CHECKCGERROR
5447                 if (r_cg_permutation->fp_Texture_ReflectMask    ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask    , rsurface.texture->reflectmasktexture                );CHECKCGERROR
5448                 if (r_cg_permutation->fp_Texture_ReflectCube    ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectCube    , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);CHECKCGERROR
5449                 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture                         );CHECKCGERROR
5450                 if (r_cg_permutation->fp_Texture_FogMask        ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask        , r_texture_fogattenuation                            );CHECKCGERROR
5451                 if (r_cg_permutation->fp_Texture_Lightmap       ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap       , r_texture_white                                     );CHECKCGERROR
5452                 if (r_cg_permutation->fp_Texture_Deluxemap      ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap      , r_texture_blanknormalmap                            );CHECKCGERROR
5453                 if (r_cg_permutation->fp_Texture_Attenuation    ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation    , r_shadow_attenuationgradienttexture                 );CHECKCGERROR
5454                 if (r_cg_permutation->fp_Texture_Refraction     ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction     , r_texture_white                                     );CHECKCGERROR
5455                 if (r_cg_permutation->fp_Texture_Reflection     ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection     , r_texture_white                                     );CHECKCGERROR
5456                 if (r_cg_permutation->fp_Texture_ScreenDepth    ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth    , r_shadow_prepassgeometrydepthtexture                );CHECKCGERROR
5457                 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture            );CHECKCGERROR
5458                 if (r_cg_permutation->fp_Texture_ScreenDiffuse  ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse  , r_shadow_prepasslightingdiffusetexture              );CHECKCGERROR
5459                 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture             );CHECKCGERROR
5460                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5461                 {
5462                         if (r_cg_permutation->fp_Texture_ShadowMap2D    ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D    , r_shadow_shadowmap2dtexture                         );CHECKCGERROR
5463                         if (r_cg_permutation->fp_Texture_ShadowMapRect  ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect  , r_shadow_shadowmaprectangletexture                  );CHECKCGERROR
5464                         if (rsurface.rtlight)
5465                         {
5466                                 if (r_cg_permutation->fp_Texture_Cube           ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube           , rsurface.rtlight->currentcubemap                    );CHECKCGERROR
5467                                 if (r_shadow_usingshadowmapcube)
5468                                         if (r_cg_permutation->fp_Texture_ShadowMapCube  ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube  , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5469                                 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture                      );CHECKCGERROR
5470                         }
5471                 }
5472
5473                 CHECKGLERROR
5474 #endif
5475                 break;
5476         case RENDERPATH_GL13:
5477         case RENDERPATH_GL11:
5478                 break;
5479         }
5480 }
5481
5482 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5483 {
5484         // select a permutation of the lighting shader appropriate to this
5485         // combination of texture, entity, light source, and fogging, only use the
5486         // minimum features necessary to avoid wasting rendering time in the
5487         // fragment shader on features that are not being used
5488         unsigned int permutation = 0;
5489         unsigned int mode = 0;
5490         const float *lightcolorbase = rtlight->currentcolor;
5491         float ambientscale = rtlight->ambientscale;
5492         float diffusescale = rtlight->diffusescale;
5493         float specularscale = rtlight->specularscale;
5494         // this is the location of the light in view space
5495         vec3_t viewlightorigin;
5496         // this transforms from view space (camera) to light space (cubemap)
5497         matrix4x4_t viewtolight;
5498         matrix4x4_t lighttoview;
5499         float viewtolight16f[16];
5500         float range = 1.0f / r_shadow_deferred_8bitrange.value;
5501         // light source
5502         mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5503         if (rtlight->currentcubemap != r_texture_whitecube)
5504                 permutation |= SHADERPERMUTATION_CUBEFILTER;
5505         if (diffusescale > 0)
5506                 permutation |= SHADERPERMUTATION_DIFFUSE;
5507         if (specularscale > 0)
5508         {
5509                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5510                 if (r_shadow_glossexact.integer)
5511                         permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5512         }
5513         if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5514         {
5515                 if (r_shadow_usingshadowmaprect)
5516                         permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5517                 if (r_shadow_usingshadowmap2d)
5518                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5519                 if (r_shadow_usingshadowmapcube)
5520                         permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5521                 else if(r_shadow_shadowmapvsdct)
5522                         permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5523
5524                 if (r_shadow_shadowmapsampler)
5525                         permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5526                 if (r_shadow_shadowmappcf > 1)
5527                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5528                 else if (r_shadow_shadowmappcf)
5529                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5530         }
5531         Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5532         Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5533         Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5534         Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5535         switch(vid.renderpath)
5536         {
5537         case RENDERPATH_GL20:
5538                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5539                 if (r_glsl_permutation->loc_LightPosition             >= 0) qglUniform3fARB(       r_glsl_permutation->loc_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5540                 if (r_glsl_permutation->loc_ViewToLight               >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight              , 1, false, viewtolight16f);
5541                 if (r_glsl_permutation->loc_DeferredColor_Ambient     >= 0) qglUniform3fARB(       r_glsl_permutation->loc_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
5542                 if (r_glsl_permutation->loc_DeferredColor_Diffuse     >= 0) qglUniform3fARB(       r_glsl_permutation->loc_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
5543                 if (r_glsl_permutation->loc_DeferredColor_Specular    >= 0) qglUniform3fARB(       r_glsl_permutation->loc_DeferredColor_Specular   , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5544                 if (r_glsl_permutation->loc_ShadowMap_TextureScale    >= 0) qglUniform2fARB(       r_glsl_permutation->loc_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5545                 if (r_glsl_permutation->loc_ShadowMap_Parameters      >= 0) qglUniform4fARB(       r_glsl_permutation->loc_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5546                 if (r_glsl_permutation->loc_SpecularPower             >= 0) qglUniform1fARB(       r_glsl_permutation->loc_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5547                 if (r_glsl_permutation->loc_ScreenToDepth             >= 0) qglUniform2fARB(       r_glsl_permutation->loc_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5548                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5549
5550                 if (r_glsl_permutation->loc_Texture_Attenuation       >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
5551                 if (r_glsl_permutation->loc_Texture_ScreenDepth       >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthtexture                );
5552                 if (r_glsl_permutation->loc_Texture_ScreenNormalMap   >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
5553                 if (r_glsl_permutation->loc_Texture_Cube              >= 0) R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
5554                 if (r_glsl_permutation->loc_Texture_ShadowMapRect     >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT      , r_shadow_shadowmaprectangletexture                  );
5555                 if (r_shadow_usingshadowmapcube)
5556                         if (r_glsl_permutation->loc_Texture_ShadowMapCube     >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE      , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5557                 if (r_glsl_permutation->loc_Texture_ShadowMap2D       >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dtexture                         );
5558                 if (r_glsl_permutation->loc_Texture_CubeProjection    >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
5559                 break;
5560         case RENDERPATH_CGGL:
5561 #ifdef SUPPORTCG
5562                 R_SetupShader_SetPermutationCG(mode, permutation);
5563                 if (r_cg_permutation->fp_LightPosition            ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
5564                 if (r_cg_permutation->fp_ViewToLight              ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
5565                 if (r_cg_permutation->fp_DeferredColor_Ambient    ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Ambient , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);CHECKCGERROR
5566                 if (r_cg_permutation->fp_DeferredColor_Diffuse    ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);CHECKCGERROR
5567                 if (r_cg_permutation->fp_DeferredColor_Specular   ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);CHECKCGERROR
5568                 if (r_cg_permutation->fp_ShadowMap_TextureScale   ) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5569                 if (r_cg_permutation->fp_ShadowMap_Parameters     ) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5570                 if (r_cg_permutation->fp_SpecularPower            ) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5571                 if (r_cg_permutation->fp_ScreenToDepth            ) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
5572                 if (r_cg_permutation->fp_PixelToScreenTexCoord    ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5573
5574                 if (r_cg_permutation->fp_Texture_Attenuation      ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation    , r_shadow_attenuationgradienttexture                 );CHECKCGERROR
5575                 if (r_cg_permutation->fp_Texture_ScreenDepth      ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth    , r_shadow_prepassgeometrydepthtexture                );CHECKCGERROR
5576                 if (r_cg_permutation->fp_Texture_ScreenNormalMap  ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture            );CHECKCGERROR
5577                 if (r_cg_permutation->fp_Texture_Cube             ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube           , rsurface.rtlight->currentcubemap                    );CHECKCGERROR
5578                 if (r_cg_permutation->fp_Texture_ShadowMapRect    ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect  , r_shadow_shadowmaprectangletexture                  );CHECKCGERROR
5579                 if (r_shadow_usingshadowmapcube)
5580                         if (r_cg_permutation->fp_Texture_ShadowMapCube    ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube  , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5581                 if (r_cg_permutation->fp_Texture_ShadowMap2D      ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D    , r_shadow_shadowmap2dtexture                         );CHECKCGERROR
5582                 if (r_cg_permutation->fp_Texture_CubeProjection   ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture                      );CHECKCGERROR
5583 #endif
5584                 break;
5585         case RENDERPATH_GL13:
5586         case RENDERPATH_GL11:
5587                 break;
5588         }
5589 }
5590
5591 #define SKINFRAME_HASH 1024
5592
5593 typedef struct
5594 {
5595         int loadsequence; // incremented each level change
5596         memexpandablearray_t array;
5597         skinframe_t *hash[SKINFRAME_HASH];
5598 }
5599 r_skinframe_t;
5600 r_skinframe_t r_skinframe;
5601
5602 void R_SkinFrame_PrepareForPurge(void)
5603 {
5604         r_skinframe.loadsequence++;
5605         // wrap it without hitting zero
5606         if (r_skinframe.loadsequence >= 200)
5607                 r_skinframe.loadsequence = 1;
5608 }
5609
5610 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5611 {
5612         if (!skinframe)
5613                 return;
5614         // mark the skinframe as used for the purging code
5615         skinframe->loadsequence = r_skinframe.loadsequence;
5616 }
5617
5618 void R_SkinFrame_Purge(void)
5619 {
5620         int i;
5621         skinframe_t *s;
5622         for (i = 0;i < SKINFRAME_HASH;i++)
5623         {
5624                 for (s = r_skinframe.hash[i];s;s = s->next)
5625                 {
5626                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5627                         {
5628                                 if (s->merged == s->base)
5629                                         s->merged = NULL;
5630                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5631                                 R_PurgeTexture(s->stain );s->stain  = NULL;
5632                                 R_PurgeTexture(s->merged);s->merged = NULL;
5633                                 R_PurgeTexture(s->base  );s->base   = NULL;
5634                                 R_PurgeTexture(s->pants );s->pants  = NULL;
5635                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
5636                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
5637                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
5638                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
5639                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
5640                                 R_PurgeTexture(s->reflect);s->reflect = NULL;
5641                                 s->loadsequence = 0;
5642                         }
5643                 }
5644         }
5645 }
5646
5647 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5648         skinframe_t *item;
5649         char basename[MAX_QPATH];
5650
5651         Image_StripImageExtension(name, basename, sizeof(basename));
5652
5653         if( last == NULL ) {
5654                 int hashindex;
5655                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5656                 item = r_skinframe.hash[hashindex];
5657         } else {
5658                 item = last->next;
5659         }
5660
5661         // linearly search through the hash bucket
5662         for( ; item ; item = item->next ) {
5663                 if( !strcmp( item->basename, basename ) ) {
5664                         return item;
5665                 }
5666         }
5667         return NULL;
5668 }
5669
5670 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5671 {
5672         skinframe_t *item;
5673         int hashindex;
5674         char basename[MAX_QPATH];
5675
5676         Image_StripImageExtension(name, basename, sizeof(basename));
5677
5678         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5679         for (item = r_skinframe.hash[hashindex];item;item = item->next)
5680                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5681                         break;
5682
5683         if (!item) {
5684                 rtexture_t *dyntexture;
5685                 // check whether its a dynamic texture
5686                 dyntexture = CL_GetDynTexture( basename );
5687                 if (!add && !dyntexture)
5688                         return NULL;
5689                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5690                 memset(item, 0, sizeof(*item));
5691                 strlcpy(item->basename, basename, sizeof(item->basename));
5692                 item->base = dyntexture; // either NULL or dyntexture handle
5693                 item->textureflags = textureflags;
5694                 item->comparewidth = comparewidth;
5695                 item->compareheight = compareheight;
5696                 item->comparecrc = comparecrc;
5697                 item->next = r_skinframe.hash[hashindex];
5698                 r_skinframe.hash[hashindex] = item;
5699         }
5700         else if( item->base == NULL )
5701         {
5702                 rtexture_t *dyntexture;
5703                 // check whether its a dynamic texture
5704                 // 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]
5705                 dyntexture = CL_GetDynTexture( basename );
5706                 item->base = dyntexture; // either NULL or dyntexture handle
5707         }
5708
5709         R_SkinFrame_MarkUsed(item);
5710         return item;
5711 }
5712
5713 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5714         { \
5715                 unsigned long long avgcolor[5], wsum; \
5716                 int pix, comp, w; \
5717                 avgcolor[0] = 0; \
5718                 avgcolor[1] = 0; \
5719                 avgcolor[2] = 0; \
5720                 avgcolor[3] = 0; \
5721                 avgcolor[4] = 0; \
5722                 wsum = 0; \
5723                 for(pix = 0; pix < cnt; ++pix) \
5724                 { \
5725                         w = 0; \
5726                         for(comp = 0; comp < 3; ++comp) \
5727                                 w += getpixel; \
5728                         if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5729                         { \
5730                                 ++wsum; \
5731                                 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5732                                 w = getpixel; \
5733                                 for(comp = 0; comp < 3; ++comp) \
5734                                         avgcolor[comp] += getpixel * w; \
5735                                 avgcolor[3] += w; \
5736                         } \
5737                         /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5738                         avgcolor[4] += getpixel; \
5739                 } \
5740                 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
5741                         avgcolor[3] = 1; \
5742                 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
5743                 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
5744                 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
5745                 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
5746         }
5747
5748 extern cvar_t gl_picmip;
5749 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
5750 {
5751         int j;
5752         unsigned char *pixels;
5753         unsigned char *bumppixels;
5754         unsigned char *basepixels = NULL;
5755         int basepixels_width = 0;
5756         int basepixels_height = 0;
5757         skinframe_t *skinframe;
5758         rtexture_t *ddsbase = NULL;
5759         qboolean ddshasalpha = false;
5760         float ddsavgcolor[4];
5761         char basename[MAX_QPATH];
5762         int miplevel = R_PicmipForFlags(textureflags);
5763         int savemiplevel = miplevel;
5764         int mymiplevel;
5765
5766         if (cls.state == ca_dedicated)
5767                 return NULL;
5768
5769         // return an existing skinframe if already loaded
5770         // if loading of the first image fails, don't make a new skinframe as it
5771         // would cause all future lookups of this to be missing
5772         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
5773         if (skinframe && skinframe->base)
5774                 return skinframe;
5775
5776         Image_StripImageExtension(name, basename, sizeof(basename));
5777
5778         // check for DDS texture file first
5779         if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
5780         {
5781                 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer, &miplevel);
5782                 if (basepixels == NULL)
5783                         return NULL;
5784         }
5785
5786         // FIXME handle miplevel
5787
5788         if (developer_loading.integer)
5789                 Con_Printf("loading skin \"%s\"\n", name);
5790
5791         // we've got some pixels to store, so really allocate this new texture now
5792         if (!skinframe)
5793                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
5794         skinframe->stain = NULL;
5795         skinframe->merged = NULL;
5796         skinframe->base = NULL;
5797         skinframe->pants = NULL;
5798         skinframe->shirt = NULL;
5799         skinframe->nmap = NULL;
5800         skinframe->gloss = NULL;
5801         skinframe->glow = NULL;
5802         skinframe->fog = NULL;
5803         skinframe->reflect = NULL;
5804         skinframe->hasalpha = false;
5805
5806         if (ddsbase)
5807         {
5808                 skinframe->base = ddsbase;
5809                 skinframe->hasalpha = ddshasalpha;
5810                 VectorCopy(ddsavgcolor, skinframe->avgcolor);
5811                 if (r_loadfog && skinframe->hasalpha)
5812                         skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
5813                 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5814         }
5815         else
5816         {
5817                 basepixels_width = image_width;
5818                 basepixels_height = image_height;
5819                 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
5820                 if (textureflags & TEXF_ALPHA)
5821                 {
5822                         for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
5823                         {
5824                                 if (basepixels[j] < 255)
5825                                 {
5826                                         skinframe->hasalpha = true;
5827                                         break;
5828                                 }
5829                         }
5830                         if (r_loadfog && skinframe->hasalpha)
5831                         {
5832                                 // has transparent pixels
5833                                 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5834                                 for (j = 0;j < image_width * image_height * 4;j += 4)
5835                                 {
5836                                         pixels[j+0] = 255;
5837                                         pixels[j+1] = 255;
5838                                         pixels[j+2] = 255;
5839                                         pixels[j+3] = basepixels[j+3];
5840                                 }
5841                                 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
5842                                 Mem_Free(pixels);
5843                         }
5844                 }
5845                 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
5846                 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
5847                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
5848                         R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true, skinframe->hasalpha);
5849                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
5850                         R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true, true);
5851         }
5852
5853         if (r_loaddds)
5854         {
5855                 mymiplevel = savemiplevel;
5856                 if (r_loadnormalmap)
5857                         skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), NULL, NULL, mymiplevel);
5858                 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5859                 if (r_loadgloss)
5860                         skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5861                 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5862                 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5863                 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5864         }
5865
5866         // _norm is the name used by tenebrae and has been adopted as standard
5867         if (r_loadnormalmap && skinframe->nmap == NULL)
5868         {
5869                 mymiplevel = savemiplevel;
5870                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
5871                 {
5872                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5873                         Mem_Free(pixels);
5874                         pixels = NULL;
5875                 }
5876                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
5877                 {
5878                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5879                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
5880                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5881                         Mem_Free(pixels);
5882                         Mem_Free(bumppixels);
5883                 }
5884                 else if (r_shadow_bumpscale_basetexture.value > 0)
5885                 {
5886                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
5887                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
5888                         skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5889                         Mem_Free(pixels);
5890                 }
5891                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
5892                         R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true, true);
5893         }
5894
5895         // _luma is supported only for tenebrae compatibility
5896         // _glow is the preferred name
5897         mymiplevel = savemiplevel;
5898         if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow",  skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel))))
5899         {
5900                 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5901                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
5902                         R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true, true);
5903                 Mem_Free(pixels);pixels = NULL;
5904         }
5905
5906         mymiplevel = savemiplevel;
5907         if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5908         {
5909                 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5910                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
5911                         R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true, true);
5912                 Mem_Free(pixels);
5913                 pixels = NULL;
5914         }
5915
5916         mymiplevel = savemiplevel;
5917         if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5918         {
5919                 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5920                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
5921                         R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true, false);
5922                 Mem_Free(pixels);
5923                 pixels = NULL;
5924         }
5925
5926         mymiplevel = savemiplevel;
5927         if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5928         {
5929                 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5930                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
5931                         R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true, false);
5932                 Mem_Free(pixels);
5933                 pixels = NULL;
5934         }
5935
5936         mymiplevel = savemiplevel;
5937         if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5938         {
5939                 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5940                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
5941                         R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true, true);
5942                 Mem_Free(pixels);
5943                 pixels = NULL;
5944         }
5945
5946         if (basepixels)
5947                 Mem_Free(basepixels);
5948
5949         return skinframe;
5950 }
5951
5952 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
5953 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
5954 {
5955         int i;
5956         unsigned char *temp1, *temp2;
5957         skinframe_t *skinframe;
5958
5959         if (cls.state == ca_dedicated)
5960                 return NULL;
5961
5962         // if already loaded just return it, otherwise make a new skinframe
5963         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
5964         if (skinframe && skinframe->base)
5965                 return skinframe;
5966
5967         skinframe->stain = NULL;
5968         skinframe->merged = NULL;
5969         skinframe->base = NULL;
5970         skinframe->pants = NULL;
5971         skinframe->shirt = NULL;
5972         skinframe->nmap = NULL;
5973         skinframe->gloss = NULL;
5974         skinframe->glow = NULL;
5975         skinframe->fog = NULL;
5976         skinframe->reflect = NULL;
5977         skinframe->hasalpha = false;
5978
5979         // if no data was provided, then clearly the caller wanted to get a blank skinframe
5980         if (!skindata)
5981                 return NULL;
5982
5983         if (developer_loading.integer)
5984                 Con_Printf("loading 32bit skin \"%s\"\n", name);
5985
5986         if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
5987         {
5988                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5989                 temp2 = temp1 + width * height * 4;
5990                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5991                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
5992                 Mem_Free(temp1);
5993         }
5994         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
5995         if (textureflags & TEXF_ALPHA)
5996         {
5997                 for (i = 3;i < width * height * 4;i += 4)
5998                 {
5999                         if (skindata[i] < 255)
6000                         {
6001                                 skinframe->hasalpha = true;
6002                                 break;
6003                         }
6004                 }
6005                 if (r_loadfog && skinframe->hasalpha)
6006                 {
6007                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
6008                         memcpy(fogpixels, skindata, width * height * 4);
6009                         for (i = 0;i < width * height * 4;i += 4)
6010                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
6011                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
6012                         Mem_Free(fogpixels);
6013                 }
6014         }
6015
6016         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
6017         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6018
6019         return skinframe;
6020 }
6021
6022 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
6023 {
6024         int i;
6025         int featuresmask;
6026         skinframe_t *skinframe;
6027
6028         if (cls.state == ca_dedicated)
6029                 return NULL;
6030
6031         // if already loaded just return it, otherwise make a new skinframe
6032         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6033         if (skinframe && skinframe->base)
6034                 return skinframe;
6035
6036         skinframe->stain = NULL;
6037         skinframe->merged = NULL;
6038         skinframe->base = NULL;
6039         skinframe->pants = NULL;
6040         skinframe->shirt = NULL;
6041         skinframe->nmap = NULL;
6042         skinframe->gloss = NULL;
6043         skinframe->glow = NULL;
6044         skinframe->fog = NULL;
6045         skinframe->reflect = NULL;
6046         skinframe->hasalpha = false;
6047
6048         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6049         if (!skindata)
6050                 return NULL;
6051
6052         if (developer_loading.integer)
6053                 Con_Printf("loading quake skin \"%s\"\n", name);
6054
6055         // we actually don't upload anything until the first use, because mdl skins frequently go unused, and are almost never used in both modes (colormapped and non-colormapped)
6056         skinframe->qpixels = Mem_Alloc(r_main_mempool, width*height);
6057         memcpy(skinframe->qpixels, skindata, width*height);
6058         skinframe->qwidth = width;
6059         skinframe->qheight = height;
6060
6061         featuresmask = 0;
6062         for (i = 0;i < width * height;i++)
6063                 featuresmask |= palette_featureflags[skindata[i]];
6064
6065         skinframe->hasalpha = false;
6066         skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
6067         skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
6068         skinframe->qgeneratemerged = true;
6069         skinframe->qgeneratebase = skinframe->qhascolormapping;
6070         skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
6071
6072         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
6073         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6074
6075         return skinframe;
6076 }
6077
6078 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
6079 {
6080         int width;
6081         int height;
6082         unsigned char *skindata;
6083
6084         if (!skinframe->qpixels)
6085                 return;
6086
6087         if (!skinframe->qhascolormapping)
6088                 colormapped = false;
6089
6090         if (colormapped)
6091         {
6092                 if (!skinframe->qgeneratebase)
6093                         return;
6094         }
6095         else
6096         {
6097                 if (!skinframe->qgeneratemerged)
6098                         return;
6099         }
6100
6101         width = skinframe->qwidth;
6102         height = skinframe->qheight;
6103         skindata = skinframe->qpixels;
6104
6105         if (skinframe->qgeneratenmap)
6106         {
6107                 unsigned char *temp1, *temp2;
6108                 skinframe->qgeneratenmap = false;
6109                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6110                 temp2 = temp1 + width * height * 4;
6111                 // use either a custom palette or the quake palette
6112                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
6113                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6114                 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (skinframe->textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
6115                 Mem_Free(temp1);
6116         }
6117
6118         if (skinframe->qgenerateglow)
6119         {
6120                 skinframe->qgenerateglow = false;
6121                 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
6122         }
6123
6124         if (colormapped)
6125         {
6126                 skinframe->qgeneratebase = false;
6127                 skinframe->base  = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
6128                 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6129                 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6130         }
6131         else
6132         {
6133                 skinframe->qgeneratemerged = false;
6134                 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
6135         }
6136
6137         if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6138         {
6139                 Mem_Free(skinframe->qpixels);
6140                 skinframe->qpixels = NULL;
6141         }
6142 }
6143
6144 skinframe_t *R_SkinFrame_LoadInternal8bit(const char *name, int textureflags, const unsigned char *skindata, int width, int height, const unsigned int *palette, const unsigned int *alphapalette)
6145 {
6146         int i;
6147         skinframe_t *skinframe;
6148
6149         if (cls.state == ca_dedicated)
6150                 return NULL;
6151
6152         // if already loaded just return it, otherwise make a new skinframe
6153         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6154         if (skinframe && skinframe->base)
6155                 return skinframe;
6156
6157         skinframe->stain = NULL;
6158         skinframe->merged = NULL;
6159         skinframe->base = NULL;
6160         skinframe->pants = NULL;
6161         skinframe->shirt = NULL;
6162         skinframe->nmap = NULL;
6163         skinframe->gloss = NULL;
6164         skinframe->glow = NULL;
6165         skinframe->fog = NULL;
6166         skinframe->reflect = NULL;
6167         skinframe->hasalpha = false;
6168
6169         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6170         if (!skindata)
6171                 return NULL;
6172
6173         if (developer_loading.integer)
6174                 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6175
6176         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6177         if (textureflags & TEXF_ALPHA)
6178         {
6179                 for (i = 0;i < width * height;i++)
6180                 {
6181                         if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6182                         {
6183                                 skinframe->hasalpha = true;
6184                                 break;
6185                         }
6186                 }
6187                 if (r_loadfog && skinframe->hasalpha)
6188                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6189         }
6190
6191         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6192         //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6193
6194         return skinframe;
6195 }
6196
6197 skinframe_t *R_SkinFrame_LoadMissing(void)
6198 {
6199         skinframe_t *skinframe;
6200
6201         if (cls.state == ca_dedicated)
6202                 return NULL;
6203
6204         skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6205         skinframe->stain = NULL;
6206         skinframe->merged = NULL;
6207         skinframe->base = NULL;
6208         skinframe->pants = NULL;
6209         skinframe->shirt = NULL;
6210         skinframe->nmap = NULL;
6211         skinframe->gloss = NULL;
6212         skinframe->glow = NULL;
6213         skinframe->fog = NULL;
6214         skinframe->reflect = NULL;
6215         skinframe->hasalpha = false;
6216
6217         skinframe->avgcolor[0] = rand() / RAND_MAX;
6218         skinframe->avgcolor[1] = rand() / RAND_MAX;
6219         skinframe->avgcolor[2] = rand() / RAND_MAX;
6220         skinframe->avgcolor[3] = 1;
6221
6222         return skinframe;
6223 }
6224
6225 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6226 typedef struct suffixinfo_s
6227 {
6228         char *suffix;
6229         qboolean flipx, flipy, flipdiagonal;
6230 }
6231 suffixinfo_t;
6232 static suffixinfo_t suffix[3][6] =
6233 {
6234         {
6235                 {"px",   false, false, false},
6236                 {"nx",   false, false, false},
6237                 {"py",   false, false, false},
6238                 {"ny",   false, false, false},
6239                 {"pz",   false, false, false},
6240                 {"nz",   false, false, false}
6241         },
6242         {
6243                 {"posx", false, false, false},
6244                 {"negx", false, false, false},
6245                 {"posy", false, false, false},
6246                 {"negy", false, false, false},
6247                 {"posz", false, false, false},
6248                 {"negz", false, false, false}
6249         },
6250         {
6251                 {"rt",    true, false,  true},
6252                 {"lf",   false,  true,  true},
6253                 {"ft",    true,  true, false},
6254                 {"bk",   false, false, false},
6255                 {"up",    true, false,  true},
6256                 {"dn",    true, false,  true}
6257         }
6258 };
6259
6260 static int componentorder[4] = {0, 1, 2, 3};
6261
6262 rtexture_t *R_LoadCubemap(const char *basename)
6263 {
6264         int i, j, cubemapsize;
6265         unsigned char *cubemappixels, *image_buffer;
6266         rtexture_t *cubemaptexture;
6267         char name[256];
6268         // must start 0 so the first loadimagepixels has no requested width/height
6269         cubemapsize = 0;
6270         cubemappixels = NULL;
6271         cubemaptexture = NULL;
6272         // keep trying different suffix groups (posx, px, rt) until one loads
6273         for (j = 0;j < 3 && !cubemappixels;j++)
6274         {
6275                 // load the 6 images in the suffix group
6276                 for (i = 0;i < 6;i++)
6277                 {
6278                         // generate an image name based on the base and and suffix
6279                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6280                         // load it
6281                         if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer, NULL)))
6282                         {
6283                                 // an image loaded, make sure width and height are equal
6284                                 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6285                                 {
6286                                         // if this is the first image to load successfully, allocate the cubemap memory
6287                                         if (!cubemappixels && image_width >= 1)
6288                                         {
6289                                                 cubemapsize = image_width;
6290                                                 // note this clears to black, so unavailable sides are black
6291                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6292                                         }
6293                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6294                                         if (cubemappixels)
6295                                                 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_buffer, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
6296                                 }
6297                                 else
6298                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6299                                 // free the image
6300                                 Mem_Free(image_buffer);
6301                         }
6302                 }
6303         }
6304         // if a cubemap loaded, upload it
6305         if (cubemappixels)
6306         {
6307                 if (developer_loading.integer)
6308                         Con_Printf("loading cubemap \"%s\"\n", basename);
6309
6310                 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6311                 Mem_Free(cubemappixels);
6312         }
6313         else
6314         {
6315                 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6316                 if (developer_loading.integer)
6317                 {
6318                         Con_Printf("(tried tried images ");
6319                         for (j = 0;j < 3;j++)
6320                                 for (i = 0;i < 6;i++)
6321                                         Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6322                         Con_Print(" and was unable to find any of them).\n");
6323                 }
6324         }
6325         return cubemaptexture;
6326 }
6327
6328 rtexture_t *R_GetCubemap(const char *basename)
6329 {
6330         int i;
6331         for (i = 0;i < r_texture_numcubemaps;i++)
6332                 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6333                         return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6334         if (i >= MAX_CUBEMAPS)
6335                 return r_texture_whitecube;
6336         r_texture_numcubemaps++;
6337         strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6338         r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6339         return r_texture_cubemaps[i].texture;
6340 }
6341
6342 void R_FreeCubemaps(void)
6343 {
6344         int i;
6345         for (i = 0;i < r_texture_numcubemaps;i++)
6346         {
6347                 if (developer_loading.integer)
6348                         Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6349                 if (r_texture_cubemaps[i].texture)
6350                         R_FreeTexture(r_texture_cubemaps[i].texture);
6351         }
6352         r_texture_numcubemaps = 0;
6353 }
6354
6355 void R_Main_FreeViewCache(void)
6356 {
6357         if (r_refdef.viewcache.entityvisible)
6358                 Mem_Free(r_refdef.viewcache.entityvisible);
6359         if (r_refdef.viewcache.world_pvsbits)
6360                 Mem_Free(r_refdef.viewcache.world_pvsbits);
6361         if (r_refdef.viewcache.world_leafvisible)
6362                 Mem_Free(r_refdef.viewcache.world_leafvisible);
6363         if (r_refdef.viewcache.world_surfacevisible)
6364                 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6365         memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6366 }
6367
6368 void R_Main_ResizeViewCache(void)
6369 {
6370         int numentities = r_refdef.scene.numentities;
6371         int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6372         int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6373         int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6374         int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6375         if (r_refdef.viewcache.maxentities < numentities)
6376         {
6377                 r_refdef.viewcache.maxentities = numentities;
6378                 if (r_refdef.viewcache.entityvisible)
6379                         Mem_Free(r_refdef.viewcache.entityvisible);
6380                 r_refdef.viewcache.entityvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6381         }
6382         if (r_refdef.viewcache.world_numclusters != numclusters)
6383         {
6384                 r_refdef.viewcache.world_numclusters = numclusters;
6385                 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6386                 if (r_refdef.viewcache.world_pvsbits)
6387                         Mem_Free(r_refdef.viewcache.world_pvsbits);
6388                 r_refdef.viewcache.world_pvsbits = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6389         }
6390         if (r_refdef.viewcache.world_numleafs != numleafs)
6391         {
6392                 r_refdef.viewcache.world_numleafs = numleafs;
6393                 if (r_refdef.viewcache.world_leafvisible)
6394                         Mem_Free(r_refdef.viewcache.world_leafvisible);
6395                 r_refdef.viewcache.world_leafvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6396         }
6397         if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6398         {
6399                 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6400                 if (r_refdef.viewcache.world_surfacevisible)
6401                         Mem_Free(r_refdef.viewcache.world_surfacevisible);
6402                 r_refdef.viewcache.world_surfacevisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6403         }
6404 }
6405
6406 extern rtexture_t *loadingscreentexture;
6407 void gl_main_start(void)
6408 {
6409         loadingscreentexture = NULL;
6410         r_texture_blanknormalmap = NULL;
6411         r_texture_white = NULL;
6412         r_texture_grey128 = NULL;
6413         r_texture_black = NULL;
6414         r_texture_whitecube = NULL;
6415         r_texture_normalizationcube = NULL;
6416         r_texture_fogattenuation = NULL;
6417         r_texture_fogheighttexture = NULL;
6418         r_texture_gammaramps = NULL;
6419         r_texture_numcubemaps = 0;
6420
6421         r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
6422         r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6423
6424         switch(vid.renderpath)
6425         {
6426         case RENDERPATH_GL20:
6427         case RENDERPATH_CGGL:
6428                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6429                 Cvar_SetValueQuick(&gl_combine, 1);
6430                 Cvar_SetValueQuick(&r_glsl, 1);
6431                 r_loadnormalmap = true;
6432                 r_loadgloss = true;
6433                 r_loadfog = false;
6434                 break;
6435         case RENDERPATH_GL13:
6436                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6437                 Cvar_SetValueQuick(&gl_combine, 1);
6438                 Cvar_SetValueQuick(&r_glsl, 0);
6439                 r_loadnormalmap = false;
6440                 r_loadgloss = false;
6441                 r_loadfog = true;
6442                 break;
6443         case RENDERPATH_GL11:
6444                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6445                 Cvar_SetValueQuick(&gl_combine, 0);
6446                 Cvar_SetValueQuick(&r_glsl, 0);
6447                 r_loadnormalmap = false;
6448                 r_loadgloss = false;
6449                 r_loadfog = true;
6450                 break;
6451         }
6452
6453         R_AnimCache_Free();
6454         R_FrameData_Reset();
6455
6456         r_numqueries = 0;
6457         r_maxqueries = 0;
6458         memset(r_queries, 0, sizeof(r_queries));
6459
6460         r_qwskincache = NULL;
6461         r_qwskincache_size = 0;
6462
6463         // set up r_skinframe loading system for textures
6464         memset(&r_skinframe, 0, sizeof(r_skinframe));
6465         r_skinframe.loadsequence = 1;
6466         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6467
6468         r_main_texturepool = R_AllocTexturePool();
6469         R_BuildBlankTextures();
6470         R_BuildNoTexture();
6471         if (vid.support.arb_texture_cube_map)
6472         {
6473                 R_BuildWhiteCube();
6474                 R_BuildNormalizationCube();
6475         }
6476         r_texture_fogattenuation = NULL;
6477         r_texture_fogheighttexture = NULL;
6478         r_texture_gammaramps = NULL;
6479         //r_texture_fogintensity = NULL;
6480         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6481         memset(&r_waterstate, 0, sizeof(r_waterstate));
6482         r_glsl_permutation = NULL;
6483         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6484         Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6485         glslshaderstring = NULL;
6486 #ifdef SUPPORTCG
6487         r_cg_permutation = NULL;
6488         memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6489         Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
6490         cgshaderstring = NULL;
6491 #endif
6492         memset(&r_svbsp, 0, sizeof (r_svbsp));
6493
6494         r_refdef.fogmasktable_density = 0;
6495 }
6496
6497 void gl_main_shutdown(void)
6498 {
6499         R_AnimCache_Free();
6500         R_FrameData_Reset();
6501
6502         R_Main_FreeViewCache();
6503
6504         if (r_maxqueries)
6505                 qglDeleteQueriesARB(r_maxqueries, r_queries);
6506
6507         r_numqueries = 0;
6508         r_maxqueries = 0;
6509         memset(r_queries, 0, sizeof(r_queries));
6510
6511         r_qwskincache = NULL;
6512         r_qwskincache_size = 0;
6513
6514         // clear out the r_skinframe state
6515         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6516         memset(&r_skinframe, 0, sizeof(r_skinframe));
6517
6518         if (r_svbsp.nodes)
6519                 Mem_Free(r_svbsp.nodes);
6520         memset(&r_svbsp, 0, sizeof (r_svbsp));
6521         R_FreeTexturePool(&r_main_texturepool);
6522         loadingscreentexture = NULL;
6523         r_texture_blanknormalmap = NULL;
6524         r_texture_white = NULL;
6525         r_texture_grey128 = NULL;
6526         r_texture_black = NULL;
6527         r_texture_whitecube = NULL;
6528         r_texture_normalizationcube = NULL;
6529         r_texture_fogattenuation = NULL;
6530         r_texture_fogheighttexture = NULL;
6531         r_texture_gammaramps = NULL;
6532         r_texture_numcubemaps = 0;
6533         //r_texture_fogintensity = NULL;
6534         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6535         memset(&r_waterstate, 0, sizeof(r_waterstate));
6536         r_glsl_permutation = NULL;
6537         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6538         glslshaderstring = NULL;
6539 #ifdef SUPPORTCG
6540         r_cg_permutation = NULL;
6541         memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6542         cgshaderstring = NULL;
6543 #endif
6544         R_GLSL_Restart_f();
6545 }
6546
6547 extern void CL_ParseEntityLump(char *entitystring);
6548 void gl_main_newmap(void)
6549 {
6550         // FIXME: move this code to client
6551         char *entities, entname[MAX_QPATH];
6552         if (r_qwskincache)
6553                 Mem_Free(r_qwskincache);
6554         r_qwskincache = NULL;
6555         r_qwskincache_size = 0;
6556         if (cl.worldmodel)
6557         {
6558                 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
6559                 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6560                 {
6561                         CL_ParseEntityLump(entities);
6562                         Mem_Free(entities);
6563                         return;
6564                 }
6565                 if (cl.worldmodel->brush.entities)
6566                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
6567         }
6568         R_Main_FreeViewCache();
6569
6570         R_FrameData_Reset();
6571 }
6572
6573 void GL_Main_Init(void)
6574 {
6575         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6576
6577         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6578         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6579         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6580         if (gamemode == GAME_NEHAHRA)
6581         {
6582                 Cvar_RegisterVariable (&gl_fogenable);
6583                 Cvar_RegisterVariable (&gl_fogdensity);
6584                 Cvar_RegisterVariable (&gl_fogred);
6585                 Cvar_RegisterVariable (&gl_foggreen);
6586                 Cvar_RegisterVariable (&gl_fogblue);
6587                 Cvar_RegisterVariable (&gl_fogstart);
6588                 Cvar_RegisterVariable (&gl_fogend);
6589                 Cvar_RegisterVariable (&gl_skyclip);
6590         }
6591         Cvar_RegisterVariable(&r_motionblur);
6592         Cvar_RegisterVariable(&r_motionblur_maxblur);
6593         Cvar_RegisterVariable(&r_motionblur_bmin);
6594         Cvar_RegisterVariable(&r_motionblur_vmin);
6595         Cvar_RegisterVariable(&r_motionblur_vmax);
6596         Cvar_RegisterVariable(&r_motionblur_vcoeff);
6597         Cvar_RegisterVariable(&r_motionblur_randomize);
6598         Cvar_RegisterVariable(&r_damageblur);
6599         Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6600         Cvar_RegisterVariable(&r_equalize_entities_minambient);
6601         Cvar_RegisterVariable(&r_equalize_entities_by);
6602         Cvar_RegisterVariable(&r_equalize_entities_to);
6603         Cvar_RegisterVariable(&r_depthfirst);
6604         Cvar_RegisterVariable(&r_useinfinitefarclip);
6605         Cvar_RegisterVariable(&r_farclip_base);
6606         Cvar_RegisterVariable(&r_farclip_world);
6607         Cvar_RegisterVariable(&r_nearclip);
6608         Cvar_RegisterVariable(&r_showbboxes);
6609         Cvar_RegisterVariable(&r_showsurfaces);
6610         Cvar_RegisterVariable(&r_showtris);
6611         Cvar_RegisterVariable(&r_shownormals);
6612         Cvar_RegisterVariable(&r_showlighting);
6613         Cvar_RegisterVariable(&r_showshadowvolumes);
6614         Cvar_RegisterVariable(&r_showcollisionbrushes);
6615         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6616         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6617         Cvar_RegisterVariable(&r_showdisabledepthtest);
6618         Cvar_RegisterVariable(&r_drawportals);
6619         Cvar_RegisterVariable(&r_drawentities);
6620         Cvar_RegisterVariable(&r_draw2d);
6621         Cvar_RegisterVariable(&r_drawworld);
6622         Cvar_RegisterVariable(&r_cullentities_trace);
6623         Cvar_RegisterVariable(&r_cullentities_trace_samples);
6624         Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6625         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6626         Cvar_RegisterVariable(&r_cullentities_trace_delay);
6627         Cvar_RegisterVariable(&r_drawviewmodel);
6628         Cvar_RegisterVariable(&r_drawexteriormodel);
6629         Cvar_RegisterVariable(&r_speeds);
6630         Cvar_RegisterVariable(&r_fullbrights);
6631         Cvar_RegisterVariable(&r_wateralpha);
6632         Cvar_RegisterVariable(&r_dynamic);
6633         Cvar_RegisterVariable(&r_fakelight);
6634         Cvar_RegisterVariable(&r_fakelight_intensity);
6635         Cvar_RegisterVariable(&r_fullbright);
6636         Cvar_RegisterVariable(&r_shadows);
6637         Cvar_RegisterVariable(&r_shadows_darken);
6638         Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6639         Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6640         Cvar_RegisterVariable(&r_shadows_throwdistance);
6641         Cvar_RegisterVariable(&r_shadows_throwdirection);
6642         Cvar_RegisterVariable(&r_shadows_focus);
6643         Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6644         Cvar_RegisterVariable(&r_q1bsp_skymasking);
6645         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6646         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6647         Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6648         Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6649         Cvar_RegisterVariable(&r_fog_exp2);
6650         Cvar_RegisterVariable(&r_drawfog);
6651         Cvar_RegisterVariable(&r_transparentdepthmasking);
6652         Cvar_RegisterVariable(&r_texture_dds_load);
6653         Cvar_RegisterVariable(&r_texture_dds_save);
6654         Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6655         Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6656         Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6657         Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6658         Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6659         Cvar_RegisterVariable(&r_textureunits);
6660         Cvar_RegisterVariable(&gl_combine);
6661         Cvar_RegisterVariable(&r_glsl);
6662         Cvar_RegisterVariable(&r_glsl_deluxemapping);
6663         Cvar_RegisterVariable(&r_glsl_offsetmapping);
6664         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6665         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6666         Cvar_RegisterVariable(&r_glsl_postprocess);
6667         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6668         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6669         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6670         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6671         Cvar_RegisterVariable(&r_water);
6672         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6673         Cvar_RegisterVariable(&r_water_clippingplanebias);
6674         Cvar_RegisterVariable(&r_water_refractdistort);
6675         Cvar_RegisterVariable(&r_water_reflectdistort);
6676         Cvar_RegisterVariable(&r_water_scissormode);
6677         Cvar_RegisterVariable(&r_lerpsprites);
6678         Cvar_RegisterVariable(&r_lerpmodels);
6679         Cvar_RegisterVariable(&r_lerplightstyles);
6680         Cvar_RegisterVariable(&r_waterscroll);
6681         Cvar_RegisterVariable(&r_bloom);
6682         Cvar_RegisterVariable(&r_bloom_colorscale);
6683         Cvar_RegisterVariable(&r_bloom_brighten);
6684         Cvar_RegisterVariable(&r_bloom_blur);
6685         Cvar_RegisterVariable(&r_bloom_resolution);
6686         Cvar_RegisterVariable(&r_bloom_colorexponent);
6687         Cvar_RegisterVariable(&r_bloom_colorsubtract);
6688         Cvar_RegisterVariable(&r_hdr);
6689         Cvar_RegisterVariable(&r_hdr_scenebrightness);
6690         Cvar_RegisterVariable(&r_hdr_glowintensity);
6691         Cvar_RegisterVariable(&r_hdr_range);
6692         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6693         Cvar_RegisterVariable(&developer_texturelogging);
6694         Cvar_RegisterVariable(&gl_lightmaps);
6695         Cvar_RegisterVariable(&r_test);
6696         Cvar_RegisterVariable(&r_batchmode);
6697         Cvar_RegisterVariable(&r_glsl_saturation);
6698         Cvar_RegisterVariable(&r_framedatasize);
6699         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
6700                 Cvar_SetValue("r_fullbrights", 0);
6701         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
6702
6703         Cvar_RegisterVariable(&r_track_sprites);
6704         Cvar_RegisterVariable(&r_track_sprites_flags);
6705         Cvar_RegisterVariable(&r_track_sprites_scalew);
6706         Cvar_RegisterVariable(&r_track_sprites_scaleh);
6707         Cvar_RegisterVariable(&r_overheadsprites_perspective);
6708         Cvar_RegisterVariable(&r_overheadsprites_pushback);
6709 }
6710
6711 extern void R_Textures_Init(void);
6712 extern void GL_Draw_Init(void);
6713 extern void GL_Main_Init(void);
6714 extern void R_Shadow_Init(void);
6715 extern void R_Sky_Init(void);
6716 extern void GL_Surf_Init(void);
6717 extern void R_Particles_Init(void);
6718 extern void R_Explosion_Init(void);
6719 extern void gl_backend_init(void);
6720 extern void Sbar_Init(void);
6721 extern void R_LightningBeams_Init(void);
6722 extern void Mod_RenderInit(void);
6723 extern void Font_Init(void);
6724
6725 void Render_Init(void)
6726 {
6727         gl_backend_init();
6728         R_Textures_Init();
6729         GL_Main_Init();
6730         Font_Init();
6731         GL_Draw_Init();
6732         R_Shadow_Init();
6733         R_Sky_Init();
6734         GL_Surf_Init();
6735         Sbar_Init();
6736         R_Particles_Init();
6737         R_Explosion_Init();
6738         R_LightningBeams_Init();
6739         Mod_RenderInit();
6740 }
6741
6742 /*
6743 ===============
6744 GL_Init
6745 ===============
6746 */
6747 extern char *ENGINE_EXTENSIONS;
6748 void GL_Init (void)
6749 {
6750         gl_renderer = (const char *)qglGetString(GL_RENDERER);
6751         gl_vendor = (const char *)qglGetString(GL_VENDOR);
6752         gl_version = (const char *)qglGetString(GL_VERSION);
6753         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
6754
6755         if (!gl_extensions)
6756                 gl_extensions = "";
6757         if (!gl_platformextensions)
6758                 gl_platformextensions = "";
6759
6760         Con_Printf("GL_VENDOR: %s\n", gl_vendor);
6761         Con_Printf("GL_RENDERER: %s\n", gl_renderer);
6762         Con_Printf("GL_VERSION: %s\n", gl_version);
6763         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
6764         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
6765
6766         VID_CheckExtensions();
6767
6768         // LordHavoc: report supported extensions
6769         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
6770
6771         // clear to black (loading plaque will be seen over this)
6772         CHECKGLERROR
6773         qglClearColor(0,0,0,1);CHECKGLERROR
6774         qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
6775 }
6776
6777 int R_CullBox(const vec3_t mins, const vec3_t maxs)
6778 {
6779         int i;
6780         mplane_t *p;
6781         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
6782         {
6783                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
6784                 if (i == 4)
6785                         continue;
6786                 p = r_refdef.view.frustum + i;
6787                 switch(p->signbits)
6788                 {
6789                 default:
6790                 case 0:
6791                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6792                                 return true;
6793                         break;
6794                 case 1:
6795                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6796                                 return true;
6797                         break;
6798                 case 2:
6799                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6800                                 return true;
6801                         break;
6802                 case 3:
6803                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6804                                 return true;
6805                         break;
6806                 case 4:
6807                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6808                                 return true;
6809                         break;
6810                 case 5:
6811                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6812                                 return true;
6813                         break;
6814                 case 6:
6815                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6816                                 return true;
6817                         break;
6818                 case 7:
6819                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6820                                 return true;
6821                         break;
6822                 }
6823         }
6824         return false;
6825 }
6826
6827 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
6828 {
6829         int i;
6830         const mplane_t *p;
6831         for (i = 0;i < numplanes;i++)
6832         {
6833                 p = planes + i;
6834                 switch(p->signbits)
6835                 {
6836                 default:
6837                 case 0:
6838                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6839                                 return true;
6840                         break;
6841                 case 1:
6842                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6843                                 return true;
6844                         break;
6845                 case 2:
6846                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6847                                 return true;
6848                         break;
6849                 case 3:
6850                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6851                                 return true;
6852                         break;
6853                 case 4:
6854                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6855                                 return true;
6856                         break;
6857                 case 5:
6858                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6859                                 return true;
6860                         break;
6861                 case 6:
6862                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6863                                 return true;
6864                         break;
6865                 case 7:
6866                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6867                                 return true;
6868                         break;
6869                 }
6870         }
6871         return false;
6872 }
6873
6874 //==================================================================================
6875
6876 // LordHavoc: this stores temporary data used within the same frame
6877
6878 qboolean r_framedata_failed;
6879 static size_t r_framedata_size;
6880 static size_t r_framedata_current;
6881 static void *r_framedata_base;
6882
6883 void R_FrameData_Reset(void)
6884 {
6885         if (r_framedata_base)
6886                 Mem_Free(r_framedata_base);
6887         r_framedata_base = NULL;
6888         r_framedata_size = 0;
6889         r_framedata_current = 0;
6890         r_framedata_failed = false;
6891 }
6892
6893 void R_FrameData_NewFrame(void)
6894 {
6895         size_t wantedsize;
6896         if (r_framedata_failed)
6897                 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
6898         wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
6899         wantedsize = bound(65536, wantedsize, 128*1024*1024);
6900         if (r_framedata_size != wantedsize)
6901         {
6902                 r_framedata_size = wantedsize;
6903                 if (r_framedata_base)
6904                         Mem_Free(r_framedata_base);
6905                 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
6906         }
6907         r_framedata_current = 0;
6908         r_framedata_failed = false;
6909 }
6910
6911 void *R_FrameData_Alloc(size_t size)
6912 {
6913         void *data;
6914
6915         // align to 16 byte boundary
6916         size = (size + 15) & ~15;
6917         data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
6918         r_framedata_current += size;
6919
6920         // check overflow
6921         if (r_framedata_current > r_framedata_size)
6922                 r_framedata_failed = true;
6923
6924         // return NULL on everything after a failure
6925         if (r_framedata_failed)
6926                 return NULL;
6927
6928         return data;
6929 }
6930
6931 void *R_FrameData_Store(size_t size, void *data)
6932 {
6933         void *d = R_FrameData_Alloc(size);
6934         if (d)
6935                 memcpy(d, data, size);
6936         return d;
6937 }
6938
6939 //==================================================================================
6940
6941 // LordHavoc: animcache originally written by Echon, rewritten since then
6942
6943 /**
6944  * Animation cache prevents re-generating mesh data for an animated model
6945  * multiple times in one frame for lighting, shadowing, reflections, etc.
6946  */
6947
6948 void R_AnimCache_Free(void)
6949 {
6950 }
6951
6952 void R_AnimCache_ClearCache(void)
6953 {
6954         int i;
6955         entity_render_t *ent;
6956
6957         for (i = 0;i < r_refdef.scene.numentities;i++)
6958         {
6959                 ent = r_refdef.scene.entities[i];
6960                 ent->animcache_vertex3f = NULL;
6961                 ent->animcache_normal3f = NULL;
6962                 ent->animcache_svector3f = NULL;
6963                 ent->animcache_tvector3f = NULL;
6964         }
6965 }
6966
6967 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
6968 {
6969         dp_model_t *model = ent->model;
6970         int numvertices;
6971         // see if it's already cached this frame
6972         if (ent->animcache_vertex3f)
6973         {
6974                 // add normals/tangents if needed
6975                 if (wantnormals || wanttangents)
6976                 {
6977                         if (ent->animcache_normal3f)
6978                                 wantnormals = false;
6979                         if (ent->animcache_svector3f)
6980                                 wanttangents = false;
6981                         if (wantnormals || wanttangents)
6982                         {
6983                                 numvertices = model->surfmesh.num_vertices;
6984                                 if (wantnormals)
6985                                         ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6986                                 if (wanttangents)
6987                                 {
6988                                         ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6989                                         ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6990                                 }
6991                                 if (!r_framedata_failed)
6992                                         model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
6993                         }
6994                 }
6995         }
6996         else
6997         {
6998                 // see if this ent is worth caching
6999                 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
7000                         return false;
7001                 // get some memory for this entity and generate mesh data
7002                 numvertices = model->surfmesh.num_vertices;
7003                 ent->animcache_vertex3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
7004                 if (wantnormals)
7005                         ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
7006                 if (wanttangents)
7007                 {
7008                         ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
7009                         ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
7010                 }
7011                 if (!r_framedata_failed)
7012                         model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
7013         }
7014         return !r_framedata_failed;
7015 }
7016
7017 void R_AnimCache_CacheVisibleEntities(void)
7018 {
7019         int i;
7020         qboolean wantnormals = !r_showsurfaces.integer;
7021         qboolean wanttangents = !r_showsurfaces.integer;
7022
7023         switch(vid.renderpath)
7024         {
7025         case RENDERPATH_GL20:
7026         case RENDERPATH_CGGL:
7027                 break;
7028         case RENDERPATH_GL13:
7029         case RENDERPATH_GL11:
7030                 wanttangents = false;
7031                 break;
7032         }
7033
7034         // TODO: thread this
7035         // NOTE: R_PrepareRTLights() also caches entities
7036
7037         for (i = 0;i < r_refdef.scene.numentities;i++)
7038                 if (r_refdef.viewcache.entityvisible[i])
7039                         R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
7040 }
7041
7042 //==================================================================================
7043
7044 static void R_View_UpdateEntityLighting (void)
7045 {
7046         int i;
7047         entity_render_t *ent;
7048         vec3_t tempdiffusenormal, avg;
7049         vec_t f, fa, fd, fdd;
7050         qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
7051
7052         for (i = 0;i < r_refdef.scene.numentities;i++)
7053         {
7054                 ent = r_refdef.scene.entities[i];
7055
7056                 // skip unseen models
7057                 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
7058                         continue;
7059
7060                 // skip bsp models
7061                 if (ent->model && ent->model->brush.num_leafs)
7062                 {
7063                         // TODO: use modellight for r_ambient settings on world?
7064                         VectorSet(ent->modellight_ambient, 0, 0, 0);
7065                         VectorSet(ent->modellight_diffuse, 0, 0, 0);
7066                         VectorSet(ent->modellight_lightdir, 0, 0, 1);
7067                         continue;
7068                 }
7069
7070                 // fetch the lighting from the worldmodel data
7071                 VectorClear(ent->modellight_ambient);
7072                 VectorClear(ent->modellight_diffuse);
7073                 VectorClear(tempdiffusenormal);
7074                 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
7075                 {
7076                         vec3_t org;
7077                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7078                         r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
7079                         if(ent->flags & RENDER_EQUALIZE)
7080                         {
7081                                 // first fix up ambient lighting...
7082                                 if(r_equalize_entities_minambient.value > 0)
7083                                 {
7084                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7085                                         if(fd > 0)
7086                                         {
7087                                                 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
7088                                                 if(fa < r_equalize_entities_minambient.value * fd)
7089                                                 {
7090                                                         // solve:
7091                                                         //   fa'/fd' = minambient
7092                                                         //   fa'+0.25*fd' = fa+0.25*fd
7093                                                         //   ...
7094                                                         //   fa' = fd' * minambient
7095                                                         //   fd'*(0.25+minambient) = fa+0.25*fd
7096                                                         //   ...
7097                                                         //   fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7098                                                         //   fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7099                                                         //   ...
7100                                                         fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7101                                                         f = fdd / fd; // f>0 because all this is additive; f<1 because fdd<fd because this follows from fa < r_equalize_entities_minambient.value * fd
7102                                                         VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7103                                                         VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7104                                                 }
7105                                         }
7106                                 }
7107
7108                                 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7109                                 {
7110                                         VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
7111                                         f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
7112                                         if(f > 0)
7113                                         {
7114                                                 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
7115                                                 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
7116                                                 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7117                                         }
7118                                 }
7119                         }
7120                 }
7121                 else // highly rare
7122                         VectorSet(ent->modellight_ambient, 1, 1, 1);
7123
7124                 // move the light direction into modelspace coordinates for lighting code
7125                 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7126                 if(VectorLength2(ent->modellight_lightdir) == 0)
7127                         VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7128                 VectorNormalize(ent->modellight_lightdir);
7129         }
7130 }
7131
7132 #define MAX_LINEOFSIGHTTRACES 64
7133
7134 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7135 {
7136         int i;
7137         vec3_t boxmins, boxmaxs;
7138         vec3_t start;
7139         vec3_t end;
7140         dp_model_t *model = r_refdef.scene.worldmodel;
7141
7142         if (!model || !model->brush.TraceLineOfSight)
7143                 return true;
7144
7145         // expand the box a little
7146         boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7147         boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7148         boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7149         boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7150         boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7151         boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7152
7153         // return true if eye is inside enlarged box
7154         if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7155                 return true;
7156
7157         // try center
7158         VectorCopy(eye, start);
7159         VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7160         if (model->brush.TraceLineOfSight(model, start, end))
7161                 return true;
7162
7163         // try various random positions
7164         for (i = 0;i < numsamples;i++)
7165         {
7166                 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7167                 if (model->brush.TraceLineOfSight(model, start, end))
7168                         return true;
7169         }
7170
7171         return false;
7172 }
7173
7174
7175 static void R_View_UpdateEntityVisible (void)
7176 {
7177         int i;
7178         int renderimask;
7179         int samples;
7180         entity_render_t *ent;
7181
7182         renderimask = r_refdef.envmap                                    ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7183                 : r_waterstate.renderingrefraction                       ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7184                 : (chase_active.integer || r_waterstate.renderingscene)  ? RENDER_VIEWMODEL
7185                 :                                                          RENDER_EXTERIORMODEL;
7186         if (!r_drawviewmodel.integer)
7187                 renderimask |= RENDER_VIEWMODEL;
7188         if (!r_drawexteriormodel.integer)
7189                 renderimask |= RENDER_EXTERIORMODEL;
7190         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7191         {
7192                 // worldmodel can check visibility
7193                 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7194                 for (i = 0;i < r_refdef.scene.numentities;i++)
7195                 {
7196                         ent = r_refdef.scene.entities[i];
7197                         if (!(ent->flags & renderimask))
7198                         if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
7199                         if ((ent->flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL)) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs))
7200                                 r_refdef.viewcache.entityvisible[i] = true;
7201                 }
7202                 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7203                         // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7204                 {
7205                         for (i = 0;i < r_refdef.scene.numentities;i++)
7206                         {
7207                                 ent = r_refdef.scene.entities[i];
7208                                 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7209                                 {
7210                                         samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7211                                         if (samples < 0)
7212                                                 continue; // temp entities do pvs only
7213                                         if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7214                                                 ent->last_trace_visibility = realtime;
7215                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7216                                                 r_refdef.viewcache.entityvisible[i] = 0;
7217                                 }
7218                         }
7219                 }
7220         }
7221         else
7222         {
7223                 // no worldmodel or it can't check visibility
7224                 for (i = 0;i < r_refdef.scene.numentities;i++)
7225                 {
7226                         ent = r_refdef.scene.entities[i];
7227                         r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
7228                 }
7229         }
7230 }
7231
7232 /// only used if skyrendermasked, and normally returns false
7233 int R_DrawBrushModelsSky (void)
7234 {
7235         int i, sky;
7236         entity_render_t *ent;
7237
7238         sky = false;
7239         for (i = 0;i < r_refdef.scene.numentities;i++)
7240         {
7241                 if (!r_refdef.viewcache.entityvisible[i])
7242                         continue;
7243                 ent = r_refdef.scene.entities[i];
7244                 if (!ent->model || !ent->model->DrawSky)
7245                         continue;
7246                 ent->model->DrawSky(ent);
7247                 sky = true;
7248         }
7249         return sky;
7250 }
7251
7252 static void R_DrawNoModel(entity_render_t *ent);
7253 static void R_DrawModels(void)
7254 {
7255         int i;
7256         entity_render_t *ent;
7257
7258         for (i = 0;i < r_refdef.scene.numentities;i++)
7259         {
7260                 if (!r_refdef.viewcache.entityvisible[i])
7261                         continue;
7262                 ent = r_refdef.scene.entities[i];
7263                 r_refdef.stats.entities++;
7264                 if (ent->model && ent->model->Draw != NULL)
7265                         ent->model->Draw(ent);
7266                 else
7267                         R_DrawNoModel(ent);
7268         }
7269 }
7270
7271 static void R_DrawModelsDepth(void)
7272 {
7273         int i;
7274         entity_render_t *ent;
7275
7276         for (i = 0;i < r_refdef.scene.numentities;i++)
7277         {
7278                 if (!r_refdef.viewcache.entityvisible[i])
7279                         continue;
7280                 ent = r_refdef.scene.entities[i];
7281                 if (ent->model && ent->model->DrawDepth != NULL)
7282                         ent->model->DrawDepth(ent);
7283         }
7284 }
7285
7286 static void R_DrawModelsDebug(void)
7287 {
7288         int i;
7289         entity_render_t *ent;
7290
7291         for (i = 0;i < r_refdef.scene.numentities;i++)
7292         {
7293                 if (!r_refdef.viewcache.entityvisible[i])
7294                         continue;
7295                 ent = r_refdef.scene.entities[i];
7296                 if (ent->model && ent->model->DrawDebug != NULL)
7297                         ent->model->DrawDebug(ent);
7298         }
7299 }
7300
7301 static void R_DrawModelsAddWaterPlanes(void)
7302 {
7303         int i;
7304         entity_render_t *ent;
7305
7306         for (i = 0;i < r_refdef.scene.numentities;i++)
7307         {
7308                 if (!r_refdef.viewcache.entityvisible[i])
7309                         continue;
7310                 ent = r_refdef.scene.entities[i];
7311                 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7312                         ent->model->DrawAddWaterPlanes(ent);
7313         }
7314 }
7315
7316 static void R_View_SetFrustum(const int *scissor)
7317 {
7318         int i;
7319         double fpx, fnx, fpy, fny;
7320         vec3_t forward, left, up, origin, v;
7321
7322         if(scissor)
7323         {
7324                 // flipped x coordinates (because x points left here)
7325                 fpx =  1.0 - 2.0 * (scissor[0]              - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
7326                 fnx =  1.0 - 2.0 * (scissor[0] + scissor[2] - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
7327
7328                 // non-flipped y coordinates
7329                 fny = -1.0 + 2.0 * (scissor[1]              - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7330                 fpy = -1.0 + 2.0 * (scissor[1] + scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7331         }
7332         else
7333         {
7334                 fnx = fny = -1;
7335                 fpx = fpy = +1;
7336         }
7337
7338         // we can't trust r_refdef.view.forward and friends in reflected scenes
7339         Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7340
7341 #if 0
7342         r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7343         r_refdef.view.frustum[0].normal[1] = 0 - 0;
7344         r_refdef.view.frustum[0].normal[2] = -1 - 0;
7345         r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7346         r_refdef.view.frustum[1].normal[1] = 0 + 0;
7347         r_refdef.view.frustum[1].normal[2] = -1 + 0;
7348         r_refdef.view.frustum[2].normal[0] = 0 - 0;
7349         r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7350         r_refdef.view.frustum[2].normal[2] = -1 - 0;
7351         r_refdef.view.frustum[3].normal[0] = 0 + 0;
7352         r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7353         r_refdef.view.frustum[3].normal[2] = -1 + 0;
7354 #endif
7355
7356 #if 0
7357         zNear = r_refdef.nearclip;
7358         nudge = 1.0 - 1.0 / (1<<23);
7359         r_refdef.view.frustum[4].normal[0] = 0 - 0;
7360         r_refdef.view.frustum[4].normal[1] = 0 - 0;
7361         r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7362         r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7363         r_refdef.view.frustum[5].normal[0] = 0 + 0;
7364         r_refdef.view.frustum[5].normal[1] = 0 + 0;
7365         r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7366         r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7367 #endif
7368
7369
7370
7371 #if 0
7372         r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7373         r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7374         r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7375         r_refdef.view.frustum[0].dist = m[15] - m[12];
7376
7377         r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7378         r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7379         r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7380         r_refdef.view.frustum[1].dist = m[15] + m[12];
7381
7382         r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7383         r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7384         r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7385         r_refdef.view.frustum[2].dist = m[15] - m[13];
7386
7387         r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7388         r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7389         r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7390         r_refdef.view.frustum[3].dist = m[15] + m[13];
7391
7392         r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7393         r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7394         r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7395         r_refdef.view.frustum[4].dist = m[15] - m[14];
7396
7397         r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7398         r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7399         r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7400         r_refdef.view.frustum[5].dist = m[15] + m[14];
7401 #endif
7402
7403         if (r_refdef.view.useperspective)
7404         {
7405                 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7406                 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[0]);
7407                 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[1]);
7408                 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[2]);
7409                 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[3]);
7410
7411                 // then the normals from the corners relative to origin
7412                 CrossProduct(r_refdef.view.frustumcorner[2], r_refdef.view.frustumcorner[0], r_refdef.view.frustum[0].normal);
7413                 CrossProduct(r_refdef.view.frustumcorner[1], r_refdef.view.frustumcorner[3], r_refdef.view.frustum[1].normal);
7414                 CrossProduct(r_refdef.view.frustumcorner[0], r_refdef.view.frustumcorner[1], r_refdef.view.frustum[2].normal);
7415                 CrossProduct(r_refdef.view.frustumcorner[3], r_refdef.view.frustumcorner[2], r_refdef.view.frustum[3].normal);
7416
7417                 // in a NORMAL view, forward cross left == up
7418                 // in a REFLECTED view, forward cross left == down
7419                 // so our cross products above need to be adjusted for a left handed coordinate system
7420                 CrossProduct(forward, left, v);
7421                 if(DotProduct(v, up) < 0)
7422                 {
7423                         VectorNegate(r_refdef.view.frustum[0].normal, r_refdef.view.frustum[0].normal);
7424                         VectorNegate(r_refdef.view.frustum[1].normal, r_refdef.view.frustum[1].normal);
7425                         VectorNegate(r_refdef.view.frustum[2].normal, r_refdef.view.frustum[2].normal);
7426                         VectorNegate(r_refdef.view.frustum[3].normal, r_refdef.view.frustum[3].normal);
7427                 }
7428
7429                 // Leaving those out was a mistake, those were in the old code, and they
7430                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7431                 // I couldn't reproduce it after adding those normalizations. --blub
7432                 VectorNormalize(r_refdef.view.frustum[0].normal);
7433                 VectorNormalize(r_refdef.view.frustum[1].normal);
7434                 VectorNormalize(r_refdef.view.frustum[2].normal);
7435                 VectorNormalize(r_refdef.view.frustum[3].normal);
7436
7437                 // make the corners absolute
7438                 VectorAdd(r_refdef.view.frustumcorner[0], r_refdef.view.origin, r_refdef.view.frustumcorner[0]);
7439                 VectorAdd(r_refdef.view.frustumcorner[1], r_refdef.view.origin, r_refdef.view.frustumcorner[1]);
7440                 VectorAdd(r_refdef.view.frustumcorner[2], r_refdef.view.origin, r_refdef.view.frustumcorner[2]);
7441                 VectorAdd(r_refdef.view.frustumcorner[3], r_refdef.view.origin, r_refdef.view.frustumcorner[3]);
7442
7443                 // one more normal
7444                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7445
7446                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7447                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7448                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7449                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7450                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7451         }
7452         else
7453         {
7454                 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7455                 VectorScale(left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7456                 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7457                 VectorScale(up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7458                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7459                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7460                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7461                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7462                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7463                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7464         }
7465         r_refdef.view.numfrustumplanes = 5;
7466
7467         if (r_refdef.view.useclipplane)
7468         {
7469                 r_refdef.view.numfrustumplanes = 6;
7470                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7471         }
7472
7473         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7474                 PlaneClassify(r_refdef.view.frustum + i);
7475
7476         // LordHavoc: note to all quake engine coders, Quake had a special case
7477         // for 90 degrees which assumed a square view (wrong), so I removed it,
7478         // Quake2 has it disabled as well.
7479
7480         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7481         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7482         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7483         //PlaneClassify(&frustum[0]);
7484
7485         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7486         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7487         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7488         //PlaneClassify(&frustum[1]);
7489
7490         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7491         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7492         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7493         //PlaneClassify(&frustum[2]);
7494
7495         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7496         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7497         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7498         //PlaneClassify(&frustum[3]);
7499
7500         // nearclip plane
7501         //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7502         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7503         //PlaneClassify(&frustum[4]);
7504 }
7505
7506 void R_View_UpdateWithScissor(const int *myscissor)
7507 {
7508         R_Main_ResizeViewCache();
7509         R_View_SetFrustum(myscissor);
7510         R_View_WorldVisibility(r_refdef.view.useclipplane);
7511         R_View_UpdateEntityVisible();
7512         R_View_UpdateEntityLighting();
7513 }
7514
7515 void R_View_Update(void)
7516 {
7517         R_Main_ResizeViewCache();
7518         R_View_SetFrustum(NULL);
7519         R_View_WorldVisibility(r_refdef.view.useclipplane);
7520         R_View_UpdateEntityVisible();
7521         R_View_UpdateEntityLighting();
7522 }
7523
7524 void R_SetupView(qboolean allowwaterclippingplane)
7525 {
7526         const float *customclipplane = NULL;
7527         float plane[4];
7528         if (r_refdef.view.useclipplane && allowwaterclippingplane)
7529         {
7530                 // LordHavoc: couldn't figure out how to make this approach the
7531                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7532                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7533                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7534                         dist = r_refdef.view.clipplane.dist;
7535                 plane[0] = r_refdef.view.clipplane.normal[0];
7536                 plane[1] = r_refdef.view.clipplane.normal[1];
7537                 plane[2] = r_refdef.view.clipplane.normal[2];
7538                 plane[3] = dist;
7539                 customclipplane = plane;
7540         }
7541
7542         if (!r_refdef.view.useperspective)
7543                 R_Viewport_InitOrtho(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, -r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip, customclipplane);
7544         else if (vid.stencil && r_useinfinitefarclip.integer)
7545                 R_Viewport_InitPerspectiveInfinite(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, customclipplane);
7546         else
7547                 R_Viewport_InitPerspective(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip, customclipplane);
7548         R_SetViewport(&r_refdef.view.viewport);
7549 }
7550
7551 void R_EntityMatrix(const matrix4x4_t *matrix)
7552 {
7553         if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7554         {
7555                 gl_modelmatrixchanged = false;
7556                 gl_modelmatrix = *matrix;
7557                 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
7558                 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
7559                 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
7560                 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
7561                 CHECKGLERROR
7562                 switch(vid.renderpath)
7563                 {
7564                 case RENDERPATH_GL20:
7565                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
7566                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
7567                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7568                         break;
7569                 case RENDERPATH_CGGL:
7570 #ifdef SUPPORTCG
7571                         CHECKCGERROR
7572                         if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
7573                         if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
7574                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7575 #endif
7576                         break;
7577                 case RENDERPATH_GL13:
7578                 case RENDERPATH_GL11:
7579                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7580                         break;
7581                 }
7582         }
7583 }
7584
7585 void R_ResetViewRendering2D(void)
7586 {
7587         r_viewport_t viewport;
7588         DrawQ_Finish();
7589
7590         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
7591         R_Viewport_InitOrtho(&viewport, &identitymatrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, 0, 0, 1, 1, -10, 100, NULL);
7592         R_SetViewport(&viewport);
7593         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
7594         GL_Color(1, 1, 1, 1);
7595         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7596         GL_BlendFunc(GL_ONE, GL_ZERO);
7597         GL_AlphaTest(false);
7598         GL_ScissorTest(false);
7599         GL_DepthMask(false);
7600         GL_DepthRange(0, 1);
7601         GL_DepthTest(false);
7602         R_EntityMatrix(&identitymatrix);
7603         R_Mesh_ResetTextureState();
7604         GL_PolygonOffset(0, 0);
7605         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7606         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7607         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7608         qglStencilMask(~0);CHECKGLERROR
7609         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7610         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7611         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
7612 }
7613
7614 void R_ResetViewRendering3D(void)
7615 {
7616         DrawQ_Finish();
7617
7618         R_SetupView(true);
7619         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7620         GL_Color(1, 1, 1, 1);
7621         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7622         GL_BlendFunc(GL_ONE, GL_ZERO);
7623         GL_AlphaTest(false);
7624         GL_ScissorTest(true);
7625         GL_DepthMask(true);
7626         GL_DepthRange(0, 1);
7627         GL_DepthTest(true);
7628         R_EntityMatrix(&identitymatrix);
7629         R_Mesh_ResetTextureState();
7630         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7631         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7632         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7633         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7634         qglStencilMask(~0);CHECKGLERROR
7635         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7636         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7637         GL_CullFace(r_refdef.view.cullface_back);
7638 }
7639
7640 /*
7641 ================
7642 R_RenderView_UpdateViewVectors
7643 ================
7644 */
7645 static void R_RenderView_UpdateViewVectors(void)
7646 {
7647         // break apart the view matrix into vectors for various purposes
7648         // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
7649         // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
7650         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
7651         VectorNegate(r_refdef.view.left, r_refdef.view.right);
7652         // make an inverted copy of the view matrix for tracking sprites
7653         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
7654 }
7655
7656 void R_RenderScene(void);
7657 void R_RenderWaterPlanes(void);
7658
7659 static void R_Water_StartFrame(void)
7660 {
7661         int i;
7662         int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
7663         r_waterstate_waterplane_t *p;
7664
7665         if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
7666                 return;
7667
7668         switch(vid.renderpath)
7669         {
7670         case RENDERPATH_GL20:
7671         case RENDERPATH_CGGL:
7672                 break;
7673         case RENDERPATH_GL13:
7674         case RENDERPATH_GL11:
7675                 return;
7676         }
7677
7678         // set waterwidth and waterheight to the water resolution that will be
7679         // used (often less than the screen resolution for faster rendering)
7680         waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
7681         waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
7682
7683         // calculate desired texture sizes
7684         // can't use water if the card does not support the texture size
7685         if (!r_water.integer || r_showsurfaces.integer)
7686                 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
7687         else if (vid.support.arb_texture_non_power_of_two)
7688         {
7689                 texturewidth = waterwidth;
7690                 textureheight = waterheight;
7691                 camerawidth = waterwidth;
7692                 cameraheight = waterheight;
7693         }
7694         else
7695         {
7696                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
7697                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
7698                 for (camerawidth    = 1;camerawidth   <= waterwidth; camerawidth    *= 2); camerawidth  /= 2;
7699                 for (cameraheight   = 1;cameraheight  <= waterheight;cameraheight   *= 2); cameraheight /= 2;
7700         }
7701
7702         // allocate textures as needed
7703         if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
7704         {
7705                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7706                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
7707                 {
7708                         if (p->texture_refraction)
7709                                 R_FreeTexture(p->texture_refraction);
7710                         p->texture_refraction = NULL;
7711                         if (p->texture_reflection)
7712                                 R_FreeTexture(p->texture_reflection);
7713                         p->texture_reflection = NULL;
7714                         if (p->texture_camera)
7715                                 R_FreeTexture(p->texture_camera);
7716                         p->texture_camera = NULL;
7717                 }
7718                 memset(&r_waterstate, 0, sizeof(r_waterstate));
7719                 r_waterstate.texturewidth = texturewidth;
7720                 r_waterstate.textureheight = textureheight;
7721                 r_waterstate.camerawidth = camerawidth;
7722                 r_waterstate.cameraheight = cameraheight;
7723         }
7724
7725         if (r_waterstate.texturewidth)
7726         {
7727                 r_waterstate.enabled = true;
7728
7729                 // when doing a reduced render (HDR) we want to use a smaller area
7730                 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
7731                 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
7732
7733                 // set up variables that will be used in shader setup
7734                 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7735                 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7736                 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7737                 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7738         }
7739
7740         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7741         r_waterstate.numwaterplanes = 0;
7742 }
7743
7744 void R_Water_AddWaterPlane(msurface_t *surface)
7745 {
7746         int triangleindex, planeindex;
7747         const int *e;
7748         vec3_t vert[3];
7749         vec3_t normal;
7750         vec3_t center;
7751         mplane_t plane;
7752         int cam_ent;
7753         r_waterstate_waterplane_t *p;
7754         texture_t *t = R_GetCurrentTexture(surface->texture);
7755         cam_ent = t->camera_entity;
7756         if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
7757                 cam_ent = 0;
7758
7759         // just use the first triangle with a valid normal for any decisions
7760         VectorClear(normal);
7761         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7762         {
7763                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
7764                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
7765                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
7766                 TriangleNormal(vert[0], vert[1], vert[2], normal);
7767                 if (VectorLength2(normal) >= 0.001)
7768                         break;
7769         }
7770
7771         VectorCopy(normal, plane.normal);
7772         VectorNormalize(plane.normal);
7773         plane.dist = DotProduct(vert[0], plane.normal);
7774         PlaneClassify(&plane);
7775         if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
7776         {
7777                 // skip backfaces (except if nocullface is set)
7778                 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
7779                         return;
7780                 VectorNegate(plane.normal, plane.normal);
7781                 plane.dist *= -1;
7782                 PlaneClassify(&plane);
7783         }
7784
7785
7786         // find a matching plane if there is one
7787         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7788                 if(p->camera_entity == t->camera_entity)
7789                         if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
7790                                 break;
7791         if (planeindex >= r_waterstate.maxwaterplanes)
7792                 return; // nothing we can do, out of planes
7793
7794         // if this triangle does not fit any known plane rendered this frame, add one
7795         if (planeindex >= r_waterstate.numwaterplanes)
7796         {
7797                 // store the new plane
7798                 r_waterstate.numwaterplanes++;
7799                 p->plane = plane;
7800                 // clear materialflags and pvs
7801                 p->materialflags = 0;
7802                 p->pvsvalid = false;
7803                 p->camera_entity = t->camera_entity;
7804                 VectorCopy(surface->mins, p->mins);
7805                 VectorCopy(surface->maxs, p->maxs);
7806         }
7807         else
7808         {
7809                 // merge mins/maxs
7810                 p->mins[0] = min(p->mins[0], surface->mins[0]);
7811                 p->mins[1] = min(p->mins[1], surface->mins[1]);
7812                 p->mins[2] = min(p->mins[2], surface->mins[2]);
7813                 p->maxs[0] = min(p->maxs[0], surface->maxs[0]);
7814                 p->maxs[1] = min(p->maxs[1], surface->maxs[1]);
7815                 p->maxs[2] = min(p->maxs[2], surface->maxs[2]);
7816         }
7817         // merge this surface's materialflags into the waterplane
7818         p->materialflags |= t->currentmaterialflags;
7819         if(!(p->materialflags & MATERIALFLAG_CAMERA))
7820         {
7821                 // merge this surface's PVS into the waterplane
7822                 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
7823                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
7824                  && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
7825                 {
7826                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
7827                         p->pvsvalid = true;
7828                 }
7829         }
7830 }
7831
7832 static void R_Water_ProcessPlanes(void)
7833 {
7834         int myscissor[4];
7835         r_refdef_view_t originalview;
7836         r_refdef_view_t myview;
7837         int planeindex;
7838         r_waterstate_waterplane_t *p;
7839         vec3_t visorigin;
7840
7841         originalview = r_refdef.view;
7842
7843         // make sure enough textures are allocated
7844         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7845         {
7846                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7847                 {
7848                         if (!p->texture_refraction)
7849                                 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
7850                         if (!p->texture_refraction)
7851                                 goto error;
7852                 }
7853                 else if (p->materialflags & MATERIALFLAG_CAMERA)
7854                 {
7855                         if (!p->texture_camera)
7856                                 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR, -1, NULL);
7857                         if (!p->texture_camera)
7858                                 goto error;
7859                 }
7860
7861                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7862                 {
7863                         if (!p->texture_reflection)
7864                                 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
7865                         if (!p->texture_reflection)
7866                                 goto error;
7867                 }
7868         }
7869
7870         // render views
7871         r_refdef.view = originalview;
7872         r_refdef.view.showdebug = false;
7873         r_refdef.view.width = r_waterstate.waterwidth;
7874         r_refdef.view.height = r_waterstate.waterheight;
7875         r_refdef.view.useclipplane = true;
7876         myview = r_refdef.view;
7877         r_waterstate.renderingscene = true;
7878         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7879         {
7880                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7881                 {
7882                         r_refdef.view = myview;
7883                         if(r_water_scissormode.integer)
7884                         {
7885                                 R_SetupView(true);
7886                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
7887                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
7888                         }
7889
7890                         // render reflected scene and copy into texture
7891                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
7892                         // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
7893                         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
7894                         r_refdef.view.clipplane = p->plane;
7895
7896                         // reverse the cullface settings for this render
7897                         r_refdef.view.cullface_front = GL_FRONT;
7898                         r_refdef.view.cullface_back = GL_BACK;
7899                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
7900                         {
7901                                 r_refdef.view.usecustompvs = true;
7902                                 if (p->pvsvalid)
7903                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7904                                 else
7905                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7906                         }
7907
7908                         R_ResetViewRendering3D();
7909                         R_ClearScreen(r_refdef.fogenabled);
7910                         if(r_water_scissormode.integer & 2)
7911                                 R_View_UpdateWithScissor(myscissor);
7912                         else
7913                                 R_View_Update();
7914                         if(r_water_scissormode.integer & 1)
7915                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
7916                         R_RenderScene();
7917
7918                         R_Mesh_CopyToTexture(p->texture_reflection, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7919                 }
7920
7921                 // render the normal view scene and copy into texture
7922                 // (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)
7923                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7924                 {
7925                         r_refdef.view = myview;
7926                         if(r_water_scissormode.integer)
7927                         {
7928                                 R_SetupView(true);
7929                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
7930                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
7931                         }
7932
7933                         r_waterstate.renderingrefraction = true;
7934
7935                         r_refdef.view.clipplane = p->plane;
7936                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7937                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7938
7939                         if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
7940                         {
7941                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7942                                 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
7943                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7944                                 R_RenderView_UpdateViewVectors();
7945                                 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7946                                 {
7947                                         r_refdef.view.usecustompvs = true;
7948                                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
7949                                 }
7950                         }
7951
7952                         PlaneClassify(&r_refdef.view.clipplane);
7953
7954                         R_ResetViewRendering3D();
7955                         R_ClearScreen(r_refdef.fogenabled);
7956                         if(r_water_scissormode.integer & 2)
7957                                 R_View_UpdateWithScissor(myscissor);
7958                         else
7959                                 R_View_Update();
7960                         if(r_water_scissormode.integer & 1)
7961                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
7962                         R_RenderScene();
7963
7964                         R_Mesh_CopyToTexture(p->texture_refraction, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7965                         r_waterstate.renderingrefraction = false;
7966                 }
7967                 else if (p->materialflags & MATERIALFLAG_CAMERA)
7968                 {
7969                         r_refdef.view = myview;
7970
7971                         r_refdef.view.clipplane = p->plane;
7972                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7973                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7974
7975                         r_refdef.view.width = r_waterstate.camerawidth;
7976                         r_refdef.view.height = r_waterstate.cameraheight;
7977                         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
7978                         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
7979
7980                         if(p->camera_entity)
7981                         {
7982                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7983                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7984                         }
7985
7986                         // note: all of the view is used for displaying... so
7987                         // there is no use in scissoring
7988
7989                         // reverse the cullface settings for this render
7990                         r_refdef.view.cullface_front = GL_FRONT;
7991                         r_refdef.view.cullface_back = GL_BACK;
7992                         // also reverse the view matrix
7993                         Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, 1, -1); // this serves to invert texcoords in the result, as the copied texture is mapped the wrong way round
7994                         R_RenderView_UpdateViewVectors();
7995                         if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7996                         {
7997                                 r_refdef.view.usecustompvs = true;
7998                                 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
7999                         }
8000                         
8001                         // camera needs no clipplane
8002                         r_refdef.view.useclipplane = false;
8003
8004                         PlaneClassify(&r_refdef.view.clipplane);
8005
8006                         R_ResetViewRendering3D();
8007                         R_ClearScreen(r_refdef.fogenabled);
8008                         R_View_Update();
8009                         R_RenderScene();
8010
8011                         R_Mesh_CopyToTexture(p->texture_camera, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8012                         r_waterstate.renderingrefraction = false;
8013                 }
8014
8015         }
8016         r_waterstate.renderingscene = false;
8017         r_refdef.view = originalview;
8018         R_ResetViewRendering3D();
8019         R_ClearScreen(r_refdef.fogenabled);
8020         R_View_Update();
8021         return;
8022 error:
8023         r_refdef.view = originalview;
8024         r_waterstate.renderingscene = false;
8025         Cvar_SetValueQuick(&r_water, 0);
8026         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
8027         return;
8028 }
8029
8030 void R_Bloom_StartFrame(void)
8031 {
8032         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8033
8034         switch(vid.renderpath)
8035         {
8036         case RENDERPATH_GL20:
8037         case RENDERPATH_CGGL:
8038                 break;
8039         case RENDERPATH_GL13:
8040         case RENDERPATH_GL11:
8041                 return;
8042         }
8043
8044         // set bloomwidth and bloomheight to the bloom resolution that will be
8045         // used (often less than the screen resolution for faster rendering)
8046         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8047         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8048         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8049         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8050         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8051
8052         // calculate desired texture sizes
8053         if (vid.support.arb_texture_non_power_of_two)
8054         {
8055                 screentexturewidth = r_refdef.view.width;
8056                 screentextureheight = r_refdef.view.height;
8057                 bloomtexturewidth = r_bloomstate.bloomwidth;
8058                 bloomtextureheight = r_bloomstate.bloomheight;
8059         }
8060         else
8061         {
8062                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
8063                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
8064                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
8065                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
8066         }
8067
8068         if ((r_hdr.integer || r_bloom.integer || (!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))) && ((r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512) || r_refdef.view.width > (int)vid.maxtexturesize_2d || r_refdef.view.height > (int)vid.maxtexturesize_2d))
8069         {
8070                 Cvar_SetValueQuick(&r_hdr, 0);
8071                 Cvar_SetValueQuick(&r_bloom, 0);
8072                 Cvar_SetValueQuick(&r_motionblur, 0);
8073                 Cvar_SetValueQuick(&r_damageblur, 0);
8074         }
8075
8076         if (!(r_glsl_postprocess.integer || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial)) && !r_bloom.integer && !r_hdr.integer && (R_Stereo_Active() || (r_motionblur.value <= 0 && r_damageblur.value <= 0)))
8077                 screentexturewidth = screentextureheight = 0;
8078         if (!r_hdr.integer && !r_bloom.integer)
8079                 bloomtexturewidth = bloomtextureheight = 0;
8080
8081         // allocate textures as needed
8082         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8083         {
8084                 if (r_bloomstate.texture_screen)
8085                         R_FreeTexture(r_bloomstate.texture_screen);
8086                 r_bloomstate.texture_screen = NULL;
8087                 r_bloomstate.screentexturewidth = screentexturewidth;
8088                 r_bloomstate.screentextureheight = screentextureheight;
8089                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8090                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
8091         }
8092         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8093         {
8094                 if (r_bloomstate.texture_bloom)
8095                         R_FreeTexture(r_bloomstate.texture_bloom);
8096                 r_bloomstate.texture_bloom = NULL;
8097                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8098                 r_bloomstate.bloomtextureheight = bloomtextureheight;
8099                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8100                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8101         }
8102
8103         // when doing a reduced render (HDR) we want to use a smaller area
8104         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8105         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8106         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8107         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8108         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8109
8110         // set up a texcoord array for the full resolution screen image
8111         // (we have to keep this around to copy back during final render)
8112         r_bloomstate.screentexcoord2f[0] = 0;
8113         r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8114         r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8115         r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8116         r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8117         r_bloomstate.screentexcoord2f[5] = 0;
8118         r_bloomstate.screentexcoord2f[6] = 0;
8119         r_bloomstate.screentexcoord2f[7] = 0;
8120
8121         // set up a texcoord array for the reduced resolution bloom image
8122         // (which will be additive blended over the screen image)
8123         r_bloomstate.bloomtexcoord2f[0] = 0;
8124         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8125         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8126         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8127         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8128         r_bloomstate.bloomtexcoord2f[5] = 0;
8129         r_bloomstate.bloomtexcoord2f[6] = 0;
8130         r_bloomstate.bloomtexcoord2f[7] = 0;
8131
8132         if (r_hdr.integer || r_bloom.integer)
8133         {
8134                 r_bloomstate.enabled = true;
8135                 r_bloomstate.hdr = r_hdr.integer != 0;
8136         }
8137
8138         R_Viewport_InitOrtho(&r_bloomstate.viewport, &identitymatrix, r_refdef.view.x, vid.height - r_bloomstate.bloomheight - r_refdef.view.y, r_bloomstate.bloomwidth, r_bloomstate.bloomheight, 0, 0, 1, 1, -10, 100, NULL);
8139 }
8140
8141 void R_Bloom_CopyBloomTexture(float colorscale)
8142 {
8143         r_refdef.stats.bloom++;
8144
8145         // scale down screen texture to the bloom texture size
8146         CHECKGLERROR
8147         R_SetViewport(&r_bloomstate.viewport);
8148         GL_BlendFunc(GL_ONE, GL_ZERO);
8149         GL_Color(colorscale, colorscale, colorscale, 1);
8150         // TODO: optimize with multitexture or GLSL
8151         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
8152         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8153         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8154         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8155
8156         // we now have a bloom image in the framebuffer
8157         // copy it into the bloom image texture for later processing
8158         R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8159         r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8160 }
8161
8162 void R_Bloom_CopyHDRTexture(void)
8163 {
8164         R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8165         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8166 }
8167
8168 void R_Bloom_MakeTexture(void)
8169 {
8170         int x, range, dir;
8171         float xoffset, yoffset, r, brighten;
8172
8173         r_refdef.stats.bloom++;
8174
8175         R_ResetViewRendering2D();
8176         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8177         R_Mesh_ColorPointer(NULL, 0, 0);
8178
8179         // we have a bloom image in the framebuffer
8180         CHECKGLERROR
8181         R_SetViewport(&r_bloomstate.viewport);
8182
8183         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8184         {
8185                 x *= 2;
8186                 r = bound(0, r_bloom_colorexponent.value / x, 1);
8187                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8188                 GL_Color(r, r, r, 1);
8189                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8190                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8191                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8192                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8193
8194                 // copy the vertically blurred bloom view to a texture
8195                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8196                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8197         }
8198
8199         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8200         brighten = r_bloom_brighten.value;
8201         if (r_hdr.integer)
8202                 brighten *= r_hdr_range.value;
8203         brighten = sqrt(brighten);
8204         if(range >= 1)
8205                 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8206         R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8207         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.offsettexcoord2f, 0, 0);
8208
8209         for (dir = 0;dir < 2;dir++)
8210         {
8211                 // blend on at multiple vertical offsets to achieve a vertical blur
8212                 // TODO: do offset blends using GLSL
8213                 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8214                 GL_BlendFunc(GL_ONE, GL_ZERO);
8215                 for (x = -range;x <= range;x++)
8216                 {
8217                         if (!dir){xoffset = 0;yoffset = x;}
8218                         else {xoffset = x;yoffset = 0;}
8219                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
8220                         yoffset /= (float)r_bloomstate.bloomtextureheight;
8221                         // compute a texcoord array with the specified x and y offset
8222                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8223                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8224                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8225                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8226                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8227                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8228                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8229                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8230                         // this r value looks like a 'dot' particle, fading sharply to
8231                         // black at the edges
8232                         // (probably not realistic but looks good enough)
8233                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8234                         //r = brighten/(range*2+1);
8235                         r = brighten / (range * 2 + 1);
8236                         if(range >= 1)
8237                                 r *= (1 - x*x/(float)(range*range));
8238                         GL_Color(r, r, r, 1);
8239                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8240                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8241                         GL_BlendFunc(GL_ONE, GL_ONE);
8242                 }
8243
8244                 // copy the vertically blurred bloom view to a texture
8245                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8246                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8247         }
8248
8249         // apply subtract last
8250         // (just like it would be in a GLSL shader)
8251         if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
8252         {
8253                 GL_BlendFunc(GL_ONE, GL_ZERO);
8254                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8255                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8256                 GL_Color(1, 1, 1, 1);
8257                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8258                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8259
8260                 GL_BlendFunc(GL_ONE, GL_ONE);
8261                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
8262                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8263                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8264                 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
8265                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8266                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8267                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
8268
8269                 // copy the darkened bloom view to a texture
8270                 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8271                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8272         }
8273 }
8274
8275 void R_HDR_RenderBloomTexture(void)
8276 {
8277         int oldwidth, oldheight;
8278         float oldcolorscale;
8279
8280         oldcolorscale = r_refdef.view.colorscale;
8281         oldwidth = r_refdef.view.width;
8282         oldheight = r_refdef.view.height;
8283         r_refdef.view.width = r_bloomstate.bloomwidth;
8284         r_refdef.view.height = r_bloomstate.bloomheight;
8285
8286         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
8287         // TODO: add exposure compensation features
8288         // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8289
8290         r_refdef.view.showdebug = false;
8291         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8292
8293         R_ResetViewRendering3D();
8294
8295         R_ClearScreen(r_refdef.fogenabled);
8296         if (r_timereport_active)
8297                 R_TimeReport("HDRclear");
8298
8299         R_View_Update();
8300         if (r_timereport_active)
8301                 R_TimeReport("visibility");
8302
8303         // only do secondary renders with HDR if r_hdr is 2 or higher
8304         r_waterstate.numwaterplanes = 0;
8305         if (r_waterstate.enabled && r_hdr.integer >= 2)
8306                 R_RenderWaterPlanes();
8307
8308         r_refdef.view.showdebug = true;
8309         R_RenderScene();
8310         r_waterstate.numwaterplanes = 0;
8311
8312         R_ResetViewRendering2D();
8313
8314         R_Bloom_CopyHDRTexture();
8315         R_Bloom_MakeTexture();
8316
8317         // restore the view settings
8318         r_refdef.view.width = oldwidth;
8319         r_refdef.view.height = oldheight;
8320         r_refdef.view.colorscale = oldcolorscale;
8321
8322         R_ResetViewRendering3D();
8323
8324         R_ClearScreen(r_refdef.fogenabled);
8325         if (r_timereport_active)
8326                 R_TimeReport("viewclear");
8327 }
8328
8329 static void R_BlendView(void)
8330 {
8331         unsigned int permutation;
8332         float uservecs[4][4];
8333
8334         switch (vid.renderpath)
8335         {
8336         case RENDERPATH_GL20:
8337         case RENDERPATH_CGGL:
8338                 permutation =
8339                           (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8340                         | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8341                         | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8342                         | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8343                         | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8344
8345                 if (r_bloomstate.texture_screen)
8346                 {
8347                         // make sure the buffer is available
8348                         if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8349
8350                         R_ResetViewRendering2D();
8351                         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8352                         R_Mesh_ColorPointer(NULL, 0, 0);
8353
8354                         if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8355                         {
8356                                 // declare variables
8357                                 float speed;
8358                                 static float avgspeed;
8359
8360                                 speed = VectorLength(cl.movement_velocity);
8361
8362                                 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8363                                 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8364
8365                                 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8366                                 speed = bound(0, speed, 1);
8367                                 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8368
8369                                 // calculate values into a standard alpha
8370                                 cl.motionbluralpha = 1 - exp(-
8371                                                 (
8372                                                  (r_motionblur.value * speed / 80)
8373                                                  +
8374                                                  (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8375                                                 )
8376                                                 /
8377                                                 max(0.0001, cl.time - cl.oldtime) // fps independent
8378                                            );
8379
8380                                 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8381                                 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8382                                 // apply the blur
8383                                 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8384                                 {
8385                                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8386                                         GL_Color(1, 1, 1, cl.motionbluralpha);
8387                                         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8388                                         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
8389                                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8390                                         r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8391                                 }
8392                         }
8393
8394                         // copy view into the screen texture
8395                         R_Mesh_CopyToTexture(r_bloomstate.texture_screen, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8396                         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8397                 }
8398                 else if (!r_bloomstate.texture_bloom)
8399                 {
8400                         // we may still have to do view tint...
8401                         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8402                         {
8403                                 // apply a color tint to the whole view
8404                                 R_ResetViewRendering2D();
8405                                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8406                                 R_Mesh_ColorPointer(NULL, 0, 0);
8407                                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8408                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8409                                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8410                                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8411                         }
8412                         break; // no screen processing, no bloom, skip it
8413                 }
8414
8415                 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8416                 {
8417                         // render simple bloom effect
8418                         // copy the screen and shrink it and darken it for the bloom process
8419                         R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8420                         // make the bloom texture
8421                         R_Bloom_MakeTexture();
8422                 }
8423
8424 #if _MSC_VER >= 1400
8425 #define sscanf sscanf_s
8426 #endif
8427                 memset(uservecs, 0, sizeof(uservecs));
8428                 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8429                 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8430                 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8431                 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8432
8433                 R_ResetViewRendering2D();
8434                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8435                 R_Mesh_ColorPointer(NULL, 0, 0);
8436                 GL_Color(1, 1, 1, 1);
8437                 GL_BlendFunc(GL_ONE, GL_ZERO);
8438                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
8439                 R_Mesh_TexCoordPointer(1, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8440
8441                 switch(vid.renderpath)
8442                 {
8443                 case RENDERPATH_GL20:
8444                         R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8445                         if (r_glsl_permutation->loc_Texture_First      >= 0) R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
8446                         if (r_glsl_permutation->loc_Texture_Second     >= 0) R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
8447                         if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
8448                         if (r_glsl_permutation->loc_ViewTintColor      >= 0) qglUniform4fARB(r_glsl_permutation->loc_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8449                         if (r_glsl_permutation->loc_PixelSize          >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8450                         if (r_glsl_permutation->loc_UserVec1           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8451                         if (r_glsl_permutation->loc_UserVec2           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8452                         if (r_glsl_permutation->loc_UserVec3           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8453                         if (r_glsl_permutation->loc_UserVec4           >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8454                         if (r_glsl_permutation->loc_Saturation         >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation        , r_glsl_saturation.value);
8455                         if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8456                         break;
8457                 case RENDERPATH_CGGL:
8458 #ifdef SUPPORTCG
8459                         R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8460                         if (r_cg_permutation->fp_Texture_First     ) CG_BindTexture(r_cg_permutation->fp_Texture_First     , r_bloomstate.texture_screen);CHECKCGERROR
8461                         if (r_cg_permutation->fp_Texture_Second    ) CG_BindTexture(r_cg_permutation->fp_Texture_Second    , r_bloomstate.texture_bloom );CHECKCGERROR
8462                         if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps       );CHECKCGERROR
8463                         if (r_cg_permutation->fp_ViewTintColor     ) cgGLSetParameter4f(     r_cg_permutation->fp_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);CHECKCGERROR
8464                         if (r_cg_permutation->fp_PixelSize         ) cgGLSetParameter2f(     r_cg_permutation->fp_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8465                         if (r_cg_permutation->fp_UserVec1          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);CHECKCGERROR
8466                         if (r_cg_permutation->fp_UserVec2          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);CHECKCGERROR
8467                         if (r_cg_permutation->fp_UserVec3          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);CHECKCGERROR
8468                         if (r_cg_permutation->fp_UserVec4          ) cgGLSetParameter4f(     r_cg_permutation->fp_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);CHECKCGERROR
8469                         if (r_cg_permutation->fp_Saturation        ) cgGLSetParameter1f(     r_cg_permutation->fp_Saturation        , r_glsl_saturation.value);CHECKCGERROR
8470                         if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8471 #endif
8472                         break;
8473                 default:
8474                         break;
8475                 }
8476                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8477                 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8478                 break;
8479         case RENDERPATH_GL13:
8480         case RENDERPATH_GL11:
8481                 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8482                 {
8483                         // apply a color tint to the whole view
8484                         R_ResetViewRendering2D();
8485                         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8486                         R_Mesh_ColorPointer(NULL, 0, 0);
8487                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8488                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8489                         GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8490                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8491                 }
8492                 break;
8493         }
8494 }
8495
8496 matrix4x4_t r_waterscrollmatrix;
8497
8498 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
8499 {
8500         if (r_refdef.fog_density)
8501         {
8502                 r_refdef.fogcolor[0] = r_refdef.fog_red;
8503                 r_refdef.fogcolor[1] = r_refdef.fog_green;
8504                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
8505
8506                 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
8507                 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
8508                 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
8509                 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
8510
8511                 {
8512                         vec3_t fogvec;
8513                         VectorCopy(r_refdef.fogcolor, fogvec);
8514                         //   color.rgb *= ContrastBoost * SceneBrightness;
8515                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
8516                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
8517                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
8518                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
8519                 }
8520         }
8521 }
8522
8523 void R_UpdateVariables(void)
8524 {
8525         R_Textures_Frame();
8526
8527         r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
8528
8529         r_refdef.farclip = r_farclip_base.value;
8530         if (r_refdef.scene.worldmodel)
8531                 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
8532         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
8533
8534         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
8535                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
8536         r_refdef.polygonfactor = 0;
8537         r_refdef.polygonoffset = 0;
8538         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8539         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8540
8541         r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
8542         r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
8543         r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
8544         r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
8545         r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
8546         if (FAKELIGHT_ENABLED)
8547         {
8548                 r_refdef.lightmapintensity *= r_fakelight_intensity.value;
8549         }
8550         if (r_showsurfaces.integer)
8551         {
8552                 r_refdef.scene.rtworld = false;
8553                 r_refdef.scene.rtworldshadows = false;
8554                 r_refdef.scene.rtdlight = false;
8555                 r_refdef.scene.rtdlightshadows = false;
8556                 r_refdef.lightmapintensity = 0;
8557         }
8558
8559         if (gamemode == GAME_NEHAHRA)
8560         {
8561                 if (gl_fogenable.integer)
8562                 {
8563                         r_refdef.oldgl_fogenable = true;
8564                         r_refdef.fog_density = gl_fogdensity.value;
8565                         r_refdef.fog_red = gl_fogred.value;
8566                         r_refdef.fog_green = gl_foggreen.value;
8567                         r_refdef.fog_blue = gl_fogblue.value;
8568                         r_refdef.fog_alpha = 1;
8569                         r_refdef.fog_start = 0;
8570                         r_refdef.fog_end = gl_skyclip.value;
8571                         r_refdef.fog_height = 1<<30;
8572                         r_refdef.fog_fadedepth = 128;
8573                 }
8574                 else if (r_refdef.oldgl_fogenable)
8575                 {
8576                         r_refdef.oldgl_fogenable = false;
8577                         r_refdef.fog_density = 0;
8578                         r_refdef.fog_red = 0;
8579                         r_refdef.fog_green = 0;
8580                         r_refdef.fog_blue = 0;
8581                         r_refdef.fog_alpha = 0;
8582                         r_refdef.fog_start = 0;
8583                         r_refdef.fog_end = 0;
8584                         r_refdef.fog_height = 1<<30;
8585                         r_refdef.fog_fadedepth = 128;
8586                 }
8587         }
8588
8589         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
8590         r_refdef.fog_start = max(0, r_refdef.fog_start);
8591         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
8592
8593         // R_UpdateFogColor(); // why? R_RenderScene does it anyway
8594
8595         if (r_refdef.fog_density && r_drawfog.integer)
8596         {
8597                 r_refdef.fogenabled = true;
8598                 // this is the point where the fog reaches 0.9986 alpha, which we
8599                 // consider a good enough cutoff point for the texture
8600                 // (0.9986 * 256 == 255.6)
8601                 if (r_fog_exp2.integer)
8602                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
8603                 else
8604                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
8605                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
8606                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
8607                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
8608                 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
8609                         R_BuildFogHeightTexture();
8610                 // fog color was already set
8611                 // update the fog texture
8612                 if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
8613                         R_BuildFogTexture();
8614                 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
8615                 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
8616         }
8617         else
8618                 r_refdef.fogenabled = false;
8619
8620         switch(vid.renderpath)
8621         {
8622         case RENDERPATH_GL20:
8623         case RENDERPATH_CGGL:
8624                 if(v_glslgamma.integer && !vid_gammatables_trivial)
8625                 {
8626                         if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
8627                         {
8628                                 // build GLSL gamma texture
8629 #define RAMPWIDTH 256
8630                                 unsigned short ramp[RAMPWIDTH * 3];
8631                                 unsigned char rampbgr[RAMPWIDTH][4];
8632                                 int i;
8633
8634                                 r_texture_gammaramps_serial = vid_gammatables_serial;
8635
8636                                 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
8637                                 for(i = 0; i < RAMPWIDTH; ++i)
8638                                 {
8639                                         rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8640                                         rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8641                                         rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
8642                                         rampbgr[i][3] = 0;
8643                                 }
8644                                 if (r_texture_gammaramps)
8645                                 {
8646                                         R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
8647                                 }
8648                                 else
8649                                 {
8650                                         r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
8651                                 }
8652                         }
8653                 }
8654                 else
8655                 {
8656                         // remove GLSL gamma texture
8657                 }
8658                 break;
8659         case RENDERPATH_GL13:
8660         case RENDERPATH_GL11:
8661                 break;
8662         }
8663 }
8664
8665 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
8666 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
8667 /*
8668 ================
8669 R_SelectScene
8670 ================
8671 */
8672 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
8673         if( scenetype != r_currentscenetype ) {
8674                 // store the old scenetype
8675                 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
8676                 r_currentscenetype = scenetype;
8677                 // move in the new scene
8678                 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
8679         }
8680 }
8681
8682 /*
8683 ================
8684 R_GetScenePointer
8685 ================
8686 */
8687 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
8688 {
8689         // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
8690         if( scenetype == r_currentscenetype ) {
8691                 return &r_refdef.scene;
8692         } else {
8693                 return &r_scenes_store[ scenetype ];
8694         }
8695 }
8696
8697 /*
8698 ================
8699 R_RenderView
8700 ================
8701 */
8702 void R_RenderView(void)
8703 {
8704         if (r_timereport_active)
8705                 R_TimeReport("start");
8706         r_textureframe++; // used only by R_GetCurrentTexture
8707         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
8708
8709         if (!r_drawentities.integer)
8710                 r_refdef.scene.numentities = 0;
8711
8712         R_AnimCache_ClearCache();
8713         R_FrameData_NewFrame();
8714
8715         if (r_refdef.view.isoverlay)
8716         {
8717                 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
8718                 GL_Clear( GL_DEPTH_BUFFER_BIT );
8719                 R_TimeReport("depthclear");
8720
8721                 r_refdef.view.showdebug = false;
8722
8723                 r_waterstate.enabled = false;
8724                 r_waterstate.numwaterplanes = 0;
8725
8726                 R_RenderScene();
8727
8728                 CHECKGLERROR
8729                 return;
8730         }
8731
8732         if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
8733                 return; //Host_Error ("R_RenderView: NULL worldmodel");
8734
8735         r_refdef.view.colorscale = r_hdr_scenebrightness.value;
8736
8737         R_RenderView_UpdateViewVectors();
8738
8739         R_Shadow_UpdateWorldLightSelection();
8740
8741         R_Bloom_StartFrame();
8742         R_Water_StartFrame();
8743
8744         CHECKGLERROR
8745         if (r_timereport_active)
8746                 R_TimeReport("viewsetup");
8747
8748         R_ResetViewRendering3D();
8749
8750         if (r_refdef.view.clear || r_refdef.fogenabled)
8751         {
8752                 R_ClearScreen(r_refdef.fogenabled);
8753                 if (r_timereport_active)
8754                         R_TimeReport("viewclear");
8755         }
8756         r_refdef.view.clear = true;
8757
8758         // this produces a bloom texture to be used in R_BlendView() later
8759         if (r_hdr.integer && r_bloomstate.bloomwidth)
8760         {
8761                 R_HDR_RenderBloomTexture();
8762                 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
8763                 r_textureframe++; // used only by R_GetCurrentTexture
8764         }
8765
8766         r_refdef.view.showdebug = true;
8767
8768         R_View_Update();
8769         if (r_timereport_active)
8770                 R_TimeReport("visibility");
8771
8772         r_waterstate.numwaterplanes = 0;
8773         if (r_waterstate.enabled)
8774                 R_RenderWaterPlanes();
8775
8776         R_RenderScene();
8777         r_waterstate.numwaterplanes = 0;
8778
8779         R_BlendView();
8780         if (r_timereport_active)
8781                 R_TimeReport("blendview");
8782
8783         GL_Scissor(0, 0, vid.width, vid.height);
8784         GL_ScissorTest(false);
8785
8786         CHECKGLERROR
8787 }
8788
8789 void R_RenderWaterPlanes(void)
8790 {
8791         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
8792         {
8793                 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
8794                 if (r_timereport_active)
8795                         R_TimeReport("waterworld");
8796         }
8797
8798         // don't let sound skip if going slow
8799         if (r_refdef.scene.extraupdate)
8800                 S_ExtraUpdate ();
8801
8802         R_DrawModelsAddWaterPlanes();
8803         if (r_timereport_active)
8804                 R_TimeReport("watermodels");
8805
8806         if (r_waterstate.numwaterplanes)
8807         {
8808                 R_Water_ProcessPlanes();
8809                 if (r_timereport_active)
8810                         R_TimeReport("waterscenes");
8811         }
8812 }
8813
8814 extern void R_DrawLightningBeams (void);
8815 extern void VM_CL_AddPolygonsToMeshQueue (void);
8816 extern void R_DrawPortals (void);
8817 extern cvar_t cl_locs_show;
8818 static void R_DrawLocs(void);
8819 static void R_DrawEntityBBoxes(void);
8820 static void R_DrawModelDecals(void);
8821 extern void R_DrawModelShadows(void);
8822 extern void R_DrawModelShadowMaps(void);
8823 extern cvar_t cl_decals_newsystem;
8824 extern qboolean r_shadow_usingdeferredprepass;
8825 void R_RenderScene(void)
8826 {
8827         qboolean shadowmapping = false;
8828
8829         if (r_timereport_active)
8830                 R_TimeReport("beginscene");
8831
8832         r_refdef.stats.renders++;
8833
8834         R_UpdateFogColor();
8835
8836         // don't let sound skip if going slow
8837         if (r_refdef.scene.extraupdate)
8838                 S_ExtraUpdate ();
8839
8840         R_MeshQueue_BeginScene();
8841
8842         R_SkyStartFrame();
8843
8844         Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
8845
8846         if (r_timereport_active)
8847                 R_TimeReport("skystartframe");
8848
8849         if (cl.csqc_vidvars.drawworld)
8850         {
8851                 // don't let sound skip if going slow
8852                 if (r_refdef.scene.extraupdate)
8853                         S_ExtraUpdate ();
8854
8855                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
8856                 {
8857                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
8858                         if (r_timereport_active)
8859                                 R_TimeReport("worldsky");
8860                 }
8861
8862                 if (R_DrawBrushModelsSky() && r_timereport_active)
8863                         R_TimeReport("bmodelsky");
8864
8865                 if (skyrendermasked && skyrenderlater)
8866                 {
8867                         // we have to force off the water clipping plane while rendering sky
8868                         R_SetupView(false);
8869                         R_Sky();
8870                         R_SetupView(true);
8871                         if (r_timereport_active)
8872                                 R_TimeReport("sky");
8873                 }
8874         }
8875
8876         R_AnimCache_CacheVisibleEntities();
8877         if (r_timereport_active)
8878                 R_TimeReport("animation");
8879
8880         R_Shadow_PrepareLights();
8881         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
8882                 R_Shadow_PrepareModelShadows();
8883         if (r_timereport_active)
8884                 R_TimeReport("preparelights");
8885
8886         if (R_Shadow_ShadowMappingEnabled())
8887                 shadowmapping = true;
8888
8889         if (r_shadow_usingdeferredprepass)
8890                 R_Shadow_DrawPrepass();
8891
8892         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
8893         {
8894                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
8895                 if (r_timereport_active)
8896                         R_TimeReport("worlddepth");
8897         }
8898         if (r_depthfirst.integer >= 2)
8899         {
8900                 R_DrawModelsDepth();
8901                 if (r_timereport_active)
8902                         R_TimeReport("modeldepth");
8903         }
8904
8905         if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
8906         {
8907                 R_DrawModelShadowMaps();
8908                 R_ResetViewRendering3D();
8909                 // don't let sound skip if going slow
8910                 if (r_refdef.scene.extraupdate)
8911                         S_ExtraUpdate ();
8912         }
8913
8914         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
8915         {
8916                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
8917                 if (r_timereport_active)
8918                         R_TimeReport("world");
8919         }
8920
8921         // don't let sound skip if going slow
8922         if (r_refdef.scene.extraupdate)
8923                 S_ExtraUpdate ();
8924
8925         R_DrawModels();
8926         if (r_timereport_active)
8927                 R_TimeReport("models");
8928
8929         // don't let sound skip if going slow
8930         if (r_refdef.scene.extraupdate)
8931                 S_ExtraUpdate ();
8932
8933         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8934         {
8935                 R_DrawModelShadows();
8936                 R_ResetViewRendering3D();
8937                 // don't let sound skip if going slow
8938                 if (r_refdef.scene.extraupdate)
8939                         S_ExtraUpdate ();
8940         }
8941
8942         if (!r_shadow_usingdeferredprepass)
8943         {
8944                 R_Shadow_DrawLights();
8945                 if (r_timereport_active)
8946                         R_TimeReport("rtlights");
8947         }
8948
8949         // don't let sound skip if going slow
8950         if (r_refdef.scene.extraupdate)
8951                 S_ExtraUpdate ();
8952
8953         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8954         {
8955                 R_DrawModelShadows();
8956                 R_ResetViewRendering3D();
8957                 // don't let sound skip if going slow
8958                 if (r_refdef.scene.extraupdate)
8959                         S_ExtraUpdate ();
8960         }
8961
8962         if (cl.csqc_vidvars.drawworld)
8963         {
8964                 if (cl_decals_newsystem.integer)
8965                 {
8966                         R_DrawModelDecals();
8967                         if (r_timereport_active)
8968                                 R_TimeReport("modeldecals");
8969                 }
8970                 else
8971                 {
8972                         R_DrawDecals();
8973                         if (r_timereport_active)
8974                                 R_TimeReport("decals");
8975                 }
8976
8977                 R_DrawParticles();
8978                 if (r_timereport_active)
8979                         R_TimeReport("particles");
8980
8981                 R_DrawExplosions();
8982                 if (r_timereport_active)
8983                         R_TimeReport("explosions");
8984
8985                 R_DrawLightningBeams();
8986                 if (r_timereport_active)
8987                         R_TimeReport("lightning");
8988         }
8989
8990         VM_CL_AddPolygonsToMeshQueue();
8991
8992         if (r_refdef.view.showdebug)
8993         {
8994                 if (cl_locs_show.integer)
8995                 {
8996                         R_DrawLocs();
8997                         if (r_timereport_active)
8998                                 R_TimeReport("showlocs");
8999                 }
9000
9001                 if (r_drawportals.integer)
9002                 {
9003                         R_DrawPortals();
9004                         if (r_timereport_active)
9005                                 R_TimeReport("portals");
9006                 }
9007
9008                 if (r_showbboxes.value > 0)
9009                 {
9010                         R_DrawEntityBBoxes();
9011                         if (r_timereport_active)
9012                                 R_TimeReport("bboxes");
9013                 }
9014         }
9015
9016         R_MeshQueue_RenderTransparent();
9017         if (r_timereport_active)
9018                 R_TimeReport("drawtrans");
9019
9020         if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value != 0 || r_showcollisionbrushes.value > 0))
9021         {
9022                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9023                 if (r_timereport_active)
9024                         R_TimeReport("worlddebug");
9025                 R_DrawModelsDebug();
9026                 if (r_timereport_active)
9027                         R_TimeReport("modeldebug");
9028         }
9029
9030         if (cl.csqc_vidvars.drawworld)
9031         {
9032                 R_Shadow_DrawCoronas();
9033                 if (r_timereport_active)
9034                         R_TimeReport("coronas");
9035         }
9036
9037 #if 0
9038         {
9039                 GL_DepthTest(false);
9040                 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
9041                 GL_Color(1, 1, 1, 1);
9042                 qglBegin(GL_POLYGON);
9043                 qglVertex3f(r_refdef.view.frustumcorner[0][0], r_refdef.view.frustumcorner[0][1], r_refdef.view.frustumcorner[0][2]);
9044                 qglVertex3f(r_refdef.view.frustumcorner[1][0], r_refdef.view.frustumcorner[1][1], r_refdef.view.frustumcorner[1][2]);
9045                 qglVertex3f(r_refdef.view.frustumcorner[3][0], r_refdef.view.frustumcorner[3][1], r_refdef.view.frustumcorner[3][2]);
9046                 qglVertex3f(r_refdef.view.frustumcorner[2][0], r_refdef.view.frustumcorner[2][1], r_refdef.view.frustumcorner[2][2]);
9047                 qglEnd();
9048                 qglBegin(GL_POLYGON);
9049                 qglVertex3f(r_refdef.view.frustumcorner[0][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[0][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[0][2] + 1000 * r_refdef.view.forward[2]);
9050                 qglVertex3f(r_refdef.view.frustumcorner[1][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[1][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[1][2] + 1000 * r_refdef.view.forward[2]);
9051                 qglVertex3f(r_refdef.view.frustumcorner[3][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[3][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[3][2] + 1000 * r_refdef.view.forward[2]);
9052                 qglVertex3f(r_refdef.view.frustumcorner[2][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[2][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[2][2] + 1000 * r_refdef.view.forward[2]);
9053                 qglEnd();
9054                 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
9055         }
9056 #endif
9057
9058         // don't let sound skip if going slow
9059         if (r_refdef.scene.extraupdate)
9060                 S_ExtraUpdate ();
9061
9062         R_ResetViewRendering2D();
9063 }
9064
9065 static const unsigned short bboxelements[36] =
9066 {
9067         5, 1, 3, 5, 3, 7,
9068         6, 2, 0, 6, 0, 4,
9069         7, 3, 2, 7, 2, 6,
9070         4, 0, 1, 4, 1, 5,
9071         4, 5, 7, 4, 7, 6,
9072         1, 0, 2, 1, 2, 3,
9073 };
9074
9075 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9076 {
9077         int i;
9078         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9079
9080         RSurf_ActiveWorldEntity();
9081
9082         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9083         GL_DepthMask(false);
9084         GL_DepthRange(0, 1);
9085         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9086         R_Mesh_ResetTextureState();
9087
9088         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9089         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9090         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9091         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9092         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9093         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9094         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9095         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9096         R_FillColors(color4f, 8, cr, cg, cb, ca);
9097         if (r_refdef.fogenabled)
9098         {
9099                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9100                 {
9101                         f1 = RSurf_FogVertex(v);
9102                         f2 = 1 - f1;
9103                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9104                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9105                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9106                 }
9107         }
9108         R_Mesh_VertexPointer(vertex3f, 0, 0);
9109         R_Mesh_ColorPointer(color4f, 0, 0);
9110         R_Mesh_ResetTextureState();
9111         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9112         R_Mesh_Draw(0, 8, 0, 12, NULL, bboxelements, 0, 0);
9113 }
9114
9115 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9116 {
9117         int i;
9118         float color[4];
9119         prvm_edict_t *edict;
9120         prvm_prog_t *prog_save = prog;
9121
9122         // this function draws bounding boxes of server entities
9123         if (!sv.active)
9124                 return;
9125
9126         GL_CullFace(GL_NONE);
9127         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9128
9129         prog = 0;
9130         SV_VM_Begin();
9131         for (i = 0;i < numsurfaces;i++)
9132         {
9133                 edict = PRVM_EDICT_NUM(surfacelist[i]);
9134                 switch ((int)edict->fields.server->solid)
9135                 {
9136                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
9137                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
9138                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
9139                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9140                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
9141                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
9142                 }
9143                 color[3] *= r_showbboxes.value;
9144                 color[3] = bound(0, color[3], 1);
9145                 GL_DepthTest(!r_showdisabledepthtest.integer);
9146                 GL_CullFace(r_refdef.view.cullface_front);
9147                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9148         }
9149         SV_VM_End();
9150         prog = prog_save;
9151 }
9152
9153 static void R_DrawEntityBBoxes(void)
9154 {
9155         int i;
9156         prvm_edict_t *edict;
9157         vec3_t center;
9158         prvm_prog_t *prog_save = prog;
9159
9160         // this function draws bounding boxes of server entities
9161         if (!sv.active)
9162                 return;
9163
9164         prog = 0;
9165         SV_VM_Begin();
9166         for (i = 0;i < prog->num_edicts;i++)
9167         {
9168                 edict = PRVM_EDICT_NUM(i);
9169                 if (edict->priv.server->free)
9170                         continue;
9171                 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9172                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9173                         continue;
9174                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9175                         continue;
9176                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9177                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9178         }
9179         SV_VM_End();
9180         prog = prog_save;
9181 }
9182
9183 static const int nomodelelement3i[24] =
9184 {
9185         5, 2, 0,
9186         5, 1, 2,
9187         5, 0, 3,
9188         5, 3, 1,
9189         0, 2, 4,
9190         2, 1, 4,
9191         3, 0, 4,
9192         1, 3, 4
9193 };
9194
9195 static const unsigned short nomodelelement3s[24] =
9196 {
9197         5, 2, 0,
9198         5, 1, 2,
9199         5, 0, 3,
9200         5, 3, 1,
9201         0, 2, 4,
9202         2, 1, 4,
9203         3, 0, 4,
9204         1, 3, 4
9205 };
9206
9207 static const float nomodelvertex3f[6*3] =
9208 {
9209         -16,   0,   0,
9210          16,   0,   0,
9211           0, -16,   0,
9212           0,  16,   0,
9213           0,   0, -16,
9214           0,   0,  16
9215 };
9216
9217 static const float nomodelcolor4f[6*4] =
9218 {
9219         0.0f, 0.0f, 0.5f, 1.0f,
9220         0.0f, 0.0f, 0.5f, 1.0f,
9221         0.0f, 0.5f, 0.0f, 1.0f,
9222         0.0f, 0.5f, 0.0f, 1.0f,
9223         0.5f, 0.0f, 0.0f, 1.0f,
9224         0.5f, 0.0f, 0.0f, 1.0f
9225 };
9226
9227 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9228 {
9229         int i;
9230         float f1, f2, *c;
9231         float color4f[6*4];
9232
9233         RSurf_ActiveCustomEntity(&ent->matrix, &ent->inversematrix, ent->flags, ent->shadertime, ent->colormod[0], ent->colormod[1], ent->colormod[2], ent->alpha, 6, nomodelvertex3f, NULL, NULL, NULL, NULL, nomodelcolor4f, 8, nomodelelement3i, nomodelelement3s, false, false);
9234
9235         // this is only called once per entity so numsurfaces is always 1, and
9236         // surfacelist is always {0}, so this code does not handle batches
9237
9238         if (rsurface.ent_flags & RENDER_ADDITIVE)
9239         {
9240                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9241                 GL_DepthMask(false);
9242         }
9243         else if (rsurface.colormod[3] < 1)
9244         {
9245                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9246                 GL_DepthMask(false);
9247         }
9248         else
9249         {
9250                 GL_BlendFunc(GL_ONE, GL_ZERO);
9251                 GL_DepthMask(true);
9252         }
9253         GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9254         GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9255         GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9256         GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9257         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9258         R_Mesh_VertexPointer(rsurface.vertex3f, rsurface.vertex3f_bufferobject, rsurface.vertex3f_bufferoffset);
9259         memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9260         R_Mesh_ColorPointer(color4f, 0, 0);
9261         for (i = 0, c = color4f;i < 6;i++, c += 4)
9262         {
9263                 c[0] *= rsurface.colormod[0];
9264                 c[1] *= rsurface.colormod[1];
9265                 c[2] *= rsurface.colormod[2];
9266                 c[3] *= rsurface.colormod[3];
9267         }
9268         if (r_refdef.fogenabled)
9269         {
9270                 for (i = 0, c = color4f;i < 6;i++, c += 4)
9271                 {
9272                         f1 = RSurf_FogVertex(rsurface.vertex3f + 3*i);
9273                         f2 = 1 - f1;
9274                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9275                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9276                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9277                 }
9278         }
9279         R_Mesh_ResetTextureState();
9280         R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, nomodelelement3s, 0, 0);
9281 }
9282
9283 void R_DrawNoModel(entity_render_t *ent)
9284 {
9285         vec3_t org;
9286         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9287         if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9288                 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9289         else
9290                 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9291 }
9292
9293 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9294 {
9295         vec3_t right1, right2, diff, normal;
9296
9297         VectorSubtract (org2, org1, normal);
9298
9299         // calculate 'right' vector for start
9300         VectorSubtract (r_refdef.view.origin, org1, diff);
9301         CrossProduct (normal, diff, right1);
9302         VectorNormalize (right1);
9303
9304         // calculate 'right' vector for end
9305         VectorSubtract (r_refdef.view.origin, org2, diff);
9306         CrossProduct (normal, diff, right2);
9307         VectorNormalize (right2);
9308
9309         vert[ 0] = org1[0] + width * right1[0];
9310         vert[ 1] = org1[1] + width * right1[1];
9311         vert[ 2] = org1[2] + width * right1[2];
9312         vert[ 3] = org1[0] - width * right1[0];
9313         vert[ 4] = org1[1] - width * right1[1];
9314         vert[ 5] = org1[2] - width * right1[2];
9315         vert[ 6] = org2[0] - width * right2[0];
9316         vert[ 7] = org2[1] - width * right2[1];
9317         vert[ 8] = org2[2] - width * right2[2];
9318         vert[ 9] = org2[0] + width * right2[0];
9319         vert[10] = org2[1] + width * right2[1];
9320         vert[11] = org2[2] + width * right2[2];
9321 }
9322
9323 void R_CalcSprite_Vertex3f(float *vertex3f, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2)
9324 {
9325         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9326         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9327         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9328         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9329         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9330         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9331         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9332         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9333         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9334         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9335         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9336         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9337 }
9338
9339 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9340 {
9341         int i;
9342         float *vertex3f;
9343         float v[3];
9344         VectorSet(v, x, y, z);
9345         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9346                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9347                         break;
9348         if (i == mesh->numvertices)
9349         {
9350                 if (mesh->numvertices < mesh->maxvertices)
9351                 {
9352                         VectorCopy(v, vertex3f);
9353                         mesh->numvertices++;
9354                 }
9355                 return mesh->numvertices;
9356         }
9357         else
9358                 return i;
9359 }
9360
9361 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9362 {
9363         int i;
9364         int *e, element[3];
9365         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9366         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9367         e = mesh->element3i + mesh->numtriangles * 3;
9368         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9369         {
9370                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9371                 if (mesh->numtriangles < mesh->maxtriangles)
9372                 {
9373                         *e++ = element[0];
9374                         *e++ = element[1];
9375                         *e++ = element[2];
9376                         mesh->numtriangles++;
9377                 }
9378                 element[1] = element[2];
9379         }
9380 }
9381
9382 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9383 {
9384         int i;
9385         int *e, element[3];
9386         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9387         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9388         e = mesh->element3i + mesh->numtriangles * 3;
9389         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9390         {
9391                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9392                 if (mesh->numtriangles < mesh->maxtriangles)
9393                 {
9394                         *e++ = element[0];
9395                         *e++ = element[1];
9396                         *e++ = element[2];
9397                         mesh->numtriangles++;
9398                 }
9399                 element[1] = element[2];
9400         }
9401 }
9402
9403 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9404 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9405 {
9406         int planenum, planenum2;
9407         int w;
9408         int tempnumpoints;
9409         mplane_t *plane, *plane2;
9410         double maxdist;
9411         double temppoints[2][256*3];
9412         // figure out how large a bounding box we need to properly compute this brush
9413         maxdist = 0;
9414         for (w = 0;w < numplanes;w++)
9415                 maxdist = max(maxdist, fabs(planes[w].dist));
9416         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9417         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9418         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9419         {
9420                 w = 0;
9421                 tempnumpoints = 4;
9422                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9423                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9424                 {
9425                         if (planenum2 == planenum)
9426                                 continue;
9427                         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);
9428                         w = !w;
9429                 }
9430                 if (tempnumpoints < 3)
9431                         continue;
9432                 // generate elements forming a triangle fan for this polygon
9433                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9434         }
9435 }
9436
9437 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)
9438 {
9439         texturelayer_t *layer;
9440         layer = t->currentlayers + t->currentnumlayers++;
9441         layer->type = type;
9442         layer->depthmask = depthmask;
9443         layer->blendfunc1 = blendfunc1;
9444         layer->blendfunc2 = blendfunc2;
9445         layer->texture = texture;
9446         layer->texmatrix = *matrix;
9447         layer->color[0] = r;
9448         layer->color[1] = g;
9449         layer->color[2] = b;
9450         layer->color[3] = a;
9451 }
9452
9453 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
9454 {
9455         if(parms[0] == 0 && parms[1] == 0)
9456                 return false;
9457         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9458                 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
9459                         return false;
9460         return true;
9461 }
9462
9463 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9464 {
9465         double index, f;
9466         index = parms[2] + r_refdef.scene.time * parms[3];
9467         index -= floor(index);
9468         switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
9469         {
9470         default:
9471         case Q3WAVEFUNC_NONE:
9472         case Q3WAVEFUNC_NOISE:
9473         case Q3WAVEFUNC_COUNT:
9474                 f = 0;
9475                 break;
9476         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
9477         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
9478         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
9479         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
9480         case Q3WAVEFUNC_TRIANGLE:
9481                 index *= 4;
9482                 f = index - floor(index);
9483                 if (index < 1)
9484                         f = f;
9485                 else if (index < 2)
9486                         f = 1 - f;
9487                 else if (index < 3)
9488                         f = -f;
9489                 else
9490                         f = -(1 - f);
9491                 break;
9492         }
9493         f = parms[0] + parms[1] * f;
9494         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9495                 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
9496         return (float) f;
9497 }
9498
9499 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
9500 {
9501         int w, h, idx;
9502         float f;
9503         float tcmat[12];
9504         matrix4x4_t matrix, temp;
9505         switch(tcmod->tcmod)
9506         {
9507                 case Q3TCMOD_COUNT:
9508                 case Q3TCMOD_NONE:
9509                         if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9510                                 matrix = r_waterscrollmatrix;
9511                         else
9512                                 matrix = identitymatrix;
9513                         break;
9514                 case Q3TCMOD_ENTITYTRANSLATE:
9515                         // this is used in Q3 to allow the gamecode to control texcoord
9516                         // scrolling on the entity, which is not supported in darkplaces yet.
9517                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
9518                         break;
9519                 case Q3TCMOD_ROTATE:
9520                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
9521                         Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
9522                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
9523                         break;
9524                 case Q3TCMOD_SCALE:
9525                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
9526                         break;
9527                 case Q3TCMOD_SCROLL:
9528                         Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
9529                         break;
9530                 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
9531                         w = (int) tcmod->parms[0];
9532                         h = (int) tcmod->parms[1];
9533                         f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
9534                         f = f - floor(f);
9535                         idx = (int) floor(f * w * h);
9536                         Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
9537                         break;
9538                 case Q3TCMOD_STRETCH:
9539                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
9540                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
9541                         break;
9542                 case Q3TCMOD_TRANSFORM:
9543                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
9544                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
9545                         VectorSet(tcmat +  6, 0                   , 0                , 1);
9546                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
9547                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
9548                         break;
9549                 case Q3TCMOD_TURBULENT:
9550                         // this is handled in the RSurf_PrepareVertices function
9551                         matrix = identitymatrix;
9552                         break;
9553         }
9554         temp = *texmatrix;
9555         Matrix4x4_Concat(texmatrix, &matrix, &temp);
9556 }
9557
9558 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
9559 {
9560         int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
9561         char name[MAX_QPATH];
9562         skinframe_t *skinframe;
9563         unsigned char pixels[296*194];
9564         strlcpy(cache->name, skinname, sizeof(cache->name));
9565         dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
9566         if (developer_loading.integer)
9567                 Con_Printf("loading %s\n", name);
9568         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
9569         if (!skinframe || !skinframe->base)
9570         {
9571                 unsigned char *f;
9572                 fs_offset_t filesize;
9573                 skinframe = NULL;
9574                 f = FS_LoadFile(name, tempmempool, true, &filesize);
9575                 if (f)
9576                 {
9577                         if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
9578                                 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
9579                         Mem_Free(f);
9580                 }
9581         }
9582         cache->skinframe = skinframe;
9583 }
9584
9585 texture_t *R_GetCurrentTexture(texture_t *t)
9586 {
9587         int i;
9588         const entity_render_t *ent = rsurface.entity;
9589         dp_model_t *model = ent->model;
9590         q3shaderinfo_layer_tcmod_t *tcmod;
9591
9592         if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
9593                 return t->currentframe;
9594         t->update_lastrenderframe = r_textureframe;
9595         t->update_lastrenderentity = (void *)ent;
9596
9597         if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
9598                 t->camera_entity = ent->entitynumber;
9599         else
9600                 t->camera_entity = 0;
9601
9602         // switch to an alternate material if this is a q1bsp animated material
9603         {
9604                 texture_t *texture = t;
9605                 int s = rsurface.ent_skinnum;
9606                 if ((unsigned int)s >= (unsigned int)model->numskins)
9607                         s = 0;
9608                 if (model->skinscenes)
9609                 {
9610                         if (model->skinscenes[s].framecount > 1)
9611                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
9612                         else
9613                                 s = model->skinscenes[s].firstframe;
9614                 }
9615                 if (s > 0)
9616                         t = t + s * model->num_surfaces;
9617                 if (t->animated)
9618                 {
9619                         // use an alternate animation if the entity's frame is not 0,
9620                         // and only if the texture has an alternate animation
9621                         if (rsurface.ent_alttextures && t->anim_total[1])
9622                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
9623                         else
9624                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
9625                 }
9626                 texture->currentframe = t;
9627         }
9628
9629         // update currentskinframe to be a qw skin or animation frame
9630         if (rsurface.ent_qwskin >= 0)
9631         {
9632                 i = rsurface.ent_qwskin;
9633                 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
9634                 {
9635                         r_qwskincache_size = cl.maxclients;
9636                         if (r_qwskincache)
9637                                 Mem_Free(r_qwskincache);
9638                         r_qwskincache = Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
9639                 }
9640                 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
9641                         R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
9642                 t->currentskinframe = r_qwskincache[i].skinframe;
9643                 if (t->currentskinframe == NULL)
9644                         t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9645         }
9646         else if (t->numskinframes >= 2)
9647                 t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9648         if (t->backgroundnumskinframes >= 2)
9649                 t->backgroundcurrentskinframe = t->backgroundskinframes[(unsigned int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
9650
9651         t->currentmaterialflags = t->basematerialflags;
9652         t->currentalpha = rsurface.colormod[3];
9653         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
9654                 t->currentalpha *= r_wateralpha.value;
9655         if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
9656                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW; // we apply wateralpha later
9657         if(!r_waterstate.enabled || r_refdef.view.isoverlay)
9658                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
9659         if (!(rsurface.ent_flags & RENDER_LIGHT))
9660                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
9661         else if (FAKELIGHT_ENABLED)
9662         {
9663                         // no modellight if using fakelight for the map
9664         }
9665         else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
9666         {
9667                 // pick a model lighting mode
9668                 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
9669                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
9670                 else
9671                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
9672         }
9673         if (rsurface.ent_flags & RENDER_ADDITIVE)
9674                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9675         else if (t->currentalpha < 1)
9676                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9677         if (rsurface.ent_flags & RENDER_DOUBLESIDED)
9678                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
9679         if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
9680                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
9681         if (t->backgroundnumskinframes)
9682                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
9683         if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
9684         {
9685                 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
9686                         t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
9687         }
9688         else
9689                 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
9690         if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
9691                 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
9692
9693         // there is no tcmod
9694         if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9695         {
9696                 t->currenttexmatrix = r_waterscrollmatrix;
9697                 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
9698         }
9699         else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
9700         {
9701                 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
9702                 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
9703         }
9704
9705         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9706                 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
9707         for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9708                 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
9709
9710         t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
9711         if (t->currentskinframe->qpixels)
9712                 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
9713         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
9714         if (!t->basetexture)
9715                 t->basetexture = r_texture_notexture;
9716         t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
9717         t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
9718         t->nmaptexture = t->currentskinframe->nmap;
9719         if (!t->nmaptexture)
9720                 t->nmaptexture = r_texture_blanknormalmap;
9721         t->glosstexture = r_texture_black;
9722         t->glowtexture = t->currentskinframe->glow;
9723         t->fogtexture = t->currentskinframe->fog;
9724         t->reflectmasktexture = t->currentskinframe->reflect;
9725         if (t->backgroundnumskinframes)
9726         {
9727                 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
9728                 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
9729                 t->backgroundglosstexture = r_texture_black;
9730                 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
9731                 if (!t->backgroundnmaptexture)
9732                         t->backgroundnmaptexture = r_texture_blanknormalmap;
9733         }
9734         else
9735         {
9736                 t->backgroundbasetexture = t->backgroundnumskinframes ? ((!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base) : r_texture_white;
9737                 t->backgroundnmaptexture = r_texture_blanknormalmap;
9738                 t->backgroundglosstexture = r_texture_black;
9739                 t->backgroundglowtexture = NULL;
9740         }
9741         t->specularpower = r_shadow_glossexponent.value;
9742         // TODO: store reference values for these in the texture?
9743         t->specularscale = 0;
9744         if (r_shadow_gloss.integer > 0)
9745         {
9746                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
9747                 {
9748                         if (r_shadow_glossintensity.value > 0)
9749                         {
9750                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
9751                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
9752                                 t->specularscale = r_shadow_glossintensity.value;
9753                         }
9754                 }
9755                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
9756                 {
9757                         t->glosstexture = r_texture_white;
9758                         t->backgroundglosstexture = r_texture_white;
9759                         t->specularscale = r_shadow_gloss2intensity.value;
9760                         t->specularpower = r_shadow_gloss2exponent.value;
9761                 }
9762         }
9763         t->specularscale *= t->specularscalemod;
9764         t->specularpower *= t->specularpowermod;
9765
9766         // lightmaps mode looks bad with dlights using actual texturing, so turn
9767         // off the colormap and glossmap, but leave the normalmap on as it still
9768         // accurately represents the shading involved
9769         if (gl_lightmaps.integer)
9770         {
9771                 t->basetexture = r_texture_grey128;
9772                 t->pantstexture = r_texture_black;
9773                 t->shirttexture = r_texture_black;
9774                 t->nmaptexture = r_texture_blanknormalmap;
9775                 t->glosstexture = r_texture_black;
9776                 t->glowtexture = NULL;
9777                 t->fogtexture = NULL;
9778                 t->reflectmasktexture = NULL;
9779                 t->backgroundbasetexture = NULL;
9780                 t->backgroundnmaptexture = r_texture_blanknormalmap;
9781                 t->backgroundglosstexture = r_texture_black;
9782                 t->backgroundglowtexture = NULL;
9783                 t->specularscale = 0;
9784                 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
9785         }
9786
9787         Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
9788         VectorClear(t->dlightcolor);
9789         t->currentnumlayers = 0;
9790         if (t->currentmaterialflags & MATERIALFLAG_WALL)
9791         {
9792                 int blendfunc1, blendfunc2;
9793                 qboolean depthmask;
9794                 if (t->currentmaterialflags & MATERIALFLAG_ADD)
9795                 {
9796                         blendfunc1 = GL_SRC_ALPHA;
9797                         blendfunc2 = GL_ONE;
9798                 }
9799                 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
9800                 {
9801                         blendfunc1 = GL_SRC_ALPHA;
9802                         blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
9803                 }
9804                 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
9805                 {
9806                         blendfunc1 = t->customblendfunc[0];
9807                         blendfunc2 = t->customblendfunc[1];
9808                 }
9809                 else
9810                 {
9811                         blendfunc1 = GL_ONE;
9812                         blendfunc2 = GL_ZERO;
9813                 }
9814                 // don't colormod evilblend textures
9815                 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
9816                         VectorSet(t->lightmapcolor, 1, 1, 1);
9817                 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
9818                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
9819                 {
9820                         // fullbright is not affected by r_refdef.lightmapintensity
9821                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
9822                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9823                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9824                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9825                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9826                 }
9827                 else
9828                 {
9829                         vec3_t ambientcolor;
9830                         float colorscale;
9831                         // set the color tint used for lights affecting this surface
9832                         VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
9833                         colorscale = 2;
9834                         // q3bsp has no lightmap updates, so the lightstylevalue that
9835                         // would normally be baked into the lightmap must be
9836                         // applied to the color
9837                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
9838                         if (model->type == mod_brushq3)
9839                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
9840                         colorscale *= r_refdef.lightmapintensity;
9841                         VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
9842                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
9843                         // basic lit geometry
9844                         R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
9845                         // add pants/shirt if needed
9846                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9847                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2]  * t->lightmapcolor[2], t->lightmapcolor[3]);
9848                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9849                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
9850                         // now add ambient passes if needed
9851                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
9852                         {
9853                                 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
9854                                 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9855                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * ambientcolor[0], rsurface.colormap_pantscolor[1] * ambientcolor[1], rsurface.colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
9856                                 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9857                                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * ambientcolor[0], rsurface.colormap_shirtcolor[1] * ambientcolor[1], rsurface.colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
9858                         }
9859                 }
9860                 if (t->glowtexture != NULL && !gl_lightmaps.integer)
9861                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->glowtexture, &t->currenttexmatrix, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2], t->lightmapcolor[3]);
9862                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
9863                 {
9864                         // if this is opaque use alpha blend which will darken the earlier
9865                         // passes cheaply.
9866                         //
9867                         // if this is an alpha blended material, all the earlier passes
9868                         // were darkened by fog already, so we only need to add the fog
9869                         // color ontop through the fog mask texture
9870                         //
9871                         // if this is an additive blended material, all the earlier passes
9872                         // were darkened by fog already, and we should not add fog color
9873                         // (because the background was not darkened, there is no fog color
9874                         // that was lost behind it).
9875                         R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->fogtexture, &t->currenttexmatrix, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], t->lightmapcolor[3]);
9876                 }
9877         }
9878
9879         return t->currentframe;
9880 }
9881
9882 rsurfacestate_t rsurface;
9883
9884 void R_Mesh_ResizeArrays(int newvertices)
9885 {
9886         float *base;
9887         if (rsurface.array_size >= newvertices)
9888                 return;
9889         if (rsurface.array_modelvertex3f)
9890                 Mem_Free(rsurface.array_modelvertex3f);
9891         rsurface.array_size = (newvertices + 1023) & ~1023;
9892         base = (float *)Mem_Alloc(r_main_mempool, rsurface.array_size * sizeof(float[33]));
9893         rsurface.array_modelvertex3f     = base + rsurface.array_size * 0;
9894         rsurface.array_modelsvector3f    = base + rsurface.array_size * 3;
9895         rsurface.array_modeltvector3f    = base + rsurface.array_size * 6;
9896         rsurface.array_modelnormal3f     = base + rsurface.array_size * 9;
9897         rsurface.array_deformedvertex3f  = base + rsurface.array_size * 12;
9898         rsurface.array_deformedsvector3f = base + rsurface.array_size * 15;
9899         rsurface.array_deformedtvector3f = base + rsurface.array_size * 18;
9900         rsurface.array_deformednormal3f  = base + rsurface.array_size * 21;
9901         rsurface.array_texcoord3f        = base + rsurface.array_size * 24;
9902         rsurface.array_color4f           = base + rsurface.array_size * 27;
9903         rsurface.array_generatedtexcoordtexture2f = base + rsurface.array_size * 31;
9904 }
9905
9906 void RSurf_ActiveWorldEntity(void)
9907 {
9908         dp_model_t *model = r_refdef.scene.worldmodel;
9909         //if (rsurface.entity == r_refdef.scene.worldentity)
9910         //      return;
9911         rsurface.entity = r_refdef.scene.worldentity;
9912         rsurface.skeleton = NULL;
9913         memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
9914         rsurface.ent_skinnum = 0;
9915         rsurface.ent_qwskin = -1;
9916         rsurface.ent_shadertime = 0;
9917         rsurface.ent_flags = r_refdef.scene.worldentity->flags;
9918         if (rsurface.array_size < model->surfmesh.num_vertices)
9919                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9920         rsurface.matrix = identitymatrix;
9921         rsurface.inversematrix = identitymatrix;
9922         rsurface.matrixscale = 1;
9923         rsurface.inversematrixscale = 1;
9924         R_EntityMatrix(&identitymatrix);
9925         VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
9926         Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
9927         rsurface.fograngerecip = r_refdef.fograngerecip;
9928         rsurface.fogheightfade = r_refdef.fogheightfade;
9929         rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
9930         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9931         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9932         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9933         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9934         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9935         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9936         VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
9937         rsurface.colormod[3] = 1;
9938         VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
9939         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9940         rsurface.frameblend[0].lerp = 1;
9941         rsurface.ent_alttextures = false;
9942         rsurface.basepolygonfactor = r_refdef.polygonfactor;
9943         rsurface.basepolygonoffset = r_refdef.polygonoffset;
9944         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
9945         rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
9946         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9947         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9948         rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
9949         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9950         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9951         rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
9952         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9953         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
9954         rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
9955         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9956         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
9957         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
9958         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9959         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
9960         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
9961         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9962         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
9963         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
9964         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9965         rsurface.modelelement3i = model->surfmesh.data_element3i;
9966         rsurface.modelelement3s = model->surfmesh.data_element3s;
9967         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo3i;
9968         rsurface.modelelement3s_bufferobject = model->surfmesh.ebo3s;
9969         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9970         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
9971         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
9972         rsurface.modelsurfaces = model->data_surfaces;
9973         rsurface.generatedvertex = false;
9974         rsurface.vertex3f  = rsurface.modelvertex3f;
9975         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
9976         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
9977         rsurface.svector3f = rsurface.modelsvector3f;
9978         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
9979         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
9980         rsurface.tvector3f = rsurface.modeltvector3f;
9981         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
9982         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
9983         rsurface.normal3f  = rsurface.modelnormal3f;
9984         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
9985         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
9986         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
9987 }
9988
9989 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
9990 {
9991         dp_model_t *model = ent->model;
9992         //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
9993         //      return;
9994         rsurface.entity = (entity_render_t *)ent;
9995         rsurface.skeleton = ent->skeleton;
9996         memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
9997         rsurface.ent_skinnum = ent->skinnum;
9998         rsurface.ent_qwskin = (ent->entitynumber <= cl.maxclients && ent->entitynumber >= 1 && cls.protocol == PROTOCOL_QUAKEWORLD && cl.scores[ent->entitynumber - 1].qw_skin[0] && !strcmp(ent->model->name, "progs/player.mdl")) ? (ent->entitynumber - 1) : -1;
9999         rsurface.ent_shadertime = ent->shadertime;
10000         rsurface.ent_flags = ent->flags;
10001         if (rsurface.array_size < model->surfmesh.num_vertices)
10002                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10003         rsurface.matrix = ent->matrix;
10004         rsurface.inversematrix = ent->inversematrix;
10005         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10006         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10007         R_EntityMatrix(&rsurface.matrix);
10008         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10009         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10010         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10011         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10012         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10013         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10014         VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10015         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10016         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10017         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10018         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10019         VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10020         rsurface.colormod[3] = ent->alpha;
10021         VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10022         memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10023         rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10024         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10025         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10026         if (ent->model->brush.submodel && !prepass)
10027         {
10028                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10029                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10030         }
10031         if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10032         {
10033                 if (ent->animcache_vertex3f && !r_framedata_failed)
10034                 {
10035                         rsurface.modelvertex3f = ent->animcache_vertex3f;
10036                         rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10037                         rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10038                         rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10039                 }
10040                 else if (wanttangents)
10041                 {
10042                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10043                         rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10044                         rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10045                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10046                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
10047                 }
10048                 else if (wantnormals)
10049                 {
10050                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10051                         rsurface.modelsvector3f = NULL;
10052                         rsurface.modeltvector3f = NULL;
10053                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10054                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
10055                 }
10056                 else
10057                 {
10058                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10059                         rsurface.modelsvector3f = NULL;
10060                         rsurface.modeltvector3f = NULL;
10061                         rsurface.modelnormal3f = NULL;
10062                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
10063                 }
10064                 rsurface.modelvertex3f_bufferobject = 0;
10065                 rsurface.modelvertex3f_bufferoffset = 0;
10066                 rsurface.modelsvector3f_bufferobject = 0;
10067                 rsurface.modelsvector3f_bufferoffset = 0;
10068                 rsurface.modeltvector3f_bufferobject = 0;
10069                 rsurface.modeltvector3f_bufferoffset = 0;
10070                 rsurface.modelnormal3f_bufferobject = 0;
10071                 rsurface.modelnormal3f_bufferoffset = 0;
10072                 rsurface.generatedvertex = true;
10073         }
10074         else
10075         {
10076                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
10077                 rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
10078                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10079                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10080                 rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
10081                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10082                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10083                 rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
10084                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10085                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
10086                 rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
10087                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10088                 rsurface.generatedvertex = false;
10089         }
10090         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
10091         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
10092         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10093         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
10094         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
10095         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10096         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
10097         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
10098         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10099         rsurface.modelelement3i = model->surfmesh.data_element3i;
10100         rsurface.modelelement3s = model->surfmesh.data_element3s;
10101         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo3i;
10102         rsurface.modelelement3s_bufferobject = model->surfmesh.ebo3s;
10103         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10104         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
10105         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
10106         rsurface.modelsurfaces = model->data_surfaces;
10107         rsurface.vertex3f  = rsurface.modelvertex3f;
10108         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
10109         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10110         rsurface.svector3f = rsurface.modelsvector3f;
10111         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
10112         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10113         rsurface.tvector3f = rsurface.modeltvector3f;
10114         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
10115         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10116         rsurface.normal3f  = rsurface.modelnormal3f;
10117         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
10118         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10119         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
10120 }
10121
10122 void RSurf_ActiveCustomEntity(const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, int entflags, double shadertime, float r, float g, float b, float a, int numvertices, const float *vertex3f, const float *texcoord2f, const float *normal3f, const float *svector3f, const float *tvector3f, const float *color4f, int numtriangles, const int *element3i, const unsigned short *element3s, qboolean wantnormals, qboolean wanttangents)
10123 {
10124         rsurface.entity = r_refdef.scene.worldentity;
10125         rsurface.skeleton = NULL;
10126         rsurface.ent_skinnum = 0;
10127         rsurface.ent_qwskin = -1;
10128         rsurface.ent_shadertime = shadertime;
10129         rsurface.ent_flags = entflags;
10130         rsurface.modelnum_vertices = numvertices;
10131         rsurface.modelnum_triangles = numtriangles;
10132         if (rsurface.array_size < rsurface.modelnum_vertices)
10133                 R_Mesh_ResizeArrays(rsurface.modelnum_vertices);
10134         rsurface.matrix = *matrix;
10135         rsurface.inversematrix = *inversematrix;
10136         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10137         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10138         R_EntityMatrix(&rsurface.matrix);
10139         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10140         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10141         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10142         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10143         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10144         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10145         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10146         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10147         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10148         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10149         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10150         Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10151         VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
10152         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10153         rsurface.frameblend[0].lerp = 1;
10154         rsurface.ent_alttextures = false;
10155         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10156         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10157         if (wanttangents)
10158         {
10159                 rsurface.modelvertex3f = vertex3f;
10160                 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
10161                 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
10162                 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10163         }
10164         else if (wantnormals)
10165         {
10166                 rsurface.modelvertex3f = vertex3f;
10167                 rsurface.modelsvector3f = NULL;
10168                 rsurface.modeltvector3f = NULL;
10169                 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10170         }
10171         else
10172         {
10173                 rsurface.modelvertex3f = vertex3f;
10174                 rsurface.modelsvector3f = NULL;
10175                 rsurface.modeltvector3f = NULL;
10176                 rsurface.modelnormal3f = NULL;
10177         }
10178         rsurface.modelvertex3f_bufferobject = 0;
10179         rsurface.modelvertex3f_bufferoffset = 0;
10180         rsurface.modelsvector3f_bufferobject = 0;
10181         rsurface.modelsvector3f_bufferoffset = 0;
10182         rsurface.modeltvector3f_bufferobject = 0;
10183         rsurface.modeltvector3f_bufferoffset = 0;
10184         rsurface.modelnormal3f_bufferobject = 0;
10185         rsurface.modelnormal3f_bufferoffset = 0;
10186         rsurface.generatedvertex = true;
10187         rsurface.modellightmapcolor4f  = color4f;
10188         rsurface.modellightmapcolor4f_bufferobject = 0;
10189         rsurface.modellightmapcolor4f_bufferoffset = 0;
10190         rsurface.modeltexcoordtexture2f  = texcoord2f;
10191         rsurface.modeltexcoordtexture2f_bufferobject = 0;
10192         rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10193         rsurface.modeltexcoordlightmap2f  = NULL;
10194         rsurface.modeltexcoordlightmap2f_bufferobject = 0;
10195         rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10196         rsurface.modelelement3i = element3i;
10197         rsurface.modelelement3s = element3s;
10198         rsurface.modelelement3i_bufferobject = 0;
10199         rsurface.modelelement3s_bufferobject = 0;
10200         rsurface.modellightmapoffsets = NULL;
10201         rsurface.modelsurfaces = NULL;
10202         rsurface.vertex3f  = rsurface.modelvertex3f;
10203         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
10204         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10205         rsurface.svector3f = rsurface.modelsvector3f;
10206         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
10207         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10208         rsurface.tvector3f = rsurface.modeltvector3f;
10209         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
10210         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10211         rsurface.normal3f  = rsurface.modelnormal3f;
10212         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
10213         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10214         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
10215
10216         if (rsurface.modelnum_vertices && rsurface.modelelement3i)
10217         {
10218                 if ((wantnormals || wanttangents) && !normal3f)
10219                         Mod_BuildNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10220                 if (wanttangents && !svector3f)
10221                         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 != 0);
10222         }
10223 }
10224
10225 float RSurf_FogPoint(const float *v)
10226 {
10227         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10228         float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10229         float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10230         float FogHeightFade = r_refdef.fogheightfade;
10231         float fogfrac;
10232         unsigned int fogmasktableindex;
10233         if (r_refdef.fogplaneviewabove)
10234                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10235         else
10236                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10237         fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10238         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10239 }
10240
10241 float RSurf_FogVertex(const float *v)
10242 {
10243         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10244         float FogPlaneViewDist = rsurface.fogplaneviewdist;
10245         float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10246         float FogHeightFade = rsurface.fogheightfade;
10247         float fogfrac;
10248         unsigned int fogmasktableindex;
10249         if (r_refdef.fogplaneviewabove)
10250                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10251         else
10252                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10253         fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10254         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10255 }
10256
10257 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10258 void RSurf_PrepareVerticesForBatch(qboolean generatenormals, qboolean generatetangents, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10259 {
10260         int deformindex;
10261         int texturesurfaceindex;
10262         int i, j;
10263         float amplitude;
10264         float animpos;
10265         float scale;
10266         const float *v1, *in_tc;
10267         float *out_tc;
10268         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10269         float waveparms[4];
10270         q3shaderinfo_deform_t *deform;
10271         // 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
10272         if (rsurface.generatedvertex)
10273         {
10274                 if (rsurface.texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
10275                         generatenormals = true;
10276                 for (i = 0;i < Q3MAXDEFORMS;i++)
10277                 {
10278                         if (rsurface.texture->deforms[i].deform == Q3DEFORM_AUTOSPRITE)
10279                         {
10280                                 generatetangents = true;
10281                                 generatenormals = true;
10282                         }
10283                         if (rsurface.texture->deforms[i].deform != Q3DEFORM_NONE)
10284                                 generatenormals = true;
10285                 }
10286                 if (generatenormals && !rsurface.modelnormal3f)
10287                 {
10288                         rsurface.normal3f = rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10289                         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject = 0;
10290                         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset = 0;
10291                         Mod_BuildNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10292                 }
10293                 if (generatetangents && !rsurface.modelsvector3f)
10294                 {
10295                         rsurface.svector3f = rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10296                         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject = 0;
10297                         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset = 0;
10298                         rsurface.tvector3f = rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10299                         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject = 0;
10300                         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset = 0;
10301                         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 != 0);
10302                 }
10303         }
10304         rsurface.vertex3f  = rsurface.modelvertex3f;
10305         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
10306         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10307         rsurface.svector3f = rsurface.modelsvector3f;
10308         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
10309         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10310         rsurface.tvector3f = rsurface.modeltvector3f;
10311         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
10312         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10313         rsurface.normal3f  = rsurface.modelnormal3f;
10314         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
10315         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10316         // if vertices are deformed (sprite flares and things in maps, possibly
10317         // water waves, bulges and other deformations), generate them into
10318         // rsurface.deform* arrays from whatever the rsurface.* arrays point to
10319         // (may be static model data or generated data for an animated model, or
10320         //  the previous deform pass)
10321         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10322         {
10323                 switch (deform->deform)
10324                 {
10325                 default:
10326                 case Q3DEFORM_PROJECTIONSHADOW:
10327                 case Q3DEFORM_TEXT0:
10328                 case Q3DEFORM_TEXT1:
10329                 case Q3DEFORM_TEXT2:
10330                 case Q3DEFORM_TEXT3:
10331                 case Q3DEFORM_TEXT4:
10332                 case Q3DEFORM_TEXT5:
10333                 case Q3DEFORM_TEXT6:
10334                 case Q3DEFORM_TEXT7:
10335                 case Q3DEFORM_NONE:
10336                         break;
10337                 case Q3DEFORM_AUTOSPRITE:
10338                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10339                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10340                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10341                         VectorNormalize(newforward);
10342                         VectorNormalize(newright);
10343                         VectorNormalize(newup);
10344                         // make deformed versions of only the model vertices used by the specified surfaces
10345                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10346                         {
10347                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10348                                 // a single autosprite surface can contain multiple sprites...
10349                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
10350                                 {
10351                                         VectorClear(center);
10352                                         for (i = 0;i < 4;i++)
10353                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
10354                                         VectorScale(center, 0.25f, center);
10355                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, forward);
10356                                         VectorCopy((rsurface.svector3f + 3 * surface->num_firstvertex) + j*3, right);
10357                                         VectorCopy((rsurface.tvector3f + 3 * surface->num_firstvertex) + j*3, up);
10358                                         for (i = 0;i < 4;i++)
10359                                         {
10360                                                 VectorSubtract((rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i)*3, center, v);
10361                                                 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
10362                                         }
10363                                 }
10364                                 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 != 0);
10365                                 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 != 0);
10366                         }
10367                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10368                         rsurface.vertex3f_bufferobject = 0;
10369                         rsurface.vertex3f_bufferoffset = 0;
10370                         rsurface.svector3f = rsurface.array_deformedsvector3f;
10371                         rsurface.svector3f_bufferobject = 0;
10372                         rsurface.svector3f_bufferoffset = 0;
10373                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
10374                         rsurface.tvector3f_bufferobject = 0;
10375                         rsurface.tvector3f_bufferoffset = 0;
10376                         rsurface.normal3f = rsurface.array_deformednormal3f;
10377                         rsurface.normal3f_bufferobject = 0;
10378                         rsurface.normal3f_bufferoffset = 0;
10379                         break;
10380                 case Q3DEFORM_AUTOSPRITE2:
10381                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10382                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10383                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10384                         VectorNormalize(newforward);
10385                         VectorNormalize(newright);
10386                         VectorNormalize(newup);
10387                         // make deformed versions of only the model vertices used by the specified surfaces
10388                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10389                         {
10390                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10391                                 const float *v1, *v2;
10392                                 vec3_t start, end;
10393                                 float f, l;
10394                                 struct
10395                                 {
10396                                         float length2;
10397                                         const float *v1;
10398                                         const float *v2;
10399                                 }
10400                                 shortest[2];
10401                                 memset(shortest, 0, sizeof(shortest));
10402                                 // a single autosprite surface can contain multiple sprites...
10403                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
10404                                 {
10405                                         VectorClear(center);
10406                                         for (i = 0;i < 4;i++)
10407                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
10408                                         VectorScale(center, 0.25f, center);
10409                                         // find the two shortest edges, then use them to define the
10410                                         // axis vectors for rotating around the central axis
10411                                         for (i = 0;i < 6;i++)
10412                                         {
10413                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][0]);
10414                                                 v2 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][1]);
10415 #if 0
10416                                                 Debug_PolygonBegin(NULL, 0);
10417                                                 Debug_PolygonVertex(v1[0], v1[1], v1[2], 0, 0, 1, 0, 0, 1);
10418                                                 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);
10419                                                 Debug_PolygonVertex(v2[0], v2[1], v2[2], 0, 0, 1, 0, 0, 1);
10420                                                 Debug_PolygonEnd();
10421 #endif
10422                                                 l = VectorDistance2(v1, v2);
10423                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
10424                                                 if (v1[2] != v2[2])
10425                                                         l += (1.0f / 1024.0f);
10426                                                 if (shortest[0].length2 > l || i == 0)
10427                                                 {
10428                                                         shortest[1] = shortest[0];
10429                                                         shortest[0].length2 = l;
10430                                                         shortest[0].v1 = v1;
10431                                                         shortest[0].v2 = v2;
10432                                                 }
10433                                                 else if (shortest[1].length2 > l || i == 1)
10434                                                 {
10435                                                         shortest[1].length2 = l;
10436                                                         shortest[1].v1 = v1;
10437                                                         shortest[1].v2 = v2;
10438                                                 }
10439                                         }
10440                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
10441                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
10442 #if 0
10443                                         Debug_PolygonBegin(NULL, 0);
10444                                         Debug_PolygonVertex(start[0], start[1], start[2], 0, 0, 1, 1, 0, 1);
10445                                         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);
10446                                         Debug_PolygonVertex(end[0], end[1], end[2], 0, 0, 0, 1, 1, 1);
10447                                         Debug_PolygonEnd();
10448 #endif
10449                                         // this calculates the right vector from the shortest edge
10450                                         // and the up vector from the edge midpoints
10451                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
10452                                         VectorNormalize(right);
10453                                         VectorSubtract(end, start, up);
10454                                         VectorNormalize(up);
10455                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
10456                                         VectorSubtract(rsurface.localvieworigin, center, forward);
10457                                         //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
10458                                         VectorNegate(forward, forward);
10459                                         VectorReflect(forward, 0, up, forward);
10460                                         VectorNormalize(forward);
10461                                         CrossProduct(up, forward, newright);
10462                                         VectorNormalize(newright);
10463 #if 0
10464                                         Debug_PolygonBegin(NULL, 0);
10465                                         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);
10466                                         Debug_PolygonVertex(center[0] + right[0] * 8, center[1] + right[1] * 8, center[2] + right[2] * 8, 0, 0, 0, 1, 0, 1);
10467                                         Debug_PolygonVertex(center[0] + up   [0] * 8, center[1] + up   [1] * 8, center[2] + up   [2] * 8, 0, 0, 0, 0, 1, 1);
10468                                         Debug_PolygonEnd();
10469 #endif
10470 #if 0
10471                                         Debug_PolygonBegin(NULL, 0);
10472                                         Debug_PolygonVertex(center[0] + forward [0] * 8, center[1] + forward [1] * 8, center[2] + forward [2] * 8, 0, 0, 1, 0, 0, 1);
10473                                         Debug_PolygonVertex(center[0] + newright[0] * 8, center[1] + newright[1] * 8, center[2] + newright[2] * 8, 0, 0, 0, 1, 0, 1);
10474                                         Debug_PolygonVertex(center[0] + up      [0] * 8, center[1] + up      [1] * 8, center[2] + up      [2] * 8, 0, 0, 0, 0, 1, 1);
10475                                         Debug_PolygonEnd();
10476 #endif
10477                                         // rotate the quad around the up axis vector, this is made
10478                                         // especially easy by the fact we know the quad is flat,
10479                                         // so we only have to subtract the center position and
10480                                         // measure distance along the right vector, and then
10481                                         // multiply that by the newright vector and add back the
10482                                         // center position
10483                                         // we also need to subtract the old position to undo the
10484                                         // displacement from the center, which we do with a
10485                                         // DotProduct, the subtraction/addition of center is also
10486                                         // optimized into DotProducts here
10487                                         l = DotProduct(right, center);
10488                                         for (i = 0;i < 4;i++)
10489                                         {
10490                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + j + i);
10491                                                 f = DotProduct(right, v1) - l;
10492                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
10493                                         }
10494                                 }
10495                                 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 != 0);
10496                                 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 != 0);
10497                         }
10498                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10499                         rsurface.vertex3f_bufferobject = 0;
10500                         rsurface.vertex3f_bufferoffset = 0;
10501                         rsurface.svector3f = rsurface.array_deformedsvector3f;
10502                         rsurface.svector3f_bufferobject = 0;
10503                         rsurface.svector3f_bufferoffset = 0;
10504                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
10505                         rsurface.tvector3f_bufferobject = 0;
10506                         rsurface.tvector3f_bufferoffset = 0;
10507                         rsurface.normal3f = rsurface.array_deformednormal3f;
10508                         rsurface.normal3f_bufferobject = 0;
10509                         rsurface.normal3f_bufferoffset = 0;
10510                         break;
10511                 case Q3DEFORM_NORMAL:
10512                         // deform the normals to make reflections wavey
10513                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10514                         {
10515                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10516                                 for (j = 0;j < surface->num_vertices;j++)
10517                                 {
10518                                         float vertex[3];
10519                                         float *normal = (rsurface.array_deformednormal3f  + 3 * surface->num_firstvertex) + j*3;
10520                                         VectorScale((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, 0.98f, vertex);
10521                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, normal);
10522                                         normal[0] += deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10523                                         normal[1] += deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10524                                         normal[2] += deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10525                                         VectorNormalize(normal);
10526                                 }
10527                                 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 != 0);
10528                         }
10529                         rsurface.svector3f = rsurface.array_deformedsvector3f;
10530                         rsurface.svector3f_bufferobject = 0;
10531                         rsurface.svector3f_bufferoffset = 0;
10532                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
10533                         rsurface.tvector3f_bufferobject = 0;
10534                         rsurface.tvector3f_bufferoffset = 0;
10535                         rsurface.normal3f = rsurface.array_deformednormal3f;
10536                         rsurface.normal3f_bufferobject = 0;
10537                         rsurface.normal3f_bufferoffset = 0;
10538                         break;
10539                 case Q3DEFORM_WAVE:
10540                         // deform vertex array to make wavey water and flags and such
10541                         waveparms[0] = deform->waveparms[0];
10542                         waveparms[1] = deform->waveparms[1];
10543                         waveparms[2] = deform->waveparms[2];
10544                         waveparms[3] = deform->waveparms[3];
10545                         if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
10546                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
10547                         // this is how a divisor of vertex influence on deformation
10548                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
10549                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10550                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10551                         {
10552                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10553                                 for (j = 0;j < surface->num_vertices;j++)
10554                                 {
10555                                         float *vertex = (rsurface.array_deformedvertex3f  + 3 * surface->num_firstvertex) + j*3;
10556                                         VectorCopy((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, vertex);
10557                                         // if the wavefunc depends on time, evaluate it per-vertex
10558                                         if (waveparms[3])
10559                                         {
10560                                                 waveparms[2] = deform->waveparms[2] + (vertex[0] + vertex[1] + vertex[2]) * animpos;
10561                                                 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10562                                         }
10563                                         VectorMA(vertex, scale, (rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, vertex);
10564                                 }
10565                         }
10566                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10567                         rsurface.vertex3f_bufferobject = 0;
10568                         rsurface.vertex3f_bufferoffset = 0;
10569                         break;
10570                 case Q3DEFORM_BULGE:
10571                         // deform vertex array to make the surface have moving bulges
10572                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10573                         {
10574                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10575                                 for (j = 0;j < surface->num_vertices;j++)
10576                                 {
10577                                         scale = sin((rsurface.modeltexcoordtexture2f[2 * (surface->num_firstvertex + j)] * deform->parms[0] + r_refdef.scene.time * deform->parms[2])) * deform->parms[1];
10578                                         VectorMA(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), scale, rsurface.normal3f + 3 * (surface->num_firstvertex + j), rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
10579                                 }
10580                         }
10581                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10582                         rsurface.vertex3f_bufferobject = 0;
10583                         rsurface.vertex3f_bufferoffset = 0;
10584                         break;
10585                 case Q3DEFORM_MOVE:
10586                         // deform vertex array
10587                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
10588                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
10589                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
10590                         VectorScale(deform->parms, scale, waveparms);
10591                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10592                         {
10593                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10594                                 for (j = 0;j < surface->num_vertices;j++)
10595                                         VectorAdd(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), waveparms, rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
10596                         }
10597                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10598                         rsurface.vertex3f_bufferobject = 0;
10599                         rsurface.vertex3f_bufferoffset = 0;
10600                         break;
10601                 }
10602         }
10603         // generate texcoords based on the chosen texcoord source
10604         switch(rsurface.texture->tcgen.tcgen)
10605         {
10606         default:
10607         case Q3TCGEN_TEXTURE:
10608                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordtexture2f;
10609                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordtexture2f_bufferobject;
10610                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
10611                 break;
10612         case Q3TCGEN_LIGHTMAP:
10613                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordlightmap2f;
10614                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordlightmap2f_bufferobject;
10615                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordlightmap2f_bufferoffset;
10616                 break;
10617         case Q3TCGEN_VECTOR:
10618                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10619                 {
10620                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10621                         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)
10622                         {
10623                                 out_tc[0] = DotProduct(v1, rsurface.texture->tcgen.parms);
10624                                 out_tc[1] = DotProduct(v1, rsurface.texture->tcgen.parms + 3);
10625                         }
10626                 }
10627                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
10628                 rsurface.texcoordtexture2f_bufferobject  = 0;
10629                 rsurface.texcoordtexture2f_bufferoffset  = 0;
10630                 break;
10631         case Q3TCGEN_ENVIRONMENT:
10632                 // make environment reflections using a spheremap
10633                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10634                 {
10635                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10636                         const float *vertex = rsurface.modelvertex3f + 3 * surface->num_firstvertex;
10637                         const float *normal = rsurface.modelnormal3f + 3 * surface->num_firstvertex;
10638                         float *out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;
10639                         for (j = 0;j < surface->num_vertices;j++, vertex += 3, normal += 3, out_tc += 2)
10640                         {
10641                                 // identical to Q3A's method, but executed in worldspace so
10642                                 // carried models can be shiny too
10643
10644                                 float viewer[3], d, reflected[3], worldreflected[3];
10645
10646                                 VectorSubtract(rsurface.localvieworigin, vertex, viewer);
10647                                 // VectorNormalize(viewer);
10648
10649                                 d = DotProduct(normal, viewer);
10650
10651                                 reflected[0] = normal[0]*2*d - viewer[0];
10652                                 reflected[1] = normal[1]*2*d - viewer[1];
10653                                 reflected[2] = normal[2]*2*d - viewer[2];
10654                                 // note: this is proportinal to viewer, so we can normalize later
10655
10656                                 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
10657                                 VectorNormalize(worldreflected);
10658
10659                                 // note: this sphere map only uses world x and z!
10660                                 // so positive and negative y will LOOK THE SAME.
10661                                 out_tc[0] = 0.5 + 0.5 * worldreflected[1];
10662                                 out_tc[1] = 0.5 - 0.5 * worldreflected[2];
10663                         }
10664                 }
10665                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
10666                 rsurface.texcoordtexture2f_bufferobject  = 0;
10667                 rsurface.texcoordtexture2f_bufferoffset  = 0;
10668                 break;
10669         }
10670         // the only tcmod that needs software vertex processing is turbulent, so
10671         // check for it here and apply the changes if needed
10672         // and we only support that as the first one
10673         // (handling a mixture of turbulent and other tcmods would be problematic
10674         //  without punting it entirely to a software path)
10675         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10676         {
10677                 amplitude = rsurface.texture->tcmods[0].parms[1];
10678                 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
10679                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10680                 {
10681                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10682                         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)
10683                         {
10684                                 out_tc[0] = in_tc[0] + amplitude * sin(((v1[0] + v1[2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10685                                 out_tc[1] = in_tc[1] + amplitude * sin(((v1[1]        ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10686                         }
10687                 }
10688                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
10689                 rsurface.texcoordtexture2f_bufferobject  = 0;
10690                 rsurface.texcoordtexture2f_bufferoffset  = 0;
10691         }
10692         rsurface.texcoordlightmap2f              = rsurface.modeltexcoordlightmap2f;
10693         rsurface.texcoordlightmap2f_bufferobject = rsurface.modeltexcoordlightmap2f_bufferobject;
10694         rsurface.texcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
10695         R_Mesh_VertexPointer(rsurface.vertex3f, rsurface.vertex3f_bufferobject, rsurface.vertex3f_bufferoffset);
10696 }
10697
10698 void RSurf_DrawBatch_Simple(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10699 {
10700         int i, j;
10701         const msurface_t *surface = texturesurfacelist[0];
10702         const msurface_t *surface2;
10703         int firstvertex;
10704         int endvertex;
10705         int numvertices;
10706         int numtriangles;
10707         // TODO: lock all array ranges before render, rather than on each surface
10708         if (texturenumsurfaces == 1)
10709                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10710         else if (r_batchmode.integer == 2)
10711         {
10712                 #define MAXBATCHTRIANGLES 65536
10713                 int batchtriangles = 0;
10714                 static int batchelements[MAXBATCHTRIANGLES*3];
10715                 for (i = 0;i < texturenumsurfaces;i = j)
10716                 {
10717                         surface = texturesurfacelist[i];
10718                         j = i + 1;
10719                         if (surface->num_triangles > MAXBATCHTRIANGLES)
10720                         {
10721                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10722                                 continue;
10723                         }
10724                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
10725                         batchtriangles = surface->num_triangles;
10726                         firstvertex = surface->num_firstvertex;
10727                         endvertex = surface->num_firstvertex + surface->num_vertices;
10728                         for (;j < texturenumsurfaces;j++)
10729                         {
10730                                 surface2 = texturesurfacelist[j];
10731                                 if (batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
10732                                         break;
10733                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
10734                                 batchtriangles += surface2->num_triangles;
10735                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
10736                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
10737                         }
10738                         surface2 = texturesurfacelist[j-1];
10739                         numvertices = endvertex - firstvertex;
10740                         R_Mesh_Draw(firstvertex, numvertices, 0, batchtriangles, batchelements, NULL, 0, 0);
10741                 }
10742         }
10743         else if (r_batchmode.integer == 1)
10744         {
10745                 for (i = 0;i < texturenumsurfaces;i = j)
10746                 {
10747                         surface = texturesurfacelist[i];
10748                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
10749                                 if (texturesurfacelist[j] != surface2)
10750                                         break;
10751                         surface2 = texturesurfacelist[j-1];
10752                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
10753                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
10754                         R_Mesh_Draw(surface->num_firstvertex, numvertices, surface->num_firsttriangle, numtriangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10755                 }
10756         }
10757         else
10758         {
10759                 for (i = 0;i < texturenumsurfaces;i++)
10760                 {
10761                         surface = texturesurfacelist[i];
10762                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10763                 }
10764         }
10765 }
10766
10767 static void RSurf_BindLightmapForSurface(const msurface_t *surface)
10768 {
10769         switch(vid.renderpath)
10770         {
10771         case RENDERPATH_CGGL:
10772 #ifdef SUPPORTCG
10773                 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , surface->lightmaptexture );CHECKCGERROR
10774                 if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, surface->deluxemaptexture);CHECKCGERROR
10775 #endif
10776                 break;
10777         case RENDERPATH_GL20:
10778                 if (r_glsl_permutation->loc_Texture_Lightmap  >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , surface->lightmaptexture );
10779                 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, surface->deluxemaptexture);
10780                 break;
10781         case RENDERPATH_GL13:
10782         case RENDERPATH_GL11:
10783                 R_Mesh_TexBind(0, surface->lightmaptexture);
10784                 break;
10785         }
10786 }
10787
10788 static void RSurf_BindReflectionForSurface(const msurface_t *surface)
10789 {
10790         // pick the closest matching water plane and bind textures
10791         int planeindex, vertexindex;
10792         float d, bestd;
10793         vec3_t vert;
10794         const float *v;
10795         r_waterstate_waterplane_t *p, *bestp;
10796         bestd = 0;
10797         bestp = NULL;
10798         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
10799         {
10800                 if(p->camera_entity != rsurface.texture->camera_entity)
10801                         continue;
10802                 d = 0;
10803                 for (vertexindex = 0, v = rsurface.modelvertex3f + surface->num_firstvertex * 3;vertexindex < surface->num_vertices;vertexindex++, v += 3)
10804                 {
10805                         Matrix4x4_Transform(&rsurface.matrix, v, vert);
10806                         d += fabs(PlaneDiff(vert, &p->plane));
10807                 }
10808                 if (bestd > d || !bestp)
10809                 {
10810                         bestd = d;
10811                         bestp = p;
10812                 }
10813         }
10814         switch(vid.renderpath)
10815         {
10816         case RENDERPATH_CGGL:
10817 #ifdef SUPPORTCG
10818                 if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
10819                 else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
10820                 if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
10821 #endif
10822                 break;
10823         case RENDERPATH_GL20:
10824                 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
10825                 else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
10826                 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
10827                 break;
10828         case RENDERPATH_GL13:
10829         case RENDERPATH_GL11:
10830                 break;
10831         }
10832 }
10833
10834 static void RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10835 {
10836         int i;
10837         const msurface_t *surface;
10838         if (r_waterstate.renderingscene)
10839                 return;
10840         for (i = 0;i < texturenumsurfaces;i++)
10841         {
10842                 surface = texturesurfacelist[i];
10843                 RSurf_BindLightmapForSurface(surface);
10844                 RSurf_BindReflectionForSurface(surface);
10845                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10846         }
10847 }
10848
10849 static void RSurf_DrawBatch_WithLightmapSwitching(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10850 {
10851         int i;
10852         int j;
10853         const msurface_t *surface = texturesurfacelist[0];
10854         const msurface_t *surface2;
10855         int firstvertex;
10856         int endvertex;
10857         int numvertices;
10858         int numtriangles;
10859         if (texturenumsurfaces == 1)
10860         {
10861                 RSurf_BindLightmapForSurface(surface);
10862                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10863         }
10864         else if (r_batchmode.integer == 2)
10865         {
10866                 int batchtriangles = 0;
10867                 static int batchelements[MAXBATCHTRIANGLES*3];
10868                 for (i = 0;i < texturenumsurfaces;i = j)
10869                 {
10870                         surface = texturesurfacelist[i];
10871                         RSurf_BindLightmapForSurface(surface);
10872                         j = i + 1;
10873                         if (surface->num_triangles > MAXBATCHTRIANGLES)
10874                         {
10875                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10876                                 continue;
10877                         }
10878                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
10879                         batchtriangles = surface->num_triangles;
10880                         firstvertex = surface->num_firstvertex;
10881                         endvertex = surface->num_firstvertex + surface->num_vertices;
10882                         for (;j < texturenumsurfaces;j++)
10883                         {
10884                                 surface2 = texturesurfacelist[j];
10885                                 if (surface2->lightmaptexture != surface->lightmaptexture || batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
10886                                         break;
10887                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
10888                                 batchtriangles += surface2->num_triangles;
10889                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
10890                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
10891                         }
10892                         surface2 = texturesurfacelist[j-1];
10893                         numvertices = endvertex - firstvertex;
10894                         R_Mesh_Draw(firstvertex, numvertices, 0, batchtriangles, batchelements, NULL, 0, 0);
10895                 }
10896         }
10897         else if (r_batchmode.integer == 1)
10898         {
10899 #if 0
10900                 Con_Printf("%s batch sizes ignoring lightmap:", rsurface.texture->name);
10901                 for (i = 0;i < texturenumsurfaces;i = j)
10902                 {
10903                         surface = texturesurfacelist[i];
10904                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
10905                                 if (texturesurfacelist[j] != surface2)
10906                                         break;
10907                         Con_Printf(" %i", j - i);
10908                 }
10909                 Con_Printf("\n");
10910                 Con_Printf("%s batch sizes honoring lightmap:", rsurface.texture->name);
10911 #endif
10912                 for (i = 0;i < texturenumsurfaces;i = j)
10913                 {
10914                         surface = texturesurfacelist[i];
10915                         RSurf_BindLightmapForSurface(surface);
10916                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
10917                                 if (texturesurfacelist[j] != surface2 || texturesurfacelist[j]->lightmaptexture != surface->lightmaptexture)
10918                                         break;
10919 #if 0
10920                         Con_Printf(" %i", j - i);
10921 #endif
10922                         surface2 = texturesurfacelist[j-1];
10923                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
10924                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
10925                         R_Mesh_Draw(surface->num_firstvertex, numvertices, surface->num_firsttriangle, numtriangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10926                 }
10927 #if 0
10928                 Con_Printf("\n");
10929 #endif
10930         }
10931         else
10932         {
10933                 for (i = 0;i < texturenumsurfaces;i++)
10934                 {
10935                         surface = texturesurfacelist[i];
10936                         RSurf_BindLightmapForSurface(surface);
10937                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10938                 }
10939         }
10940 }
10941
10942 static void RSurf_DrawBatch_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10943 {
10944         int j;
10945         int texturesurfaceindex;
10946         if (r_showsurfaces.integer == 2)
10947         {
10948                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10949                 {
10950                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10951                         for (j = 0;j < surface->num_triangles;j++)
10952                         {
10953                                 float f = ((j + surface->num_firsttriangle) & 31) * (1.0f / 31.0f) * r_refdef.view.colorscale;
10954                                 GL_Color(f, f, f, 1);
10955                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle + j, 1, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10956                         }
10957                 }
10958         }
10959         else
10960         {
10961                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10962                 {
10963                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10964                         int k = (int)(((size_t)surface) / sizeof(msurface_t));
10965                         GL_Color((k & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, ((k >> 4) & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, ((k >> 8) & 15) * (1.0f / 16.0f) * r_refdef.view.colorscale, 1);
10966                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10967                 }
10968         }
10969 }
10970
10971 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10972 {
10973         int texturesurfaceindex;
10974         int i;
10975         const float *v;
10976         float *c2;
10977         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10978         {
10979                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10980                 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)
10981                 {
10982                         c2[0] = 0.5;
10983                         c2[1] = 0.5;
10984                         c2[2] = 0.5;
10985                         c2[3] = 1;
10986                 }
10987         }
10988         rsurface.lightmapcolor4f = rsurface.array_color4f;
10989         rsurface.lightmapcolor4f_bufferobject = 0;
10990         rsurface.lightmapcolor4f_bufferoffset = 0;
10991 }
10992
10993 static void RSurf_DrawBatch_GL11_ApplyFog(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10994 {
10995         int texturesurfaceindex;
10996         int i;
10997         float f;
10998         const float *v;
10999         const float *c;
11000         float *c2;
11001         if (rsurface.lightmapcolor4f)
11002         {
11003                 // generate color arrays for the surfaces in this list
11004                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11005                 {
11006                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11007                         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)
11008                         {
11009                                 f = RSurf_FogVertex(v);
11010                                 c2[0] = c[0] * f;
11011                                 c2[1] = c[1] * f;
11012                                 c2[2] = c[2] * f;
11013                                 c2[3] = c[3];
11014                         }
11015                 }
11016         }
11017         else
11018         {
11019                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11020                 {
11021                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11022                         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)
11023                         {
11024                                 f = RSurf_FogVertex(v);
11025                                 c2[0] = f;
11026                                 c2[1] = f;
11027                                 c2[2] = f;
11028                                 c2[3] = 1;
11029                         }
11030                 }
11031         }
11032         rsurface.lightmapcolor4f = rsurface.array_color4f;
11033         rsurface.lightmapcolor4f_bufferobject = 0;
11034         rsurface.lightmapcolor4f_bufferoffset = 0;
11035 }
11036
11037 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11038 {
11039         int texturesurfaceindex;
11040         int i;
11041         float f;
11042         const float *v;
11043         const float *c;
11044         float *c2;
11045         if (!rsurface.lightmapcolor4f)
11046                 return;
11047         // generate color arrays for the surfaces in this list
11048         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11049         {
11050                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11051                 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)
11052                 {
11053                         f = RSurf_FogVertex(v);
11054                         c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11055                         c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11056                         c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11057                         c2[3] = c[3];
11058                 }
11059         }
11060         rsurface.lightmapcolor4f = rsurface.array_color4f;
11061         rsurface.lightmapcolor4f_bufferobject = 0;
11062         rsurface.lightmapcolor4f_bufferoffset = 0;
11063 }
11064
11065 static void RSurf_DrawBatch_GL11_ApplyColor(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a)
11066 {
11067         int texturesurfaceindex;
11068         int i;
11069         const float *c;
11070         float *c2;
11071         if (!rsurface.lightmapcolor4f)
11072                 return;
11073         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11074         {
11075                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11076                 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)
11077                 {
11078                         c2[0] = c[0] * r;
11079                         c2[1] = c[1] * g;
11080                         c2[2] = c[2] * b;
11081                         c2[3] = c[3] * a;
11082                 }
11083         }
11084         rsurface.lightmapcolor4f = rsurface.array_color4f;
11085         rsurface.lightmapcolor4f_bufferobject = 0;
11086         rsurface.lightmapcolor4f_bufferoffset = 0;
11087 }
11088
11089 static void RSurf_DrawBatch_GL11_ApplyAmbient(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11090 {
11091         int texturesurfaceindex;
11092         int i;
11093         const float *c;
11094         float *c2;
11095         if (!rsurface.lightmapcolor4f)
11096                 return;
11097         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11098         {
11099                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11100                 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)
11101                 {
11102                         c2[0] = c[0] + r_refdef.scene.ambient;
11103                         c2[1] = c[1] + r_refdef.scene.ambient;
11104                         c2[2] = c[2] + r_refdef.scene.ambient;
11105                         c2[3] = c[3];
11106                 }
11107         }
11108         rsurface.lightmapcolor4f = rsurface.array_color4f;
11109         rsurface.lightmapcolor4f_bufferobject = 0;
11110         rsurface.lightmapcolor4f_bufferoffset = 0;
11111 }
11112
11113 static void RSurf_DrawBatch_GL11_Lightmap(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11114 {
11115         // TODO: optimize
11116         rsurface.lightmapcolor4f = NULL;
11117         rsurface.lightmapcolor4f_bufferobject = 0;
11118         rsurface.lightmapcolor4f_bufferoffset = 0;
11119         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11120         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11121         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11122         GL_Color(r, g, b, a);
11123         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist);
11124 }
11125
11126 static void RSurf_DrawBatch_GL11_Unlit(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11127 {
11128         // TODO: optimize applyfog && applycolor case
11129         // just apply fog if necessary, and tint the fog color array if necessary
11130         rsurface.lightmapcolor4f = NULL;
11131         rsurface.lightmapcolor4f_bufferobject = 0;
11132         rsurface.lightmapcolor4f_bufferoffset = 0;
11133         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11134         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11135         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11136         GL_Color(r, g, b, a);
11137         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11138 }
11139
11140 static void RSurf_DrawBatch_GL11_VertexColor(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11141 {
11142         int texturesurfaceindex;
11143         int i;
11144         float *c;
11145         // TODO: optimize
11146         if (texturesurfacelist[0]->lightmapinfo)
11147         {
11148                 // generate color arrays for the surfaces in this list
11149                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11150                 {
11151                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11152                         for (i = 0, c = rsurface.array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
11153                         {
11154                                 if (surface->lightmapinfo->samples)
11155                                 {
11156                                         const unsigned char *lm = surface->lightmapinfo->samples + (rsurface.modellightmapoffsets + surface->num_firstvertex)[i];
11157                                         float scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]] * (1.0f / 32768.0f);
11158                                         VectorScale(lm, scale, c);
11159                                         if (surface->lightmapinfo->styles[1] != 255)
11160                                         {
11161                                                 int size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11162                                                 lm += size3;
11163                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]] * (1.0f / 32768.0f);
11164                                                 VectorMA(c, scale, lm, c);
11165                                                 if (surface->lightmapinfo->styles[2] != 255)
11166                                                 {
11167                                                         lm += size3;
11168                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]] * (1.0f / 32768.0f);
11169                                                         VectorMA(c, scale, lm, c);
11170                                                         if (surface->lightmapinfo->styles[3] != 255)
11171                                                         {
11172                                                                 lm += size3;
11173                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]] * (1.0f / 32768.0f);
11174                                                                 VectorMA(c, scale, lm, c);
11175                                                         }
11176                                                 }
11177                                         }
11178                                 }
11179                                 else
11180                                         VectorClear(c);
11181                                 c[3] = 1;
11182                         }
11183                 }
11184                 rsurface.lightmapcolor4f = rsurface.array_color4f;
11185                 rsurface.lightmapcolor4f_bufferobject = 0;
11186                 rsurface.lightmapcolor4f_bufferoffset = 0;
11187         }
11188         else
11189         {
11190                 rsurface.lightmapcolor4f = rsurface.modellightmapcolor4f;
11191                 rsurface.lightmapcolor4f_bufferobject = rsurface.modellightmapcolor4f_bufferobject;
11192                 rsurface.lightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11193         }
11194         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11195         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11196         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11197         GL_Color(r, g, b, a);
11198         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11199 }
11200
11201 static void RSurf_DrawBatch_GL11_ApplyFakeLight(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11202 {
11203         int texturesurfaceindex;
11204         int i;
11205         float f;
11206         const float *v;
11207         const float *n;
11208         float *c;
11209         //vec3_t eyedir;
11210
11211         // fake shading
11212         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11213         {
11214                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11215                 int numverts = surface->num_vertices;
11216                 v = rsurface.vertex3f + 3 * surface->num_firstvertex;
11217                 n = rsurface.normal3f + 3 * surface->num_firstvertex;
11218                 c = rsurface.array_color4f + 4 * surface->num_firstvertex;
11219                 for (i = 0;i < numverts;i++, v += 3, n += 3, c += 4)
11220                 {
11221                         f = -DotProduct(r_refdef.view.forward, n);
11222                         f = max(0, f);
11223                         f = f * 0.85 + 0.15; // work around so stuff won't get black
11224                         f *= r_refdef.lightmapintensity;
11225                         Vector4Set(c, f, f, f, 1);
11226                 }
11227         }
11228
11229         rsurface.lightmapcolor4f = rsurface.array_color4f;
11230         rsurface.lightmapcolor4f_bufferobject = 0;
11231         rsurface.lightmapcolor4f_bufferoffset = 0;
11232 }
11233
11234 static void RSurf_DrawBatch_GL11_FakeLight(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11235 {
11236         RSurf_DrawBatch_GL11_ApplyFakeLight(texturenumsurfaces, texturesurfacelist);
11237         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11238         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11239         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11240         GL_Color(r, g, b, a);
11241         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11242 }
11243
11244 static void RSurf_DrawBatch_GL11_ApplyVertexShade(int texturenumsurfaces, const msurface_t **texturesurfacelist, float *r, float *g, float *b, float *a, qboolean *applycolor)
11245 {
11246         int texturesurfaceindex;
11247         int i;
11248         float f;
11249         float alpha;
11250         const float *v;
11251         const float *n;
11252         float *c;
11253         vec3_t ambientcolor;
11254         vec3_t diffusecolor;
11255         vec3_t lightdir;
11256         // TODO: optimize
11257         // model lighting
11258         VectorCopy(rsurface.modellight_lightdir, lightdir);
11259         f = 0.5f * r_refdef.lightmapintensity;
11260         ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11261         ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11262         ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11263         diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11264         diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11265         diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11266         alpha = *a;
11267         if (VectorLength2(diffusecolor) > 0 && rsurface.normal3f)
11268         {
11269                 // generate color arrays for the surfaces in this list
11270                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11271                 {
11272                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11273                         int numverts = surface->num_vertices;
11274                         v = rsurface.vertex3f + 3 * surface->num_firstvertex;
11275                         n = rsurface.normal3f + 3 * surface->num_firstvertex;
11276                         c = rsurface.array_color4f + 4 * surface->num_firstvertex;
11277                         // q3-style directional shading
11278                         for (i = 0;i < numverts;i++, v += 3, n += 3, c += 4)
11279                         {
11280                                 if ((f = DotProduct(n, lightdir)) > 0)
11281                                         VectorMA(ambientcolor, f, diffusecolor, c);
11282                                 else
11283                                         VectorCopy(ambientcolor, c);
11284                                 c[3] = alpha;
11285                         }
11286                 }
11287                 *r = 1;
11288                 *g = 1;
11289                 *b = 1;
11290                 *a = 1;
11291                 rsurface.lightmapcolor4f = rsurface.array_color4f;
11292                 rsurface.lightmapcolor4f_bufferobject = 0;
11293                 rsurface.lightmapcolor4f_bufferoffset = 0;
11294                 *applycolor = false;
11295         }
11296         else
11297         {
11298                 *r = ambientcolor[0];
11299                 *g = ambientcolor[1];
11300                 *b = ambientcolor[2];
11301                 rsurface.lightmapcolor4f = NULL;
11302                 rsurface.lightmapcolor4f_bufferobject = 0;
11303                 rsurface.lightmapcolor4f_bufferoffset = 0;
11304         }
11305 }
11306
11307 static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11308 {
11309         RSurf_DrawBatch_GL11_ApplyVertexShade(texturenumsurfaces, texturesurfacelist, &r, &g, &b, &a, &applycolor);
11310         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11311         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11312         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11313         GL_Color(r, g, b, a);
11314         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11315 }
11316
11317 void RSurf_SetupDepthAndCulling(void)
11318 {
11319         // submodels are biased to avoid z-fighting with world surfaces that they
11320         // may be exactly overlapping (avoids z-fighting artifacts on certain
11321         // doors and things in Quake maps)
11322         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
11323         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
11324         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
11325         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11326 }
11327
11328 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11329 {
11330         // transparent sky would be ridiculous
11331         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11332                 return;
11333         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11334         skyrenderlater = true;
11335         RSurf_SetupDepthAndCulling();
11336         GL_DepthMask(true);
11337         // LordHavoc: HalfLife maps have freaky skypolys so don't use
11338         // skymasking on them, and Quake3 never did sky masking (unlike
11339         // software Quake and software Quake2), so disable the sky masking
11340         // in Quake3 maps as it causes problems with q3map2 sky tricks,
11341         // and skymasking also looks very bad when noclipping outside the
11342         // level, so don't use it then either.
11343         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
11344         {
11345                 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
11346                 R_Mesh_ColorPointer(NULL, 0, 0);
11347                 R_Mesh_ResetTextureState();
11348                 if (skyrendermasked)
11349                 {
11350                         R_SetupShader_DepthOrShadow();
11351                         // depth-only (masking)
11352                         GL_ColorMask(0,0,0,0);
11353                         // just to make sure that braindead drivers don't draw
11354                         // anything despite that colormask...
11355                         GL_BlendFunc(GL_ZERO, GL_ONE);
11356                 }
11357                 else
11358                 {
11359                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11360                         // fog sky
11361                         GL_BlendFunc(GL_ONE, GL_ZERO);
11362                 }
11363                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11364                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11365                 if (skyrendermasked)
11366                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11367         }
11368         R_Mesh_ResetTextureState();
11369         GL_Color(1, 1, 1, 1);
11370 }
11371
11372 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
11373 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
11374 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11375 {
11376         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
11377                 return;
11378         RSurf_PrepareVerticesForBatch(true, true, texturenumsurfaces, texturesurfacelist);
11379         if (prepass)
11380         {
11381                 // render screenspace normalmap to texture
11382                 GL_DepthMask(true);
11383                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY);
11384                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11385         }
11386         else if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
11387         {
11388                 // render water or distortion background, then blend surface on top
11389                 GL_DepthMask(true);
11390                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND);
11391                 RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist);
11392                 GL_DepthMask(false);
11393                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
11394                 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11395                         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist);
11396                 else
11397                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11398         }
11399         else
11400         {
11401                 // render surface normally
11402                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11403                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
11404                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
11405                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist);
11406                 else if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11407                         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist);
11408                 else
11409                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11410         }
11411 }
11412
11413 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11414 {
11415         // OpenGL 1.3 path - anything not completely ancient
11416         int texturesurfaceindex;
11417         qboolean applycolor;
11418         qboolean applyfog;
11419         int layerindex;
11420         const texturelayer_t *layer;
11421         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11422
11423         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11424         {
11425                 vec4_t layercolor;
11426                 int layertexrgbscale;
11427                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11428                 {
11429                         if (layerindex == 0)
11430                                 GL_AlphaTest(true);
11431                         else
11432                         {
11433                                 GL_AlphaTest(false);
11434                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11435                         }
11436                 }
11437                 GL_DepthMask(layer->depthmask && writedepth);
11438                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11439                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
11440                 {
11441                         layertexrgbscale = 4;
11442                         VectorScale(layer->color, 0.25f, layercolor);
11443                 }
11444                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
11445                 {
11446                         layertexrgbscale = 2;
11447                         VectorScale(layer->color, 0.5f, layercolor);
11448                 }
11449                 else
11450                 {
11451                         layertexrgbscale = 1;
11452                         VectorScale(layer->color, 1.0f, layercolor);
11453                 }
11454                 layercolor[3] = layer->color[3];
11455                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
11456                 R_Mesh_ColorPointer(NULL, 0, 0);
11457                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11458                 switch (layer->type)
11459                 {
11460                 case TEXTURELAYERTYPE_LITTEXTURE:
11461                         // single-pass lightmapped texture with 2x rgbscale
11462                         R_Mesh_TexBind(0, r_texture_white);
11463                         R_Mesh_TexMatrix(0, NULL);
11464                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11465                         R_Mesh_TexCoordPointer(0, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
11466                         R_Mesh_TexBind(1, layer->texture);
11467                         R_Mesh_TexMatrix(1, &layer->texmatrix);
11468                         R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11469                         R_Mesh_TexCoordPointer(1, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11470                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11471                                 RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11472                         else if (FAKELIGHT_ENABLED)
11473                                 RSurf_DrawBatch_GL11_FakeLight(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11474                         else if (rsurface.uselightmaptexture)
11475                                 RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11476                         else
11477                                 RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11478                         break;
11479                 case TEXTURELAYERTYPE_TEXTURE:
11480                         // singletexture unlit texture with transparency support
11481                         R_Mesh_TexBind(0, layer->texture);
11482                         R_Mesh_TexMatrix(0, &layer->texmatrix);
11483                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11484                         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11485                         R_Mesh_TexBind(1, 0);
11486                         R_Mesh_TexCoordPointer(1, 2, NULL, 0, 0);
11487                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11488                         break;
11489                 case TEXTURELAYERTYPE_FOG:
11490                         // singletexture fogging
11491                         if (layer->texture)
11492                         {
11493                                 R_Mesh_TexBind(0, layer->texture);
11494                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11495                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11496                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11497                         }
11498                         else
11499                         {
11500                                 R_Mesh_TexBind(0, 0);
11501                                 R_Mesh_TexCoordPointer(0, 2, NULL, 0, 0);
11502                         }
11503                         R_Mesh_TexBind(1, 0);
11504                         R_Mesh_TexCoordPointer(1, 2, NULL, 0, 0);
11505                         // generate a color array for the fog pass
11506                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
11507                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11508                         {
11509                                 int i;
11510                                 float f;
11511                                 const float *v;
11512                                 float *c;
11513                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11514                                 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)
11515                                 {
11516                                         f = 1 - RSurf_FogVertex(v);
11517                                         c[0] = layercolor[0];
11518                                         c[1] = layercolor[1];
11519                                         c[2] = layercolor[2];
11520                                         c[3] = f * layercolor[3];
11521                                 }
11522                         }
11523                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11524                         break;
11525                 default:
11526                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11527                 }
11528         }
11529         CHECKGLERROR
11530         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11531         {
11532                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11533                 GL_AlphaTest(false);
11534         }
11535 }
11536
11537 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11538 {
11539         // OpenGL 1.1 - crusty old voodoo path
11540         int texturesurfaceindex;
11541         qboolean applyfog;
11542         int layerindex;
11543         const texturelayer_t *layer;
11544         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11545
11546         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11547         {
11548                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11549                 {
11550                         if (layerindex == 0)
11551                                 GL_AlphaTest(true);
11552                         else
11553                         {
11554                                 GL_AlphaTest(false);
11555                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11556                         }
11557                 }
11558                 GL_DepthMask(layer->depthmask && writedepth);
11559                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11560                 R_Mesh_ColorPointer(NULL, 0, 0);
11561                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11562                 switch (layer->type)
11563                 {
11564                 case TEXTURELAYERTYPE_LITTEXTURE:
11565                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
11566                         {
11567                                 // two-pass lit texture with 2x rgbscale
11568                                 // first the lightmap pass
11569                                 R_Mesh_TexBind(0, r_texture_white);
11570                                 R_Mesh_TexMatrix(0, NULL);
11571                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11572                                 R_Mesh_TexCoordPointer(0, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
11573                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11574                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11575                                 else if (FAKELIGHT_ENABLED)
11576                                         RSurf_DrawBatch_GL11_FakeLight(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11577                                 else if (rsurface.uselightmaptexture)
11578                                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11579                                 else
11580                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11581                                 // then apply the texture to it
11582                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
11583                                 R_Mesh_TexBind(0, layer->texture);
11584                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11585                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11586                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11587                                 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);
11588                         }
11589                         else
11590                         {
11591                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
11592                                 R_Mesh_TexBind(0, layer->texture);
11593                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11594                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11595                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11596                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11597                                         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);
11598                                 else
11599                                         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);
11600                         }
11601                         break;
11602                 case TEXTURELAYERTYPE_TEXTURE:
11603                         // singletexture unlit texture with transparency support
11604                         R_Mesh_TexBind(0, layer->texture);
11605                         R_Mesh_TexMatrix(0, &layer->texmatrix);
11606                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11607                         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11608                         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);
11609                         break;
11610                 case TEXTURELAYERTYPE_FOG:
11611                         // singletexture fogging
11612                         if (layer->texture)
11613                         {
11614                                 R_Mesh_TexBind(0, layer->texture);
11615                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11616                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11617                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11618                         }
11619                         else
11620                         {
11621                                 R_Mesh_TexBind(0, 0);
11622                                 R_Mesh_TexCoordPointer(0, 2, NULL, 0, 0);
11623                         }
11624                         // generate a color array for the fog pass
11625                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
11626                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11627                         {
11628                                 int i;
11629                                 float f;
11630                                 const float *v;
11631                                 float *c;
11632                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11633                                 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)
11634                                 {
11635                                         f = 1 - RSurf_FogVertex(v);
11636                                         c[0] = layer->color[0];
11637                                         c[1] = layer->color[1];
11638                                         c[2] = layer->color[2];
11639                                         c[3] = f * layer->color[3];
11640                                 }
11641                         }
11642                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11643                         break;
11644                 default:
11645                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11646                 }
11647         }
11648         CHECKGLERROR
11649         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11650         {
11651                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11652                 GL_AlphaTest(false);
11653         }
11654 }
11655
11656 static void R_DrawTextureSurfaceList_ShowSurfaces3(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11657 {
11658         float c[4];
11659
11660         GL_AlphaTest(false);
11661         R_Mesh_ColorPointer(NULL, 0, 0);
11662         R_Mesh_ResetTextureState();
11663         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11664
11665         if(rsurface.texture && rsurface.texture->currentskinframe)
11666         {
11667                 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
11668                 c[3] *= rsurface.texture->currentalpha;
11669         }
11670         else
11671         {
11672                 c[0] = 1;
11673                 c[1] = 0;
11674                 c[2] = 1;
11675                 c[3] = 1;
11676         }
11677
11678         if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
11679         {
11680                 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
11681                 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
11682                 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
11683         }
11684
11685         // brighten it up (as texture value 127 means "unlit")
11686         c[0] *= 2 * r_refdef.view.colorscale;
11687         c[1] *= 2 * r_refdef.view.colorscale;
11688         c[2] *= 2 * r_refdef.view.colorscale;
11689
11690         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
11691                 c[3] *= r_wateralpha.value;
11692
11693         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
11694         {
11695                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11696                 GL_DepthMask(false);
11697         }
11698         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
11699         {
11700                 GL_BlendFunc(GL_ONE, GL_ONE);
11701                 GL_DepthMask(false);
11702         }
11703         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11704         {
11705                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
11706                 GL_DepthMask(false);
11707         }
11708         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
11709         {
11710                 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
11711                 GL_DepthMask(false);
11712         }
11713         else
11714         {
11715                 GL_BlendFunc(GL_ONE, GL_ZERO);
11716                 GL_DepthMask(writedepth);
11717         }
11718
11719         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
11720         {
11721                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11722
11723                 rsurface.lightmapcolor4f = NULL;
11724                 rsurface.lightmapcolor4f_bufferobject = 0;
11725                 rsurface.lightmapcolor4f_bufferoffset = 0;
11726         }
11727         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11728         {
11729                 qboolean applycolor = true;
11730                 float one = 1.0;
11731
11732                 RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11733
11734                 r_refdef.lightmapintensity = 1;
11735                 RSurf_DrawBatch_GL11_ApplyVertexShade(texturenumsurfaces, texturesurfacelist, &one, &one, &one, &one, &applycolor);
11736                 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11737         }
11738         else if (FAKELIGHT_ENABLED)
11739         {
11740                 RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11741
11742                 r_refdef.lightmapintensity = r_fakelight_intensity.value;
11743                 RSurf_DrawBatch_GL11_ApplyFakeLight(texturenumsurfaces, texturesurfacelist);
11744                 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11745         }
11746         else
11747         {
11748                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11749
11750                 rsurface.lightmapcolor4f = rsurface.modellightmapcolor4f;
11751                 rsurface.lightmapcolor4f_bufferobject = rsurface.modellightmapcolor4f_bufferobject;
11752                 rsurface.lightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11753         }
11754
11755         if(!rsurface.lightmapcolor4f)
11756                 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(texturenumsurfaces, texturesurfacelist);
11757
11758         RSurf_DrawBatch_GL11_ApplyAmbient(texturenumsurfaces, texturesurfacelist);
11759         RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, c[0], c[1], c[2], c[3]);
11760         if(r_refdef.fogenabled)
11761                 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(texturenumsurfaces, texturesurfacelist);
11762
11763         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11764         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11765 }
11766
11767 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11768 {
11769         CHECKGLERROR
11770         RSurf_SetupDepthAndCulling();
11771         if (r_showsurfaces.integer == 3 && !prepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY))
11772         {
11773                 R_DrawTextureSurfaceList_ShowSurfaces3(texturenumsurfaces, texturesurfacelist, writedepth);
11774                 return;
11775         }
11776         switch (vid.renderpath)
11777         {
11778         case RENDERPATH_GL20:
11779         case RENDERPATH_CGGL:
11780                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11781                 break;
11782         case RENDERPATH_GL13:
11783                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11784                 break;
11785         case RENDERPATH_GL11:
11786                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11787                 break;
11788         }
11789         CHECKGLERROR
11790 }
11791
11792 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11793 {
11794         CHECKGLERROR
11795         RSurf_SetupDepthAndCulling();
11796         if (r_showsurfaces.integer == 3 && !prepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY))
11797         {
11798                 R_DrawTextureSurfaceList_ShowSurfaces3(texturenumsurfaces, texturesurfacelist, writedepth);
11799                 return;
11800         }
11801         switch (vid.renderpath)
11802         {
11803         case RENDERPATH_GL20:
11804         case RENDERPATH_CGGL:
11805                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11806                 break;
11807         case RENDERPATH_GL13:
11808                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11809                 break;
11810         case RENDERPATH_GL11:
11811                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11812                 break;
11813         }
11814         CHECKGLERROR
11815 }
11816
11817 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
11818 {
11819         int i, j;
11820         int texturenumsurfaces, endsurface;
11821         texture_t *texture;
11822         const msurface_t *surface;
11823 #define MAXBATCH_TRANSPARENTSURFACES 256
11824         const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
11825
11826         // if the model is static it doesn't matter what value we give for
11827         // wantnormals and wanttangents, so this logic uses only rules applicable
11828         // to a model, knowing that they are meaningless otherwise
11829         if (ent == r_refdef.scene.worldentity)
11830                 RSurf_ActiveWorldEntity();
11831         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11832                 RSurf_ActiveModelEntity(ent, false, false, false);
11833         else
11834         {
11835                 switch (vid.renderpath)
11836                 {
11837                 case RENDERPATH_GL20:
11838                 case RENDERPATH_CGGL:
11839                         RSurf_ActiveModelEntity(ent, true, true, false);
11840                         break;
11841                 case RENDERPATH_GL13:
11842                 case RENDERPATH_GL11:
11843                         RSurf_ActiveModelEntity(ent, true, false, false);
11844                         break;
11845                 }
11846         }
11847
11848         if (r_transparentdepthmasking.integer)
11849         {
11850                 qboolean setup = false;
11851                 for (i = 0;i < numsurfaces;i = j)
11852                 {
11853                         j = i + 1;
11854                         surface = rsurface.modelsurfaces + surfacelist[i];
11855                         texture = surface->texture;
11856                         rsurface.texture = R_GetCurrentTexture(texture);
11857                         // scan ahead until we find a different texture
11858                         endsurface = min(i + 1024, numsurfaces);
11859                         texturenumsurfaces = 0;
11860                         texturesurfacelist[texturenumsurfaces++] = surface;
11861                         if(FAKELIGHT_ENABLED)
11862                         {
11863                                 rsurface.uselightmaptexture = false;
11864                                 for (;j < endsurface;j++)
11865                                 {
11866                                         surface = rsurface.modelsurfaces + surfacelist[j];
11867                                         if (texture != surface->texture)
11868                                                 break;
11869                                         texturesurfacelist[texturenumsurfaces++] = surface;
11870                                 }
11871                         }
11872                         else
11873                         {
11874                                 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11875                                 for (;j < endsurface;j++)
11876                                 {
11877                                         surface = rsurface.modelsurfaces + surfacelist[j];
11878                                         if (texture != surface->texture || rsurface.uselightmaptexture != (surface->lightmaptexture != NULL))
11879                                                 break;
11880                                         texturesurfacelist[texturenumsurfaces++] = surface;
11881                                 }
11882                         }
11883                         if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
11884                                 continue;
11885                         // render the range of surfaces as depth
11886                         if (!setup)
11887                         {
11888                                 setup = true;
11889                                 GL_ColorMask(0,0,0,0);
11890                                 GL_Color(1,1,1,1);
11891                                 GL_DepthTest(true);
11892                                 GL_BlendFunc(GL_ONE, GL_ZERO);
11893                                 GL_DepthMask(true);
11894                                 GL_AlphaTest(false);
11895                                 R_Mesh_ColorPointer(NULL, 0, 0);
11896                                 R_Mesh_ResetTextureState();
11897                                 R_SetupShader_DepthOrShadow();
11898                         }
11899                         RSurf_SetupDepthAndCulling();
11900                         RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11901                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11902                 }
11903                 if (setup)
11904                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11905         }
11906
11907         for (i = 0;i < numsurfaces;i = j)
11908         {
11909                 j = i + 1;
11910                 surface = rsurface.modelsurfaces + surfacelist[i];
11911                 texture = surface->texture;
11912                 rsurface.texture = R_GetCurrentTexture(texture);
11913                 // scan ahead until we find a different texture
11914                 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
11915                 texturenumsurfaces = 0;
11916                 texturesurfacelist[texturenumsurfaces++] = surface;
11917                 if(FAKELIGHT_ENABLED)
11918                 {
11919                         rsurface.uselightmaptexture = false;
11920                         for (;j < endsurface;j++)
11921                         {
11922                                 surface = rsurface.modelsurfaces + surfacelist[j];
11923                                 if (texture != surface->texture)
11924                                         break;
11925                                 texturesurfacelist[texturenumsurfaces++] = surface;
11926                         }
11927                 }
11928                 else
11929                 {
11930                         rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11931                         for (;j < endsurface;j++)
11932                         {
11933                                 surface = rsurface.modelsurfaces + surfacelist[j];
11934                                 if (texture != surface->texture || rsurface.uselightmaptexture != (surface->lightmaptexture != NULL))
11935                                         break;
11936                                 texturesurfacelist[texturenumsurfaces++] = surface;
11937                         }
11938                 }
11939                 // render the range of surfaces
11940                 if (ent == r_refdef.scene.worldentity)
11941                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11942                 else
11943                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11944         }
11945         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11946         GL_AlphaTest(false);
11947 }
11948
11949 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
11950 {
11951         // transparent surfaces get pushed off into the transparent queue
11952         int surfacelistindex;
11953         const msurface_t *surface;
11954         vec3_t tempcenter, center;
11955         for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
11956         {
11957                 surface = texturesurfacelist[surfacelistindex];
11958                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
11959                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
11960                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
11961                 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
11962                 if (queueentity->transparent_offset) // transparent offset
11963                 {
11964                         center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
11965                         center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
11966                         center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
11967                 }
11968                 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
11969         }
11970 }
11971
11972 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
11973 {
11974         const entity_render_t *queueentity = r_refdef.scene.worldentity;
11975         CHECKGLERROR
11976         if (depthonly)
11977         {
11978                 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
11979                         return;
11980                 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
11981                         return;
11982                 RSurf_SetupDepthAndCulling();
11983                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11984                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11985         }
11986         else if (prepass)
11987         {
11988                 if (!rsurface.texture->currentnumlayers)
11989                         return;
11990                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11991                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11992                 else
11993                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11994         }
11995         else if (r_showsurfaces.integer && !r_refdef.view.showdebug && !prepass)
11996         {
11997                 RSurf_SetupDepthAndCulling();
11998                 GL_AlphaTest(false);
11999                 R_Mesh_ColorPointer(NULL, 0, 0);
12000                 R_Mesh_ResetTextureState();
12001                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12002                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12003                 GL_DepthMask(true);
12004                 GL_BlendFunc(GL_ONE, GL_ZERO);
12005                 GL_Color(0, 0, 0, 1);
12006                 GL_DepthTest(writedepth);
12007                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
12008         }
12009         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3 && !prepass)
12010         {
12011                 RSurf_SetupDepthAndCulling();
12012                 GL_AlphaTest(false);
12013                 R_Mesh_ColorPointer(NULL, 0, 0);
12014                 R_Mesh_ResetTextureState();
12015                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12016                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12017                 GL_DepthMask(true);
12018                 GL_BlendFunc(GL_ONE, GL_ZERO);
12019                 GL_DepthTest(true);
12020                 RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
12021         }
12022         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
12023                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12024         else if (!rsurface.texture->currentnumlayers)
12025                 return;
12026         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12027         {
12028                 // in the deferred case, transparent surfaces were queued during prepass
12029                 if (!r_shadow_usingdeferredprepass)
12030                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12031         }
12032         else
12033         {
12034                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12035                 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12036         }
12037         CHECKGLERROR
12038 }
12039
12040 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12041 {
12042         int i, j;
12043         texture_t *texture;
12044         // break the surface list down into batches by texture and use of lightmapping
12045         for (i = 0;i < numsurfaces;i = j)
12046         {
12047                 j = i + 1;
12048                 // texture is the base texture pointer, rsurface.texture is the
12049                 // current frame/skin the texture is directing us to use (for example
12050                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12051                 // use skin 1 instead)
12052                 texture = surfacelist[i]->texture;
12053                 rsurface.texture = R_GetCurrentTexture(texture);
12054                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12055                 {
12056                         // if this texture is not the kind we want, skip ahead to the next one
12057                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12058                                 ;
12059                         continue;
12060                 }
12061                 if(FAKELIGHT_ENABLED || depthonly || prepass)
12062                 {
12063                         rsurface.uselightmaptexture = false;
12064                         // simply scan ahead until we find a different texture or lightmap state
12065                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12066                                 ;
12067                 }
12068                 else
12069                 {
12070                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12071                         // simply scan ahead until we find a different texture or lightmap state
12072                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
12073                                 ;
12074                 }
12075                 // render the range of surfaces
12076                 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12077         }
12078 }
12079
12080 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12081 {
12082         CHECKGLERROR
12083         if (depthonly)
12084         {
12085                 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12086                         return;
12087                 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12088                         return;
12089                 RSurf_SetupDepthAndCulling();
12090                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12091                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
12092         }
12093         else if (prepass)
12094         {
12095                 if (!rsurface.texture->currentnumlayers)
12096                         return;
12097                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12098                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12099                 else
12100                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12101         }
12102         else if (r_showsurfaces.integer && !r_refdef.view.showdebug)
12103         {
12104                 RSurf_SetupDepthAndCulling();
12105                 GL_AlphaTest(false);
12106                 R_Mesh_ColorPointer(NULL, 0, 0);
12107                 R_Mesh_ResetTextureState();
12108                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12109                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12110                 GL_DepthMask(true);
12111                 GL_BlendFunc(GL_ONE, GL_ZERO);
12112                 GL_Color(0, 0, 0, 1);
12113                 GL_DepthTest(writedepth);
12114                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
12115         }
12116         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12117         {
12118                 RSurf_SetupDepthAndCulling();
12119                 GL_AlphaTest(false);
12120                 R_Mesh_ColorPointer(NULL, 0, 0);
12121                 R_Mesh_ResetTextureState();
12122                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12123                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12124                 GL_DepthMask(true);
12125                 GL_BlendFunc(GL_ONE, GL_ZERO);
12126                 GL_DepthTest(true);
12127                 RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
12128         }
12129         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
12130                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12131         else if (!rsurface.texture->currentnumlayers)
12132                 return;
12133         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12134         {
12135                 // in the deferred case, transparent surfaces were queued during prepass
12136                 if (!r_shadow_usingdeferredprepass)
12137                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12138         }
12139         else
12140         {
12141                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12142                 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12143         }
12144         CHECKGLERROR
12145 }
12146
12147 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12148 {
12149         int i, j;
12150         texture_t *texture;
12151         // break the surface list down into batches by texture and use of lightmapping
12152         for (i = 0;i < numsurfaces;i = j)
12153         {
12154                 j = i + 1;
12155                 // texture is the base texture pointer, rsurface.texture is the
12156                 // current frame/skin the texture is directing us to use (for example
12157                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12158                 // use skin 1 instead)
12159                 texture = surfacelist[i]->texture;
12160                 rsurface.texture = R_GetCurrentTexture(texture);
12161                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12162                 {
12163                         // if this texture is not the kind we want, skip ahead to the next one
12164                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12165                                 ;
12166                         continue;
12167                 }
12168                 if(FAKELIGHT_ENABLED || depthonly || prepass)
12169                 {
12170                         rsurface.uselightmaptexture = false;
12171                         // simply scan ahead until we find a different texture or lightmap state
12172                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12173                                 ;
12174                 }
12175                 else
12176                 {
12177                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12178                         // simply scan ahead until we find a different texture or lightmap state
12179                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
12180                                 ;
12181                 }
12182                 // render the range of surfaces
12183                 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12184         }
12185 }
12186
12187 float locboxvertex3f[6*4*3] =
12188 {
12189         1,0,1, 1,0,0, 1,1,0, 1,1,1,
12190         0,1,1, 0,1,0, 0,0,0, 0,0,1,
12191         1,1,1, 1,1,0, 0,1,0, 0,1,1,
12192         0,0,1, 0,0,0, 1,0,0, 1,0,1,
12193         0,0,1, 1,0,1, 1,1,1, 0,1,1,
12194         1,0,0, 0,0,0, 0,1,0, 1,1,0
12195 };
12196
12197 unsigned short locboxelements[6*2*3] =
12198 {
12199          0, 1, 2, 0, 2, 3,
12200          4, 5, 6, 4, 6, 7,
12201          8, 9,10, 8,10,11,
12202         12,13,14, 12,14,15,
12203         16,17,18, 16,18,19,
12204         20,21,22, 20,22,23
12205 };
12206
12207 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12208 {
12209         int i, j;
12210         cl_locnode_t *loc = (cl_locnode_t *)ent;
12211         vec3_t mins, size;
12212         float vertex3f[6*4*3];
12213         CHECKGLERROR
12214         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12215         GL_DepthMask(false);
12216         GL_DepthRange(0, 1);
12217         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12218         GL_DepthTest(true);
12219         GL_CullFace(GL_NONE);
12220         R_EntityMatrix(&identitymatrix);
12221
12222         R_Mesh_VertexPointer(vertex3f, 0, 0);
12223         R_Mesh_ColorPointer(NULL, 0, 0);
12224         R_Mesh_ResetTextureState();
12225         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12226
12227         i = surfacelist[0];
12228         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12229                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12230                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12231                         surfacelist[0] < 0 ? 0.5f : 0.125f);
12232
12233         if (VectorCompare(loc->mins, loc->maxs))
12234         {
12235                 VectorSet(size, 2, 2, 2);
12236                 VectorMA(loc->mins, -0.5f, size, mins);
12237         }
12238         else
12239         {
12240                 VectorCopy(loc->mins, mins);
12241                 VectorSubtract(loc->maxs, loc->mins, size);
12242         }
12243
12244         for (i = 0;i < 6*4*3;)
12245                 for (j = 0;j < 3;j++, i++)
12246                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12247
12248         R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, locboxelements, 0, 0);
12249 }
12250
12251 void R_DrawLocs(void)
12252 {
12253         int index;
12254         cl_locnode_t *loc, *nearestloc;
12255         vec3_t center;
12256         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12257         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12258         {
12259                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12260                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12261         }
12262 }
12263
12264 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12265 {
12266         if (decalsystem->decals)
12267                 Mem_Free(decalsystem->decals);
12268         memset(decalsystem, 0, sizeof(*decalsystem));
12269 }
12270
12271 static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, int decalsequence)
12272 {
12273         tridecal_t *decal;
12274         tridecal_t *decals;
12275         int i;
12276
12277         // expand or initialize the system
12278         if (decalsystem->maxdecals <= decalsystem->numdecals)
12279         {
12280                 decalsystem_t old = *decalsystem;
12281                 qboolean useshortelements;
12282                 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12283                 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12284                 decalsystem->decals = Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
12285                 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12286                 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12287                 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12288                 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12289                 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12290                 if (decalsystem->numdecals)
12291                         memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12292                 if (old.decals)
12293                         Mem_Free(old.decals);
12294                 for (i = 0;i < decalsystem->maxdecals*3;i++)
12295                         decalsystem->element3i[i] = i;
12296                 if (useshortelements)
12297                         for (i = 0;i < decalsystem->maxdecals*3;i++)
12298                                 decalsystem->element3s[i] = i;
12299         }
12300
12301         // grab a decal and search for another free slot for the next one
12302         decals = decalsystem->decals;
12303         decal = decalsystem->decals + (i = decalsystem->freedecal++);
12304         for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12305                 ;
12306         decalsystem->freedecal = i;
12307         if (decalsystem->numdecals <= i)
12308                 decalsystem->numdecals = i + 1;
12309
12310         // initialize the decal
12311         decal->lived = 0;
12312         decal->triangleindex = triangleindex;
12313         decal->surfaceindex = surfaceindex;
12314         decal->decalsequence = decalsequence;
12315         decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
12316         decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
12317         decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
12318         decal->color4ub[0][3] = 255;
12319         decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
12320         decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
12321         decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
12322         decal->color4ub[1][3] = 255;
12323         decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
12324         decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
12325         decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
12326         decal->color4ub[2][3] = 255;
12327         decal->vertex3f[0][0] = v0[0];
12328         decal->vertex3f[0][1] = v0[1];
12329         decal->vertex3f[0][2] = v0[2];
12330         decal->vertex3f[1][0] = v1[0];
12331         decal->vertex3f[1][1] = v1[1];
12332         decal->vertex3f[1][2] = v1[2];
12333         decal->vertex3f[2][0] = v2[0];
12334         decal->vertex3f[2][1] = v2[1];
12335         decal->vertex3f[2][2] = v2[2];
12336         decal->texcoord2f[0][0] = t0[0];
12337         decal->texcoord2f[0][1] = t0[1];
12338         decal->texcoord2f[1][0] = t1[0];
12339         decal->texcoord2f[1][1] = t1[1];
12340         decal->texcoord2f[2][0] = t2[0];
12341         decal->texcoord2f[2][1] = t2[1];
12342 }
12343
12344 extern cvar_t cl_decals_bias;
12345 extern cvar_t cl_decals_models;
12346 extern cvar_t cl_decals_newsystem_intensitymultiplier;
12347 // baseparms, parms, temps
12348 static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
12349 {
12350         int cornerindex;
12351         int index;
12352         float v[9][3];
12353         const float *vertex3f;
12354         int numpoints;
12355         float points[2][9][3];
12356         float temp[3];
12357         float tc[9][2];
12358         float f;
12359         float c[9][4];
12360         const int *e;
12361
12362         e = rsurface.modelelement3i + 3*triangleindex;
12363
12364         vertex3f = rsurface.modelvertex3f;
12365
12366         for (cornerindex = 0;cornerindex < 3;cornerindex++)
12367         {
12368                 index = 3*e[cornerindex];
12369                 VectorCopy(vertex3f + index, v[cornerindex]);
12370         }
12371         // cull backfaces
12372         //TriangleNormal(v[0], v[1], v[2], normal);
12373         //if (DotProduct(normal, localnormal) < 0.0f)
12374         //      continue;
12375         // clip by each of the box planes formed from the projection matrix
12376         // if anything survives, we emit the decal
12377         numpoints = PolygonF_Clip(3        , v[0]        , planes[0][0], planes[0][1], planes[0][2], planes[0][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
12378         if (numpoints < 3)
12379                 return;
12380         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[1][0], planes[1][1], planes[1][2], planes[1][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
12381         if (numpoints < 3)
12382                 return;
12383         numpoints = PolygonF_Clip(numpoints, points[0][0], planes[2][0], planes[2][1], planes[2][2], planes[2][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
12384         if (numpoints < 3)
12385                 return;
12386         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[3][0], planes[3][1], planes[3][2], planes[3][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
12387         if (numpoints < 3)
12388                 return;
12389         numpoints = PolygonF_Clip(numpoints, points[0][0], planes[4][0], planes[4][1], planes[4][2], planes[4][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
12390         if (numpoints < 3)
12391                 return;
12392         numpoints = PolygonF_Clip(numpoints, points[1][0], planes[5][0], planes[5][1], planes[5][2], planes[5][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), v[0]);
12393         if (numpoints < 3)
12394                 return;
12395         // some part of the triangle survived, so we have to accept it...
12396         if (dynamic)
12397         {
12398                 // dynamic always uses the original triangle
12399                 numpoints = 3;
12400                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12401                 {
12402                         index = 3*e[cornerindex];
12403                         VectorCopy(vertex3f + index, v[cornerindex]);
12404                 }
12405         }
12406         for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
12407         {
12408                 // convert vertex positions to texcoords
12409                 Matrix4x4_Transform(projection, v[cornerindex], temp);
12410                 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
12411                 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
12412                 // calculate distance fade from the projection origin
12413                 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
12414                 f = bound(0.0f, f, 1.0f);
12415                 c[cornerindex][0] = r * f;
12416                 c[cornerindex][1] = g * f;
12417                 c[cornerindex][2] = b * f;
12418                 c[cornerindex][3] = 1.0f;
12419                 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
12420         }
12421         if (dynamic)
12422                 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
12423         else
12424                 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
12425                         R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
12426 }
12427 static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
12428 {
12429         matrix4x4_t projection;
12430         decalsystem_t *decalsystem;
12431         qboolean dynamic;
12432         dp_model_t *model;
12433         const msurface_t *surface;
12434         const msurface_t *surfaces;
12435         const int *surfacelist;
12436         const texture_t *texture;
12437         int numtriangles;
12438         int numsurfacelist;
12439         int surfacelistindex;
12440         int surfaceindex;
12441         int triangleindex;
12442         float localorigin[3];
12443         float localnormal[3];
12444         float localmins[3];
12445         float localmaxs[3];
12446         float localsize;
12447         //float normal[3];
12448         float planes[6][4];
12449         float angles[3];
12450         bih_t *bih;
12451         int bih_triangles_count;
12452         int bih_triangles[256];
12453         int bih_surfaces[256];
12454
12455         decalsystem = &ent->decalsystem;
12456         model = ent->model;
12457         if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
12458         {
12459                 R_DecalSystem_Reset(&ent->decalsystem);
12460                 return;
12461         }
12462
12463         if (!model->brush.data_nodes && !cl_decals_models.integer)
12464         {
12465                 if (decalsystem->model)
12466                         R_DecalSystem_Reset(decalsystem);
12467                 return;
12468         }
12469
12470         if (decalsystem->model != model)
12471                 R_DecalSystem_Reset(decalsystem);
12472         decalsystem->model = model;
12473
12474         RSurf_ActiveModelEntity(ent, false, false, false);
12475
12476         Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
12477         Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
12478         VectorNormalize(localnormal);
12479         localsize = worldsize*rsurface.inversematrixscale;
12480         localmins[0] = localorigin[0] - localsize;
12481         localmins[1] = localorigin[1] - localsize;
12482         localmins[2] = localorigin[2] - localsize;
12483         localmaxs[0] = localorigin[0] + localsize;
12484         localmaxs[1] = localorigin[1] + localsize;
12485         localmaxs[2] = localorigin[2] + localsize;
12486
12487         //VectorCopy(localnormal, planes[4]);
12488         //VectorVectors(planes[4], planes[2], planes[0]);
12489         AnglesFromVectors(angles, localnormal, NULL, false);
12490         AngleVectors(angles, planes[0], planes[2], planes[4]);
12491         VectorNegate(planes[0], planes[1]);
12492         VectorNegate(planes[2], planes[3]);
12493         VectorNegate(planes[4], planes[5]);
12494         planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
12495         planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
12496         planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
12497         planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
12498         planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
12499         planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
12500
12501 #if 1
12502 // works
12503 {
12504         matrix4x4_t forwardprojection;
12505         Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
12506         Matrix4x4_Invert_Simple(&projection, &forwardprojection);
12507 }
12508 #else
12509 // broken
12510 {
12511         float projectionvector[4][3];
12512         VectorScale(planes[0], ilocalsize, projectionvector[0]);
12513         VectorScale(planes[2], ilocalsize, projectionvector[1]);
12514         VectorScale(planes[4], ilocalsize, projectionvector[2]);
12515         projectionvector[0][0] = planes[0][0] * ilocalsize;
12516         projectionvector[0][1] = planes[1][0] * ilocalsize;
12517         projectionvector[0][2] = planes[2][0] * ilocalsize;
12518         projectionvector[1][0] = planes[0][1] * ilocalsize;
12519         projectionvector[1][1] = planes[1][1] * ilocalsize;
12520         projectionvector[1][2] = planes[2][1] * ilocalsize;
12521         projectionvector[2][0] = planes[0][2] * ilocalsize;
12522         projectionvector[2][1] = planes[1][2] * ilocalsize;
12523         projectionvector[2][2] = planes[2][2] * ilocalsize;
12524         projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
12525         projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
12526         projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
12527         Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
12528 }
12529 #endif
12530
12531         dynamic = model->surfmesh.isanimated;
12532         numsurfacelist = model->nummodelsurfaces;
12533         surfacelist = model->sortedmodelsurfaces;
12534         surfaces = model->data_surfaces;
12535
12536         bih = NULL;
12537         bih_triangles_count = -1;
12538         if(!dynamic)
12539         {
12540                 if(model->render_bih.numleafs)
12541                         bih = &model->render_bih;
12542                 else if(model->collision_bih.numleafs)
12543                         bih = &model->collision_bih;
12544         }
12545         if(bih)
12546                 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
12547         if(bih_triangles_count == 0)
12548                 return;
12549         if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
12550                 return;
12551         if(bih_triangles_count > 0)
12552         {
12553                 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
12554                 {
12555                         surfaceindex = bih_surfaces[triangleindex];
12556                         surface = surfaces + surfaceindex;
12557                         texture = surface->texture;
12558                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12559                                 continue;
12560                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12561                                 continue;
12562                         R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
12563                 }
12564         }
12565         else
12566         {
12567                 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
12568                 {
12569                         surfaceindex = surfacelist[surfacelistindex];
12570                         surface = surfaces + surfaceindex;
12571                         // check cull box first because it rejects more than any other check
12572                         if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
12573                                 continue;
12574                         // skip transparent surfaces
12575                         texture = surface->texture;
12576                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12577                                 continue;
12578                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12579                                 continue;
12580                         numtriangles = surface->num_triangles;
12581                         for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
12582                                 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
12583                 }
12584         }
12585 }
12586
12587 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
12588 static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
12589 {
12590         int renderentityindex;
12591         float worldmins[3];
12592         float worldmaxs[3];
12593         entity_render_t *ent;
12594
12595         if (!cl_decals_newsystem.integer)
12596                 return;
12597
12598         worldmins[0] = worldorigin[0] - worldsize;
12599         worldmins[1] = worldorigin[1] - worldsize;
12600         worldmins[2] = worldorigin[2] - worldsize;
12601         worldmaxs[0] = worldorigin[0] + worldsize;
12602         worldmaxs[1] = worldorigin[1] + worldsize;
12603         worldmaxs[2] = worldorigin[2] + worldsize;
12604
12605         R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12606
12607         for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
12608         {
12609                 ent = r_refdef.scene.entities[renderentityindex];
12610                 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
12611                         continue;
12612
12613                 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12614         }
12615 }
12616
12617 typedef struct r_decalsystem_splatqueue_s
12618 {
12619         vec3_t worldorigin;
12620         vec3_t worldnormal;
12621         float color[4];
12622         float tcrange[4];
12623         float worldsize;
12624         int decalsequence;
12625 }
12626 r_decalsystem_splatqueue_t;
12627
12628 int r_decalsystem_numqueued = 0;
12629 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
12630
12631 void R_DecalSystem_SplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize)
12632 {
12633         r_decalsystem_splatqueue_t *queue;
12634
12635         if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
12636                 return;
12637
12638         queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
12639         VectorCopy(worldorigin, queue->worldorigin);
12640         VectorCopy(worldnormal, queue->worldnormal);
12641         Vector4Set(queue->color, r, g, b, a);
12642         Vector4Set(queue->tcrange, s1, t1, s2, t2);
12643         queue->worldsize = worldsize;
12644         queue->decalsequence = cl.decalsequence++;
12645 }
12646
12647 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
12648 {
12649         int i;
12650         r_decalsystem_splatqueue_t *queue;
12651
12652         for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
12653                 R_DecalSystem_ApplySplatEntities(queue->worldorigin, queue->worldnormal, queue->color[0], queue->color[1], queue->color[2], queue->color[3], queue->tcrange[0], queue->tcrange[1], queue->tcrange[2], queue->tcrange[3], queue->worldsize, queue->decalsequence);
12654         r_decalsystem_numqueued = 0;
12655 }
12656
12657 extern cvar_t cl_decals_max;
12658 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
12659 {
12660         int i;
12661         decalsystem_t *decalsystem = &ent->decalsystem;
12662         int numdecals;
12663         int killsequence;
12664         tridecal_t *decal;
12665         float frametime;
12666         float lifetime;
12667
12668         if (!decalsystem->numdecals)
12669                 return;
12670
12671         if (r_showsurfaces.integer)
12672                 return;
12673
12674         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12675         {
12676                 R_DecalSystem_Reset(decalsystem);
12677                 return;
12678         }
12679
12680         killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
12681         lifetime = cl_decals_time.value + cl_decals_fadetime.value;
12682
12683         if (decalsystem->lastupdatetime)
12684                 frametime = (cl.time - decalsystem->lastupdatetime);
12685         else
12686                 frametime = 0;
12687         decalsystem->lastupdatetime = cl.time;
12688         decal = decalsystem->decals;
12689         numdecals = decalsystem->numdecals;
12690
12691         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12692         {
12693                 if (decal->color4ub[0][3])
12694                 {
12695                         decal->lived += frametime;
12696                         if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
12697                         {
12698                                 memset(decal, 0, sizeof(*decal));
12699                                 if (decalsystem->freedecal > i)
12700                                         decalsystem->freedecal = i;
12701                         }
12702                 }
12703         }
12704         decal = decalsystem->decals;
12705         while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
12706                 numdecals--;
12707
12708         // collapse the array by shuffling the tail decals into the gaps
12709         for (;;)
12710         {
12711                 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
12712                         decalsystem->freedecal++;
12713                 if (decalsystem->freedecal == numdecals)
12714                         break;
12715                 decal[decalsystem->freedecal] = decal[--numdecals];
12716         }
12717
12718         decalsystem->numdecals = numdecals;
12719
12720         if (numdecals <= 0)
12721         {
12722                 // if there are no decals left, reset decalsystem
12723                 R_DecalSystem_Reset(decalsystem);
12724         }
12725 }
12726
12727 extern skinframe_t *decalskinframe;
12728 static void R_DrawModelDecals_Entity(entity_render_t *ent)
12729 {
12730         int i;
12731         decalsystem_t *decalsystem = &ent->decalsystem;
12732         int numdecals;
12733         tridecal_t *decal;
12734         float faderate;
12735         float alpha;
12736         float *v3f;
12737         float *c4f;
12738         float *t2f;
12739         const int *e;
12740         const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
12741         int numtris = 0;
12742
12743         numdecals = decalsystem->numdecals;
12744         if (!numdecals)
12745                 return;
12746
12747         if (r_showsurfaces.integer)
12748                 return;
12749
12750         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12751         {
12752                 R_DecalSystem_Reset(decalsystem);
12753                 return;
12754         }
12755
12756         // if the model is static it doesn't matter what value we give for
12757         // wantnormals and wanttangents, so this logic uses only rules applicable
12758         // to a model, knowing that they are meaningless otherwise
12759         if (ent == r_refdef.scene.worldentity)
12760                 RSurf_ActiveWorldEntity();
12761         else
12762                 RSurf_ActiveModelEntity(ent, false, false, false);
12763
12764         decalsystem->lastupdatetime = cl.time;
12765         decal = decalsystem->decals;
12766
12767         faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
12768
12769         // update vertex positions for animated models
12770         v3f = decalsystem->vertex3f;
12771         c4f = decalsystem->color4f;
12772         t2f = decalsystem->texcoord2f;
12773         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12774         {
12775                 if (!decal->color4ub[0][3])
12776                         continue;
12777
12778                 if (surfacevisible && !surfacevisible[decal->surfaceindex])
12779                         continue;
12780
12781                 // update color values for fading decals
12782                 if (decal->lived >= cl_decals_time.value)
12783                 {
12784                         alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
12785                         alpha *= (1.0f/255.0f);
12786                 }
12787                 else
12788                         alpha = 1.0f/255.0f;
12789
12790                 c4f[ 0] = decal->color4ub[0][0] * alpha;
12791                 c4f[ 1] = decal->color4ub[0][1] * alpha;
12792                 c4f[ 2] = decal->color4ub[0][2] * alpha;
12793                 c4f[ 3] = 1;
12794                 c4f[ 4] = decal->color4ub[1][0] * alpha;
12795                 c4f[ 5] = decal->color4ub[1][1] * alpha;
12796                 c4f[ 6] = decal->color4ub[1][2] * alpha;
12797                 c4f[ 7] = 1;
12798                 c4f[ 8] = decal->color4ub[2][0] * alpha;
12799                 c4f[ 9] = decal->color4ub[2][1] * alpha;
12800                 c4f[10] = decal->color4ub[2][2] * alpha;
12801                 c4f[11] = 1;
12802
12803                 t2f[0] = decal->texcoord2f[0][0];
12804                 t2f[1] = decal->texcoord2f[0][1];
12805                 t2f[2] = decal->texcoord2f[1][0];
12806                 t2f[3] = decal->texcoord2f[1][1];
12807                 t2f[4] = decal->texcoord2f[2][0];
12808                 t2f[5] = decal->texcoord2f[2][1];
12809
12810                 // update vertex positions for animated models
12811                 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnum_triangles)
12812                 {
12813                         e = rsurface.modelelement3i + 3*decal->triangleindex;
12814                         VectorCopy(rsurface.vertex3f + 3*e[0], v3f);
12815                         VectorCopy(rsurface.vertex3f + 3*e[1], v3f + 3);
12816                         VectorCopy(rsurface.vertex3f + 3*e[2], v3f + 6);
12817                 }
12818                 else
12819                 {
12820                         VectorCopy(decal->vertex3f[0], v3f);
12821                         VectorCopy(decal->vertex3f[1], v3f + 3);
12822                         VectorCopy(decal->vertex3f[2], v3f + 6);
12823                 }
12824
12825                 if (r_refdef.fogenabled)
12826                 {
12827                         alpha = RSurf_FogVertex(v3f);
12828                         VectorScale(c4f, alpha, c4f);
12829                         alpha = RSurf_FogVertex(v3f + 3);
12830                         VectorScale(c4f + 4, alpha, c4f + 4);
12831                         alpha = RSurf_FogVertex(v3f + 6);
12832                         VectorScale(c4f + 8, alpha, c4f + 8);
12833                 }
12834
12835                 v3f += 9;
12836                 c4f += 12;
12837                 t2f += 6;
12838                 numtris++;
12839         }
12840
12841         if (numtris > 0)
12842         {
12843                 r_refdef.stats.drawndecals += numtris;
12844
12845                 // now render the decals all at once
12846                 // (this assumes they all use one particle font texture!)
12847                 RSurf_ActiveCustomEntity(&rsurface.matrix, &rsurface.inversematrix, rsurface.ent_flags, rsurface.ent_shadertime, 1, 1, 1, 1, numdecals*3, decalsystem->vertex3f, decalsystem->texcoord2f, NULL, NULL, NULL, decalsystem->color4f, numtris, decalsystem->element3i, decalsystem->element3s, false, false);
12848                 R_Mesh_ResetTextureState();
12849                 R_Mesh_VertexPointer(decalsystem->vertex3f, 0, 0);
12850                 R_Mesh_TexCoordPointer(0, 2, decalsystem->texcoord2f, 0, 0);
12851                 R_Mesh_ColorPointer(decalsystem->color4f, 0, 0);
12852                 GL_DepthMask(false);
12853                 GL_DepthRange(0, 1);
12854                 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
12855                 GL_DepthTest(true);
12856                 GL_CullFace(GL_NONE);
12857                 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
12858                 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
12859                 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, decalsystem->element3s, 0, 0);
12860         }
12861 }
12862
12863 static void R_DrawModelDecals(void)
12864 {
12865         int i, numdecals;
12866
12867         // fade faster when there are too many decals
12868         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12869         for (i = 0;i < r_refdef.scene.numentities;i++)
12870                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12871
12872         R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
12873         for (i = 0;i < r_refdef.scene.numentities;i++)
12874                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12875                         R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
12876
12877         R_DecalSystem_ApplySplatEntitiesQueue();
12878
12879         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12880         for (i = 0;i < r_refdef.scene.numentities;i++)
12881                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12882
12883         r_refdef.stats.totaldecals += numdecals;
12884
12885         if (r_showsurfaces.integer)
12886                 return;
12887
12888         R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
12889
12890         for (i = 0;i < r_refdef.scene.numentities;i++)
12891         {
12892                 if (!r_refdef.viewcache.entityvisible[i])
12893                         continue;
12894                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12895                         R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
12896         }
12897 }
12898
12899 extern cvar_t mod_collision_bih;
12900 void R_DrawDebugModel(void)
12901 {
12902         entity_render_t *ent = rsurface.entity;
12903         int i, j, k, l, flagsmask;
12904         const msurface_t *surface;
12905         dp_model_t *model = ent->model;
12906         vec3_t v;
12907
12908         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
12909
12910         R_Mesh_ColorPointer(NULL, 0, 0);
12911         R_Mesh_ResetTextureState();
12912         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12913         GL_DepthRange(0, 1);
12914         GL_DepthTest(!r_showdisabledepthtest.integer);
12915         GL_DepthMask(false);
12916         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12917
12918         if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
12919         {
12920                 int triangleindex;
12921                 int bihleafindex;
12922                 qboolean cullbox = ent == r_refdef.scene.worldentity;
12923                 const q3mbrush_t *brush;
12924                 const bih_t *bih = &model->collision_bih;
12925                 const bih_leaf_t *bihleaf;
12926                 float vertex3f[3][3];
12927                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
12928                 cullbox = false;
12929                 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
12930                 {
12931                         if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
12932                                 continue;
12933                         switch (bihleaf->type)
12934                         {
12935                         case BIH_BRUSH:
12936                                 brush = model->brush.data_brushes + bihleaf->itemindex;
12937                                 if (brush->colbrushf && brush->colbrushf->numtriangles)
12938                                 {
12939                                         R_Mesh_VertexPointer(brush->colbrushf->points->v, 0, 0);
12940                                         GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
12941                                         R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, 0);
12942                                 }
12943                                 break;
12944                         case BIH_COLLISIONTRIANGLE:
12945                                 triangleindex = bihleaf->itemindex;
12946                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
12947                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
12948                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
12949                                 R_Mesh_VertexPointer(vertex3f[0], 0, 0);
12950                                 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
12951                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, polygonelement3s, 0, 0);
12952                                 break;
12953                         case BIH_RENDERTRIANGLE:
12954                                 triangleindex = bihleaf->itemindex;
12955                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
12956                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
12957                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
12958                                 R_Mesh_VertexPointer(vertex3f[0], 0, 0);
12959                                 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
12960                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, polygonelement3s, 0, 0);
12961                                 break;
12962                         }
12963                 }
12964         }
12965
12966         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12967
12968         if (r_showtris.integer || r_shownormals.integer)
12969         {
12970                 if (r_showdisabledepthtest.integer)
12971                 {
12972                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12973                         GL_DepthMask(false);
12974                 }
12975                 else
12976                 {
12977                         GL_BlendFunc(GL_ONE, GL_ZERO);
12978                         GL_DepthMask(true);
12979                 }
12980                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
12981                 {
12982                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
12983                                 continue;
12984                         rsurface.texture = R_GetCurrentTexture(surface->texture);
12985                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
12986                         {
12987                                 RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
12988                                 if (r_showtris.value > 0)
12989                                 {
12990                                         if (!rsurface.texture->currentlayers->depthmask)
12991                                                 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
12992                                         else if (ent == r_refdef.scene.worldentity)
12993                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
12994                                         else
12995                                                 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
12996                                         R_Mesh_VertexPointer(rsurface.vertex3f, 0, 0);
12997                                         R_Mesh_ColorPointer(NULL, 0, 0);
12998                                         R_Mesh_TexCoordPointer(0, 0, NULL, 0, 0);
12999                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
13000                                         //R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, model->surfmesh.data_element3i, NULL, 0, 0);
13001                                         R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
13002                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
13003                                         CHECKGLERROR
13004                                 }
13005                                 if (r_shownormals.value < 0)
13006                                 {
13007                                         qglBegin(GL_LINES);
13008                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13009                                         {
13010                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
13011                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13012                                                 qglVertex3f(v[0], v[1], v[2]);
13013                                                 VectorMA(v, -r_shownormals.value, rsurface.svector3f + l * 3, v);
13014                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13015                                                 qglVertex3f(v[0], v[1], v[2]);
13016                                         }
13017                                         qglEnd();
13018                                         CHECKGLERROR
13019                                 }
13020                                 if (r_shownormals.value > 0)
13021                                 {
13022                                         qglBegin(GL_LINES);
13023                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13024                                         {
13025                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
13026                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13027                                                 qglVertex3f(v[0], v[1], v[2]);
13028                                                 VectorMA(v, r_shownormals.value, rsurface.svector3f + l * 3, v);
13029                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13030                                                 qglVertex3f(v[0], v[1], v[2]);
13031                                         }
13032                                         qglEnd();
13033                                         CHECKGLERROR
13034                                         qglBegin(GL_LINES);
13035                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13036                                         {
13037                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
13038                                                 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13039                                                 qglVertex3f(v[0], v[1], v[2]);
13040                                                 VectorMA(v, r_shownormals.value, rsurface.tvector3f + l * 3, v);
13041                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13042                                                 qglVertex3f(v[0], v[1], v[2]);
13043                                         }
13044                                         qglEnd();
13045                                         CHECKGLERROR
13046                                         qglBegin(GL_LINES);
13047                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13048                                         {
13049                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
13050                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13051                                                 qglVertex3f(v[0], v[1], v[2]);
13052                                                 VectorMA(v, r_shownormals.value, rsurface.normal3f + l * 3, v);
13053                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13054                                                 qglVertex3f(v[0], v[1], v[2]);
13055                                         }
13056                                         qglEnd();
13057                                         CHECKGLERROR
13058                                 }
13059                         }
13060                 }
13061                 rsurface.texture = NULL;
13062         }
13063 }
13064
13065 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13066 int r_maxsurfacelist = 0;
13067 const msurface_t **r_surfacelist = NULL;
13068 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13069 {
13070         int i, j, endj, flagsmask;
13071         dp_model_t *model = r_refdef.scene.worldmodel;
13072         msurface_t *surfaces;
13073         unsigned char *update;
13074         int numsurfacelist = 0;
13075         if (model == NULL)
13076                 return;
13077
13078         if (r_maxsurfacelist < model->num_surfaces)
13079         {
13080                 r_maxsurfacelist = model->num_surfaces;
13081                 if (r_surfacelist)
13082                         Mem_Free((msurface_t**)r_surfacelist);
13083                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13084         }
13085
13086         RSurf_ActiveWorldEntity();
13087
13088         surfaces = model->data_surfaces;
13089         update = model->brushq1.lightmapupdateflags;
13090
13091         // update light styles on this submodel
13092         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13093         {
13094                 model_brush_lightstyleinfo_t *style;
13095                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13096                 {
13097                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
13098                         {
13099                                 int *list = style->surfacelist;
13100                                 style->value = r_refdef.scene.lightstylevalue[style->style];
13101                                 for (j = 0;j < style->numsurfaces;j++)
13102                                         update[list[j]] = true;
13103                         }
13104                 }
13105         }
13106
13107         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13108
13109         if (debug)
13110         {
13111                 R_DrawDebugModel();
13112                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13113                 return;
13114         }
13115
13116         rsurface.uselightmaptexture = false;
13117         rsurface.texture = NULL;
13118         rsurface.rtlight = NULL;
13119         numsurfacelist = 0;
13120         // add visible surfaces to draw list
13121         for (i = 0;i < model->nummodelsurfaces;i++)
13122         {
13123                 j = model->sortedmodelsurfaces[i];
13124                 if (r_refdef.viewcache.world_surfacevisible[j])
13125                         r_surfacelist[numsurfacelist++] = surfaces + j;
13126         }
13127         // update lightmaps if needed
13128         if (model->brushq1.firstrender)
13129         {
13130                 model->brushq1.firstrender = false;
13131                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13132                         if (update[j])
13133                                 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13134         }
13135         else if (update)
13136         {
13137                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13138                         if (r_refdef.viewcache.world_surfacevisible[j])
13139                                 if (update[j])
13140                                         R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13141         }
13142         // don't do anything if there were no surfaces
13143         if (!numsurfacelist)
13144         {
13145                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13146                 return;
13147         }
13148         R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13149         GL_AlphaTest(false);
13150
13151         // add to stats if desired
13152         if (r_speeds.integer && !skysurfaces && !depthonly)
13153         {
13154                 r_refdef.stats.world_surfaces += numsurfacelist;
13155                 for (j = 0;j < numsurfacelist;j++)
13156                         r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13157         }
13158
13159         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13160 }
13161
13162 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13163 {
13164         int i, j, endj, flagsmask;
13165         dp_model_t *model = ent->model;
13166         msurface_t *surfaces;
13167         unsigned char *update;
13168         int numsurfacelist = 0;
13169         if (model == NULL)
13170                 return;
13171
13172         if (r_maxsurfacelist < model->num_surfaces)
13173         {
13174                 r_maxsurfacelist = model->num_surfaces;
13175                 if (r_surfacelist)
13176                         Mem_Free((msurface_t **)r_surfacelist);
13177                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13178         }
13179
13180         // if the model is static it doesn't matter what value we give for
13181         // wantnormals and wanttangents, so this logic uses only rules applicable
13182         // to a model, knowing that they are meaningless otherwise
13183         if (ent == r_refdef.scene.worldentity)
13184                 RSurf_ActiveWorldEntity();
13185         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13186                 RSurf_ActiveModelEntity(ent, false, false, false);
13187         else if (prepass)
13188                 RSurf_ActiveModelEntity(ent, true, true, true);
13189         else if (depthonly)
13190         {
13191                 switch (vid.renderpath)
13192                 {
13193                 case RENDERPATH_GL20:
13194                 case RENDERPATH_CGGL:
13195                         RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
13196                         break;
13197                 case RENDERPATH_GL13:
13198                 case RENDERPATH_GL11:
13199                         RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
13200                         break;
13201                 }
13202         }
13203         else
13204         {
13205                 switch (vid.renderpath)
13206                 {
13207                 case RENDERPATH_GL20:
13208                 case RENDERPATH_CGGL:
13209                         RSurf_ActiveModelEntity(ent, true, true, false);
13210                         break;
13211                 case RENDERPATH_GL13:
13212                 case RENDERPATH_GL11:
13213                         RSurf_ActiveModelEntity(ent, true, false, false);
13214                         break;
13215                 }
13216         }
13217
13218         surfaces = model->data_surfaces;
13219         update = model->brushq1.lightmapupdateflags;
13220
13221         // update light styles
13222         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13223         {
13224                 model_brush_lightstyleinfo_t *style;
13225                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13226                 {
13227                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
13228                         {
13229                                 int *list = style->surfacelist;
13230                                 style->value = r_refdef.scene.lightstylevalue[style->style];
13231                                 for (j = 0;j < style->numsurfaces;j++)
13232                                         update[list[j]] = true;
13233                         }
13234                 }
13235         }
13236
13237         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13238
13239         if (debug)
13240         {
13241                 R_DrawDebugModel();
13242                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13243                 return;
13244         }
13245
13246         rsurface.uselightmaptexture = false;
13247         rsurface.texture = NULL;
13248         rsurface.rtlight = NULL;
13249         numsurfacelist = 0;
13250         // add visible surfaces to draw list
13251         for (i = 0;i < model->nummodelsurfaces;i++)
13252                 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13253         // don't do anything if there were no surfaces
13254         if (!numsurfacelist)
13255         {
13256                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13257                 return;
13258         }
13259         // update lightmaps if needed
13260         if (update)
13261         {
13262                 int updated = 0;
13263                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13264                 {
13265                         if (update[j])
13266                         {
13267                                 updated++;
13268                                 R_BuildLightMap(ent, surfaces + j);
13269                         }
13270                 }
13271         }
13272         if (update)
13273                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13274                         if (update[j])
13275                                 R_BuildLightMap(ent, surfaces + j);
13276         R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13277         GL_AlphaTest(false);
13278
13279         // add to stats if desired
13280         if (r_speeds.integer && !skysurfaces && !depthonly)
13281         {
13282                 r_refdef.stats.entities_surfaces += numsurfacelist;
13283                 for (j = 0;j < numsurfacelist;j++)
13284                         r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13285         }
13286
13287         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13288 }
13289
13290 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13291 {
13292         static texture_t texture;
13293         static msurface_t surface;
13294         const msurface_t *surfacelist = &surface;
13295
13296         // fake enough texture and surface state to render this geometry
13297
13298         texture.update_lastrenderframe = -1; // regenerate this texture
13299         texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
13300         texture.currentskinframe = skinframe;
13301         texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
13302         texture.offsetmapping = OFFSETMAPPING_OFF;
13303         texture.offsetscale = 1;
13304         texture.specularscalemod = 1;
13305         texture.specularpowermod = 1;
13306
13307         surface.texture = &texture;
13308         surface.num_triangles = numtriangles;
13309         surface.num_firsttriangle = firsttriangle;
13310         surface.num_vertices = numvertices;
13311         surface.num_firstvertex = firstvertex;
13312
13313         // now render it
13314         rsurface.texture = R_GetCurrentTexture(surface.texture);
13315         rsurface.uselightmaptexture = false;
13316         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13317 }
13318
13319 void R_DrawCustomSurface_Texture(texture_t *texture, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13320 {
13321         static msurface_t surface;
13322         const msurface_t *surfacelist = &surface;
13323
13324         // fake enough texture and surface state to render this geometry
13325
13326         surface.texture = texture;
13327         surface.num_triangles = numtriangles;
13328         surface.num_firsttriangle = firsttriangle;
13329         surface.num_vertices = numvertices;
13330         surface.num_firstvertex = firstvertex;
13331
13332         // now render it
13333         rsurface.texture = R_GetCurrentTexture(surface.texture);
13334         rsurface.uselightmaptexture = false;
13335         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13336 }