]> git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_rmain.c
r_water_scissormode: 0 = none, 1 = glScissor, 2 = glScissor and frustum culling
[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", "2", "scissor (1) and cull (2) 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;
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                 // Leaving those out was a mistake, those were in the old code, and they
7418                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7419                 // I couldn't reproduce it after adding those normalizations. --blub
7420                 VectorNormalize(r_refdef.view.frustum[0].normal);
7421                 VectorNormalize(r_refdef.view.frustum[1].normal);
7422                 VectorNormalize(r_refdef.view.frustum[2].normal);
7423                 VectorNormalize(r_refdef.view.frustum[3].normal);
7424
7425                 // make the corners absolute
7426                 VectorAdd(r_refdef.view.frustumcorner[0], r_refdef.view.origin, r_refdef.view.frustumcorner[0]);
7427                 VectorAdd(r_refdef.view.frustumcorner[1], r_refdef.view.origin, r_refdef.view.frustumcorner[1]);
7428                 VectorAdd(r_refdef.view.frustumcorner[2], r_refdef.view.origin, r_refdef.view.frustumcorner[2]);
7429                 VectorAdd(r_refdef.view.frustumcorner[3], r_refdef.view.origin, r_refdef.view.frustumcorner[3]);
7430
7431                 // one more normal
7432                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7433
7434                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7435                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7436                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7437                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7438                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7439         }
7440         else
7441         {
7442                 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7443                 VectorScale(left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7444                 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7445                 VectorScale(up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7446                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7447                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7448                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7449                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7450                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7451                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7452         }
7453         r_refdef.view.numfrustumplanes = 5;
7454
7455         if (r_refdef.view.useclipplane)
7456         {
7457                 r_refdef.view.numfrustumplanes = 6;
7458                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7459         }
7460
7461         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7462                 PlaneClassify(r_refdef.view.frustum + i);
7463
7464         // LordHavoc: note to all quake engine coders, Quake had a special case
7465         // for 90 degrees which assumed a square view (wrong), so I removed it,
7466         // Quake2 has it disabled as well.
7467
7468         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7469         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7470         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7471         //PlaneClassify(&frustum[0]);
7472
7473         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7474         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7475         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7476         //PlaneClassify(&frustum[1]);
7477
7478         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7479         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7480         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7481         //PlaneClassify(&frustum[2]);
7482
7483         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7484         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7485         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7486         //PlaneClassify(&frustum[3]);
7487
7488         // nearclip plane
7489         //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7490         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7491         //PlaneClassify(&frustum[4]);
7492 }
7493
7494 void R_View_UpdateWithScissor(const int *myscissor)
7495 {
7496         R_Main_ResizeViewCache();
7497         R_View_SetFrustum(myscissor);
7498         R_View_WorldVisibility(r_refdef.view.useclipplane);
7499         R_View_UpdateEntityVisible();
7500         R_View_UpdateEntityLighting();
7501 }
7502
7503 void R_View_Update(void)
7504 {
7505         R_Main_ResizeViewCache();
7506         R_View_SetFrustum(NULL);
7507         R_View_WorldVisibility(r_refdef.view.useclipplane);
7508         R_View_UpdateEntityVisible();
7509         R_View_UpdateEntityLighting();
7510 }
7511
7512 void R_SetupView(qboolean allowwaterclippingplane)
7513 {
7514         const float *customclipplane = NULL;
7515         float plane[4];
7516         if (r_refdef.view.useclipplane && allowwaterclippingplane)
7517         {
7518                 // LordHavoc: couldn't figure out how to make this approach the
7519                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7520                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7521                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7522                         dist = r_refdef.view.clipplane.dist;
7523                 plane[0] = r_refdef.view.clipplane.normal[0];
7524                 plane[1] = r_refdef.view.clipplane.normal[1];
7525                 plane[2] = r_refdef.view.clipplane.normal[2];
7526                 plane[3] = dist;
7527                 customclipplane = plane;
7528         }
7529
7530         if (!r_refdef.view.useperspective)
7531                 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);
7532         else if (vid.stencil && r_useinfinitefarclip.integer)
7533                 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);
7534         else
7535                 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);
7536         R_SetViewport(&r_refdef.view.viewport);
7537 }
7538
7539 void R_EntityMatrix(const matrix4x4_t *matrix)
7540 {
7541         if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7542         {
7543                 gl_modelmatrixchanged = false;
7544                 gl_modelmatrix = *matrix;
7545                 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
7546                 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
7547                 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
7548                 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
7549                 CHECKGLERROR
7550                 switch(vid.renderpath)
7551                 {
7552                 case RENDERPATH_GL20:
7553                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
7554                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
7555                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7556                         break;
7557                 case RENDERPATH_CGGL:
7558 #ifdef SUPPORTCG
7559                         CHECKCGERROR
7560                         if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
7561                         if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
7562                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7563 #endif
7564                         break;
7565                 case RENDERPATH_GL13:
7566                 case RENDERPATH_GL11:
7567                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7568                         break;
7569                 }
7570         }
7571 }
7572
7573 void R_ResetViewRendering2D(void)
7574 {
7575         r_viewport_t viewport;
7576         DrawQ_Finish();
7577
7578         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
7579         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);
7580         R_SetViewport(&viewport);
7581         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
7582         GL_Color(1, 1, 1, 1);
7583         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7584         GL_BlendFunc(GL_ONE, GL_ZERO);
7585         GL_AlphaTest(false);
7586         GL_ScissorTest(false);
7587         GL_DepthMask(false);
7588         GL_DepthRange(0, 1);
7589         GL_DepthTest(false);
7590         R_EntityMatrix(&identitymatrix);
7591         R_Mesh_ResetTextureState();
7592         GL_PolygonOffset(0, 0);
7593         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7594         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7595         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7596         qglStencilMask(~0);CHECKGLERROR
7597         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7598         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7599         GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
7600 }
7601
7602 void R_ResetViewRendering3D(void)
7603 {
7604         DrawQ_Finish();
7605
7606         R_SetupView(true);
7607         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7608         GL_Color(1, 1, 1, 1);
7609         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7610         GL_BlendFunc(GL_ONE, GL_ZERO);
7611         GL_AlphaTest(false);
7612         GL_ScissorTest(true);
7613         GL_DepthMask(true);
7614         GL_DepthRange(0, 1);
7615         GL_DepthTest(true);
7616         R_EntityMatrix(&identitymatrix);
7617         R_Mesh_ResetTextureState();
7618         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7619         qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7620         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7621         qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7622         qglStencilMask(~0);CHECKGLERROR
7623         qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7624         qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7625         GL_CullFace(r_refdef.view.cullface_back);
7626 }
7627
7628 /*
7629 ================
7630 R_RenderView_UpdateViewVectors
7631 ================
7632 */
7633 static void R_RenderView_UpdateViewVectors(void)
7634 {
7635         // break apart the view matrix into vectors for various purposes
7636         // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
7637         // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
7638         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
7639         VectorNegate(r_refdef.view.left, r_refdef.view.right);
7640         // make an inverted copy of the view matrix for tracking sprites
7641         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
7642 }
7643
7644 void R_RenderScene(void);
7645 void R_RenderWaterPlanes(void);
7646
7647 static void R_Water_StartFrame(void)
7648 {
7649         int i;
7650         int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
7651         r_waterstate_waterplane_t *p;
7652
7653         if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
7654                 return;
7655
7656         switch(vid.renderpath)
7657         {
7658         case RENDERPATH_GL20:
7659         case RENDERPATH_CGGL:
7660                 break;
7661         case RENDERPATH_GL13:
7662         case RENDERPATH_GL11:
7663                 return;
7664         }
7665
7666         // set waterwidth and waterheight to the water resolution that will be
7667         // used (often less than the screen resolution for faster rendering)
7668         waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
7669         waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
7670
7671         // calculate desired texture sizes
7672         // can't use water if the card does not support the texture size
7673         if (!r_water.integer || r_showsurfaces.integer)
7674                 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
7675         else if (vid.support.arb_texture_non_power_of_two)
7676         {
7677                 texturewidth = waterwidth;
7678                 textureheight = waterheight;
7679                 camerawidth = waterwidth;
7680                 cameraheight = waterheight;
7681         }
7682         else
7683         {
7684                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
7685                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
7686                 for (camerawidth    = 1;camerawidth   <= waterwidth; camerawidth    *= 2); camerawidth  /= 2;
7687                 for (cameraheight   = 1;cameraheight  <= waterheight;cameraheight   *= 2); cameraheight /= 2;
7688         }
7689
7690         // allocate textures as needed
7691         if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
7692         {
7693                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7694                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
7695                 {
7696                         if (p->texture_refraction)
7697                                 R_FreeTexture(p->texture_refraction);
7698                         p->texture_refraction = NULL;
7699                         if (p->texture_reflection)
7700                                 R_FreeTexture(p->texture_reflection);
7701                         p->texture_reflection = NULL;
7702                         if (p->texture_camera)
7703                                 R_FreeTexture(p->texture_camera);
7704                         p->texture_camera = NULL;
7705                 }
7706                 memset(&r_waterstate, 0, sizeof(r_waterstate));
7707                 r_waterstate.texturewidth = texturewidth;
7708                 r_waterstate.textureheight = textureheight;
7709                 r_waterstate.camerawidth = camerawidth;
7710                 r_waterstate.cameraheight = cameraheight;
7711         }
7712
7713         if (r_waterstate.texturewidth)
7714         {
7715                 r_waterstate.enabled = true;
7716
7717                 // when doing a reduced render (HDR) we want to use a smaller area
7718                 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
7719                 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
7720
7721                 // set up variables that will be used in shader setup
7722                 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7723                 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7724                 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7725                 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7726         }
7727
7728         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7729         r_waterstate.numwaterplanes = 0;
7730 }
7731
7732 void R_Water_AddWaterPlane(msurface_t *surface)
7733 {
7734         int triangleindex, planeindex;
7735         const int *e;
7736         vec3_t vert[3];
7737         vec3_t normal;
7738         vec3_t center;
7739         mplane_t plane;
7740         int cam_ent;
7741         r_waterstate_waterplane_t *p;
7742         texture_t *t = R_GetCurrentTexture(surface->texture);
7743         cam_ent = t->camera_entity;
7744         if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
7745                 cam_ent = 0;
7746
7747         // just use the first triangle with a valid normal for any decisions
7748         VectorClear(normal);
7749         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7750         {
7751                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
7752                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
7753                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
7754                 TriangleNormal(vert[0], vert[1], vert[2], normal);
7755                 if (VectorLength2(normal) >= 0.001)
7756                         break;
7757         }
7758
7759         VectorCopy(normal, plane.normal);
7760         VectorNormalize(plane.normal);
7761         plane.dist = DotProduct(vert[0], plane.normal);
7762         PlaneClassify(&plane);
7763         if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
7764         {
7765                 // skip backfaces (except if nocullface is set)
7766                 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
7767                         return;
7768                 VectorNegate(plane.normal, plane.normal);
7769                 plane.dist *= -1;
7770                 PlaneClassify(&plane);
7771         }
7772
7773
7774         // find a matching plane if there is one
7775         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7776                 if(p->camera_entity == t->camera_entity)
7777                         if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
7778                                 break;
7779         if (planeindex >= r_waterstate.maxwaterplanes)
7780                 return; // nothing we can do, out of planes
7781
7782         // if this triangle does not fit any known plane rendered this frame, add one
7783         if (planeindex >= r_waterstate.numwaterplanes)
7784         {
7785                 // store the new plane
7786                 r_waterstate.numwaterplanes++;
7787                 p->plane = plane;
7788                 // clear materialflags and pvs
7789                 p->materialflags = 0;
7790                 p->pvsvalid = false;
7791                 p->camera_entity = t->camera_entity;
7792                 VectorCopy(surface->mins, p->mins);
7793                 VectorCopy(surface->maxs, p->maxs);
7794         }
7795         else
7796         {
7797                 // merge mins/maxs
7798                 p->mins[0] = min(p->mins[0], surface->mins[0]);
7799                 p->mins[1] = min(p->mins[1], surface->mins[1]);
7800                 p->mins[2] = min(p->mins[2], surface->mins[2]);
7801                 p->maxs[0] = min(p->maxs[0], surface->maxs[0]);
7802                 p->maxs[1] = min(p->maxs[1], surface->maxs[1]);
7803                 p->maxs[2] = min(p->maxs[2], surface->maxs[2]);
7804         }
7805         // merge this surface's materialflags into the waterplane
7806         p->materialflags |= t->currentmaterialflags;
7807         if(!(p->materialflags & MATERIALFLAG_CAMERA))
7808         {
7809                 // merge this surface's PVS into the waterplane
7810                 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
7811                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
7812                  && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
7813                 {
7814                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
7815                         p->pvsvalid = true;
7816                 }
7817         }
7818 }
7819
7820 static void R_Water_ProcessPlanes(void)
7821 {
7822         int myscissor[4];
7823         r_refdef_view_t originalview;
7824         r_refdef_view_t myview;
7825         int planeindex;
7826         r_waterstate_waterplane_t *p;
7827         vec3_t visorigin;
7828
7829         originalview = r_refdef.view;
7830
7831         // make sure enough textures are allocated
7832         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7833         {
7834                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7835                 {
7836                         if (!p->texture_refraction)
7837                                 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);
7838                         if (!p->texture_refraction)
7839                                 goto error;
7840                 }
7841                 else if (p->materialflags & MATERIALFLAG_CAMERA)
7842                 {
7843                         if (!p->texture_camera)
7844                                 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);
7845                         if (!p->texture_camera)
7846                                 goto error;
7847                 }
7848
7849                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7850                 {
7851                         if (!p->texture_reflection)
7852                                 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);
7853                         if (!p->texture_reflection)
7854                                 goto error;
7855                 }
7856         }
7857
7858         // render views
7859         r_refdef.view = originalview;
7860         r_refdef.view.showdebug = false;
7861         r_refdef.view.width = r_waterstate.waterwidth;
7862         r_refdef.view.height = r_waterstate.waterheight;
7863         r_refdef.view.useclipplane = true;
7864         myview = r_refdef.view;
7865         r_waterstate.renderingscene = true;
7866         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7867         {
7868                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7869                 {
7870                         r_refdef.view = myview;
7871                         if(r_water_scissormode.integer)
7872                         {
7873                                 R_SetupView(true);
7874                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
7875                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
7876                         }
7877
7878                         // render reflected scene and copy into texture
7879                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
7880                         // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
7881                         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
7882                         r_refdef.view.clipplane = p->plane;
7883
7884                         // reverse the cullface settings for this render
7885                         r_refdef.view.cullface_front = GL_FRONT;
7886                         r_refdef.view.cullface_back = GL_BACK;
7887                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
7888                         {
7889                                 r_refdef.view.usecustompvs = true;
7890                                 if (p->pvsvalid)
7891                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7892                                 else
7893                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7894                         }
7895
7896                         R_ResetViewRendering3D();
7897                         R_ClearScreen(r_refdef.fogenabled);
7898                         if(r_water_scissormode.integer >= 2)
7899                                 R_View_UpdateWithScissor(myscissor);
7900                         else
7901                                 R_View_Update();
7902                         if(r_water_scissormode.integer)
7903                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
7904                         R_RenderScene();
7905
7906                         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);
7907                 }
7908
7909                 // render the normal view scene and copy into texture
7910                 // (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)
7911                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7912                 {
7913                         r_refdef.view = myview;
7914                         if(r_water_scissormode.integer)
7915                         {
7916                                 R_SetupView(true);
7917                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
7918                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
7919                         }
7920
7921                         r_waterstate.renderingrefraction = true;
7922
7923                         r_refdef.view.clipplane = p->plane;
7924                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7925                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7926
7927                         if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
7928                         {
7929                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7930                                 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
7931                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7932                                 R_RenderView_UpdateViewVectors();
7933                                 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7934                                 {
7935                                         r_refdef.view.usecustompvs = true;
7936                                         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);
7937                                 }
7938                         }
7939
7940                         PlaneClassify(&r_refdef.view.clipplane);
7941
7942                         R_ResetViewRendering3D();
7943                         R_ClearScreen(r_refdef.fogenabled);
7944                         if(r_water_scissormode.integer >= 2)
7945                                 R_View_UpdateWithScissor(myscissor);
7946                         else
7947                                 R_View_Update();
7948                         if(r_water_scissormode.integer)
7949                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
7950                         R_RenderScene();
7951
7952                         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);
7953                         r_waterstate.renderingrefraction = false;
7954                 }
7955                 else if (p->materialflags & MATERIALFLAG_CAMERA)
7956                 {
7957                         r_refdef.view = myview;
7958
7959                         r_refdef.view.clipplane = p->plane;
7960                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7961                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7962
7963                         r_refdef.view.width = r_waterstate.camerawidth;
7964                         r_refdef.view.height = r_waterstate.cameraheight;
7965                         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
7966                         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
7967
7968                         if(p->camera_entity)
7969                         {
7970                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7971                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7972                         }
7973
7974                         // note: all of the view is used for displaying... so
7975                         // there is no use in scissoring
7976
7977                         // reverse the cullface settings for this render
7978                         r_refdef.view.cullface_front = GL_FRONT;
7979                         r_refdef.view.cullface_back = GL_BACK;
7980                         // also reverse the view matrix
7981                         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
7982                         R_RenderView_UpdateViewVectors();
7983                         if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7984                         {
7985                                 r_refdef.view.usecustompvs = true;
7986                                 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);
7987                         }
7988                         
7989                         // camera needs no clipplane
7990                         r_refdef.view.useclipplane = false;
7991
7992                         PlaneClassify(&r_refdef.view.clipplane);
7993
7994                         R_ResetViewRendering3D();
7995                         R_ClearScreen(r_refdef.fogenabled);
7996                         R_View_Update();
7997                         R_RenderScene();
7998
7999                         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);
8000                         r_waterstate.renderingrefraction = false;
8001                 }
8002
8003         }
8004         r_waterstate.renderingscene = false;
8005         r_refdef.view = originalview;
8006         R_ResetViewRendering3D();
8007         R_ClearScreen(r_refdef.fogenabled);
8008         R_View_Update();
8009         return;
8010 error:
8011         r_refdef.view = originalview;
8012         r_waterstate.renderingscene = false;
8013         Cvar_SetValueQuick(&r_water, 0);
8014         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
8015         return;
8016 }
8017
8018 void R_Bloom_StartFrame(void)
8019 {
8020         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8021
8022         switch(vid.renderpath)
8023         {
8024         case RENDERPATH_GL20:
8025         case RENDERPATH_CGGL:
8026                 break;
8027         case RENDERPATH_GL13:
8028         case RENDERPATH_GL11:
8029                 return;
8030         }
8031
8032         // set bloomwidth and bloomheight to the bloom resolution that will be
8033         // used (often less than the screen resolution for faster rendering)
8034         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8035         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8036         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8037         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8038         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8039
8040         // calculate desired texture sizes
8041         if (vid.support.arb_texture_non_power_of_two)
8042         {
8043                 screentexturewidth = r_refdef.view.width;
8044                 screentextureheight = r_refdef.view.height;
8045                 bloomtexturewidth = r_bloomstate.bloomwidth;
8046                 bloomtextureheight = r_bloomstate.bloomheight;
8047         }
8048         else
8049         {
8050                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
8051                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
8052                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
8053                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
8054         }
8055
8056         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))
8057         {
8058                 Cvar_SetValueQuick(&r_hdr, 0);
8059                 Cvar_SetValueQuick(&r_bloom, 0);
8060                 Cvar_SetValueQuick(&r_motionblur, 0);
8061                 Cvar_SetValueQuick(&r_damageblur, 0);
8062         }
8063
8064         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)))
8065                 screentexturewidth = screentextureheight = 0;
8066         if (!r_hdr.integer && !r_bloom.integer)
8067                 bloomtexturewidth = bloomtextureheight = 0;
8068
8069         // allocate textures as needed
8070         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8071         {
8072                 if (r_bloomstate.texture_screen)
8073                         R_FreeTexture(r_bloomstate.texture_screen);
8074                 r_bloomstate.texture_screen = NULL;
8075                 r_bloomstate.screentexturewidth = screentexturewidth;
8076                 r_bloomstate.screentextureheight = screentextureheight;
8077                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8078                         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);
8079         }
8080         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8081         {
8082                 if (r_bloomstate.texture_bloom)
8083                         R_FreeTexture(r_bloomstate.texture_bloom);
8084                 r_bloomstate.texture_bloom = NULL;
8085                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8086                 r_bloomstate.bloomtextureheight = bloomtextureheight;
8087                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8088                         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);
8089         }
8090
8091         // when doing a reduced render (HDR) we want to use a smaller area
8092         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8093         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8094         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8095         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8096         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8097
8098         // set up a texcoord array for the full resolution screen image
8099         // (we have to keep this around to copy back during final render)
8100         r_bloomstate.screentexcoord2f[0] = 0;
8101         r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8102         r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8103         r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8104         r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8105         r_bloomstate.screentexcoord2f[5] = 0;
8106         r_bloomstate.screentexcoord2f[6] = 0;
8107         r_bloomstate.screentexcoord2f[7] = 0;
8108
8109         // set up a texcoord array for the reduced resolution bloom image
8110         // (which will be additive blended over the screen image)
8111         r_bloomstate.bloomtexcoord2f[0] = 0;
8112         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8113         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8114         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8115         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8116         r_bloomstate.bloomtexcoord2f[5] = 0;
8117         r_bloomstate.bloomtexcoord2f[6] = 0;
8118         r_bloomstate.bloomtexcoord2f[7] = 0;
8119
8120         if (r_hdr.integer || r_bloom.integer)
8121         {
8122                 r_bloomstate.enabled = true;
8123                 r_bloomstate.hdr = r_hdr.integer != 0;
8124         }
8125
8126         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);
8127 }
8128
8129 void R_Bloom_CopyBloomTexture(float colorscale)
8130 {
8131         r_refdef.stats.bloom++;
8132
8133         // scale down screen texture to the bloom texture size
8134         CHECKGLERROR
8135         R_SetViewport(&r_bloomstate.viewport);
8136         GL_BlendFunc(GL_ONE, GL_ZERO);
8137         GL_Color(colorscale, colorscale, colorscale, 1);
8138         // TODO: optimize with multitexture or GLSL
8139         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
8140         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8141         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8142         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8143
8144         // we now have a bloom image in the framebuffer
8145         // copy it into the bloom image texture for later processing
8146         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);
8147         r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8148 }
8149
8150 void R_Bloom_CopyHDRTexture(void)
8151 {
8152         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);
8153         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8154 }
8155
8156 void R_Bloom_MakeTexture(void)
8157 {
8158         int x, range, dir;
8159         float xoffset, yoffset, r, brighten;
8160
8161         r_refdef.stats.bloom++;
8162
8163         R_ResetViewRendering2D();
8164         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8165         R_Mesh_ColorPointer(NULL, 0, 0);
8166
8167         // we have a bloom image in the framebuffer
8168         CHECKGLERROR
8169         R_SetViewport(&r_bloomstate.viewport);
8170
8171         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8172         {
8173                 x *= 2;
8174                 r = bound(0, r_bloom_colorexponent.value / x, 1);
8175                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8176                 GL_Color(r, r, r, 1);
8177                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8178                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8179                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8180                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8181
8182                 // copy the vertically blurred bloom view to a texture
8183                 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);
8184                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8185         }
8186
8187         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8188         brighten = r_bloom_brighten.value;
8189         if (r_hdr.integer)
8190                 brighten *= r_hdr_range.value;
8191         brighten = sqrt(brighten);
8192         if(range >= 1)
8193                 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8194         R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8195         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.offsettexcoord2f, 0, 0);
8196
8197         for (dir = 0;dir < 2;dir++)
8198         {
8199                 // blend on at multiple vertical offsets to achieve a vertical blur
8200                 // TODO: do offset blends using GLSL
8201                 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8202                 GL_BlendFunc(GL_ONE, GL_ZERO);
8203                 for (x = -range;x <= range;x++)
8204                 {
8205                         if (!dir){xoffset = 0;yoffset = x;}
8206                         else {xoffset = x;yoffset = 0;}
8207                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
8208                         yoffset /= (float)r_bloomstate.bloomtextureheight;
8209                         // compute a texcoord array with the specified x and y offset
8210                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8211                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8212                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8213                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8214                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8215                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8216                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8217                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8218                         // this r value looks like a 'dot' particle, fading sharply to
8219                         // black at the edges
8220                         // (probably not realistic but looks good enough)
8221                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8222                         //r = brighten/(range*2+1);
8223                         r = brighten / (range * 2 + 1);
8224                         if(range >= 1)
8225                                 r *= (1 - x*x/(float)(range*range));
8226                         GL_Color(r, r, r, 1);
8227                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8228                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8229                         GL_BlendFunc(GL_ONE, GL_ONE);
8230                 }
8231
8232                 // copy the vertically blurred bloom view to a texture
8233                 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);
8234                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8235         }
8236
8237         // apply subtract last
8238         // (just like it would be in a GLSL shader)
8239         if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
8240         {
8241                 GL_BlendFunc(GL_ONE, GL_ZERO);
8242                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8243                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8244                 GL_Color(1, 1, 1, 1);
8245                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8246                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8247
8248                 GL_BlendFunc(GL_ONE, GL_ONE);
8249                 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
8250                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8251                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8252                 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
8253                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8254                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8255                 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
8256
8257                 // copy the darkened bloom view to a texture
8258                 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);
8259                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8260         }
8261 }
8262
8263 void R_HDR_RenderBloomTexture(void)
8264 {
8265         int oldwidth, oldheight;
8266         float oldcolorscale;
8267
8268         oldcolorscale = r_refdef.view.colorscale;
8269         oldwidth = r_refdef.view.width;
8270         oldheight = r_refdef.view.height;
8271         r_refdef.view.width = r_bloomstate.bloomwidth;
8272         r_refdef.view.height = r_bloomstate.bloomheight;
8273
8274         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
8275         // TODO: add exposure compensation features
8276         // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8277
8278         r_refdef.view.showdebug = false;
8279         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8280
8281         R_ResetViewRendering3D();
8282
8283         R_ClearScreen(r_refdef.fogenabled);
8284         if (r_timereport_active)
8285                 R_TimeReport("HDRclear");
8286
8287         R_View_Update();
8288         if (r_timereport_active)
8289                 R_TimeReport("visibility");
8290
8291         // only do secondary renders with HDR if r_hdr is 2 or higher
8292         r_waterstate.numwaterplanes = 0;
8293         if (r_waterstate.enabled && r_hdr.integer >= 2)
8294                 R_RenderWaterPlanes();
8295
8296         r_refdef.view.showdebug = true;
8297         R_RenderScene();
8298         r_waterstate.numwaterplanes = 0;
8299
8300         R_ResetViewRendering2D();
8301
8302         R_Bloom_CopyHDRTexture();
8303         R_Bloom_MakeTexture();
8304
8305         // restore the view settings
8306         r_refdef.view.width = oldwidth;
8307         r_refdef.view.height = oldheight;
8308         r_refdef.view.colorscale = oldcolorscale;
8309
8310         R_ResetViewRendering3D();
8311
8312         R_ClearScreen(r_refdef.fogenabled);
8313         if (r_timereport_active)
8314                 R_TimeReport("viewclear");
8315 }
8316
8317 static void R_BlendView(void)
8318 {
8319         unsigned int permutation;
8320         float uservecs[4][4];
8321
8322         switch (vid.renderpath)
8323         {
8324         case RENDERPATH_GL20:
8325         case RENDERPATH_CGGL:
8326                 permutation =
8327                           (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8328                         | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8329                         | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8330                         | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8331                         | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8332
8333                 if (r_bloomstate.texture_screen)
8334                 {
8335                         // make sure the buffer is available
8336                         if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8337
8338                         R_ResetViewRendering2D();
8339                         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8340                         R_Mesh_ColorPointer(NULL, 0, 0);
8341
8342                         if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8343                         {
8344                                 // declare variables
8345                                 float speed;
8346                                 static float avgspeed;
8347
8348                                 speed = VectorLength(cl.movement_velocity);
8349
8350                                 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8351                                 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8352
8353                                 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8354                                 speed = bound(0, speed, 1);
8355                                 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8356
8357                                 // calculate values into a standard alpha
8358                                 cl.motionbluralpha = 1 - exp(-
8359                                                 (
8360                                                  (r_motionblur.value * speed / 80)
8361                                                  +
8362                                                  (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8363                                                 )
8364                                                 /
8365                                                 max(0.0001, cl.time - cl.oldtime) // fps independent
8366                                            );
8367
8368                                 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8369                                 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8370                                 // apply the blur
8371                                 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8372                                 {
8373                                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8374                                         GL_Color(1, 1, 1, cl.motionbluralpha);
8375                                         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8376                                         R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
8377                                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8378                                         r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8379                                 }
8380                         }
8381
8382                         // copy view into the screen texture
8383                         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);
8384                         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8385                 }
8386                 else if (!r_bloomstate.texture_bloom)
8387                 {
8388                         // we may still have to do view tint...
8389                         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8390                         {
8391                                 // apply a color tint to the whole view
8392                                 R_ResetViewRendering2D();
8393                                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8394                                 R_Mesh_ColorPointer(NULL, 0, 0);
8395                                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8396                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8397                                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8398                                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8399                         }
8400                         break; // no screen processing, no bloom, skip it
8401                 }
8402
8403                 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8404                 {
8405                         // render simple bloom effect
8406                         // copy the screen and shrink it and darken it for the bloom process
8407                         R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8408                         // make the bloom texture
8409                         R_Bloom_MakeTexture();
8410                 }
8411
8412 #if _MSC_VER >= 1400
8413 #define sscanf sscanf_s
8414 #endif
8415                 memset(uservecs, 0, sizeof(uservecs));
8416                 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8417                 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8418                 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8419                 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8420
8421                 R_ResetViewRendering2D();
8422                 R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8423                 R_Mesh_ColorPointer(NULL, 0, 0);
8424                 GL_Color(1, 1, 1, 1);
8425                 GL_BlendFunc(GL_ONE, GL_ZERO);
8426                 R_Mesh_TexCoordPointer(0, 2, r_bloomstate.screentexcoord2f, 0, 0);
8427                 R_Mesh_TexCoordPointer(1, 2, r_bloomstate.bloomtexcoord2f, 0, 0);
8428
8429                 switch(vid.renderpath)
8430                 {
8431                 case RENDERPATH_GL20:
8432                         R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8433                         if (r_glsl_permutation->loc_Texture_First      >= 0) R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
8434                         if (r_glsl_permutation->loc_Texture_Second     >= 0) R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
8435                         if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
8436                         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]);
8437                         if (r_glsl_permutation->loc_PixelSize          >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8438                         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]);
8439                         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]);
8440                         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]);
8441                         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]);
8442                         if (r_glsl_permutation->loc_Saturation         >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation        , r_glsl_saturation.value);
8443                         if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8444                         break;
8445                 case RENDERPATH_CGGL:
8446 #ifdef SUPPORTCG
8447                         R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8448                         if (r_cg_permutation->fp_Texture_First     ) CG_BindTexture(r_cg_permutation->fp_Texture_First     , r_bloomstate.texture_screen);CHECKCGERROR
8449                         if (r_cg_permutation->fp_Texture_Second    ) CG_BindTexture(r_cg_permutation->fp_Texture_Second    , r_bloomstate.texture_bloom );CHECKCGERROR
8450                         if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps       );CHECKCGERROR
8451                         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
8452                         if (r_cg_permutation->fp_PixelSize         ) cgGLSetParameter2f(     r_cg_permutation->fp_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8453                         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
8454                         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
8455                         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
8456                         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
8457                         if (r_cg_permutation->fp_Saturation        ) cgGLSetParameter1f(     r_cg_permutation->fp_Saturation        , r_glsl_saturation.value);CHECKCGERROR
8458                         if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8459 #endif
8460                         break;
8461                 default:
8462                         break;
8463                 }
8464                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8465                 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8466                 break;
8467         case RENDERPATH_GL13:
8468         case RENDERPATH_GL11:
8469                 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8470                 {
8471                         // apply a color tint to the whole view
8472                         R_ResetViewRendering2D();
8473                         R_Mesh_VertexPointer(r_screenvertex3f, 0, 0);
8474                         R_Mesh_ColorPointer(NULL, 0, 0);
8475                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8476                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8477                         GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8478                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0);
8479                 }
8480                 break;
8481         }
8482 }
8483
8484 matrix4x4_t r_waterscrollmatrix;
8485
8486 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
8487 {
8488         if (r_refdef.fog_density)
8489         {
8490                 r_refdef.fogcolor[0] = r_refdef.fog_red;
8491                 r_refdef.fogcolor[1] = r_refdef.fog_green;
8492                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
8493
8494                 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
8495                 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
8496                 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
8497                 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
8498
8499                 {
8500                         vec3_t fogvec;
8501                         VectorCopy(r_refdef.fogcolor, fogvec);
8502                         //   color.rgb *= ContrastBoost * SceneBrightness;
8503                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
8504                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
8505                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
8506                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
8507                 }
8508         }
8509 }
8510
8511 void R_UpdateVariables(void)
8512 {
8513         R_Textures_Frame();
8514
8515         r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
8516
8517         r_refdef.farclip = r_farclip_base.value;
8518         if (r_refdef.scene.worldmodel)
8519                 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
8520         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
8521
8522         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
8523                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
8524         r_refdef.polygonfactor = 0;
8525         r_refdef.polygonoffset = 0;
8526         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8527         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8528
8529         r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
8530         r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
8531         r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
8532         r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
8533         r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
8534         if (FAKELIGHT_ENABLED)
8535         {
8536                 r_refdef.lightmapintensity *= r_fakelight_intensity.value;
8537         }
8538         if (r_showsurfaces.integer)
8539         {
8540                 r_refdef.scene.rtworld = false;
8541                 r_refdef.scene.rtworldshadows = false;
8542                 r_refdef.scene.rtdlight = false;
8543                 r_refdef.scene.rtdlightshadows = false;
8544                 r_refdef.lightmapintensity = 0;
8545         }
8546
8547         if (gamemode == GAME_NEHAHRA)
8548         {
8549                 if (gl_fogenable.integer)
8550                 {
8551                         r_refdef.oldgl_fogenable = true;
8552                         r_refdef.fog_density = gl_fogdensity.value;
8553                         r_refdef.fog_red = gl_fogred.value;
8554                         r_refdef.fog_green = gl_foggreen.value;
8555                         r_refdef.fog_blue = gl_fogblue.value;
8556                         r_refdef.fog_alpha = 1;
8557                         r_refdef.fog_start = 0;
8558                         r_refdef.fog_end = gl_skyclip.value;
8559                         r_refdef.fog_height = 1<<30;
8560                         r_refdef.fog_fadedepth = 128;
8561                 }
8562                 else if (r_refdef.oldgl_fogenable)
8563                 {
8564                         r_refdef.oldgl_fogenable = false;
8565                         r_refdef.fog_density = 0;
8566                         r_refdef.fog_red = 0;
8567                         r_refdef.fog_green = 0;
8568                         r_refdef.fog_blue = 0;
8569                         r_refdef.fog_alpha = 0;
8570                         r_refdef.fog_start = 0;
8571                         r_refdef.fog_end = 0;
8572                         r_refdef.fog_height = 1<<30;
8573                         r_refdef.fog_fadedepth = 128;
8574                 }
8575         }
8576
8577         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
8578         r_refdef.fog_start = max(0, r_refdef.fog_start);
8579         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
8580
8581         // R_UpdateFogColor(); // why? R_RenderScene does it anyway
8582
8583         if (r_refdef.fog_density && r_drawfog.integer)
8584         {
8585                 r_refdef.fogenabled = true;
8586                 // this is the point where the fog reaches 0.9986 alpha, which we
8587                 // consider a good enough cutoff point for the texture
8588                 // (0.9986 * 256 == 255.6)
8589                 if (r_fog_exp2.integer)
8590                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
8591                 else
8592                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
8593                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
8594                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
8595                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
8596                 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
8597                         R_BuildFogHeightTexture();
8598                 // fog color was already set
8599                 // update the fog texture
8600                 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)
8601                         R_BuildFogTexture();
8602                 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
8603                 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
8604         }
8605         else
8606                 r_refdef.fogenabled = false;
8607
8608         switch(vid.renderpath)
8609         {
8610         case RENDERPATH_GL20:
8611         case RENDERPATH_CGGL:
8612                 if(v_glslgamma.integer && !vid_gammatables_trivial)
8613                 {
8614                         if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
8615                         {
8616                                 // build GLSL gamma texture
8617 #define RAMPWIDTH 256
8618                                 unsigned short ramp[RAMPWIDTH * 3];
8619                                 unsigned char rampbgr[RAMPWIDTH][4];
8620                                 int i;
8621
8622                                 r_texture_gammaramps_serial = vid_gammatables_serial;
8623
8624                                 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
8625                                 for(i = 0; i < RAMPWIDTH; ++i)
8626                                 {
8627                                         rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8628                                         rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8629                                         rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
8630                                         rampbgr[i][3] = 0;
8631                                 }
8632                                 if (r_texture_gammaramps)
8633                                 {
8634                                         R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
8635                                 }
8636                                 else
8637                                 {
8638                                         r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
8639                                 }
8640                         }
8641                 }
8642                 else
8643                 {
8644                         // remove GLSL gamma texture
8645                 }
8646                 break;
8647         case RENDERPATH_GL13:
8648         case RENDERPATH_GL11:
8649                 break;
8650         }
8651 }
8652
8653 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
8654 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
8655 /*
8656 ================
8657 R_SelectScene
8658 ================
8659 */
8660 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
8661         if( scenetype != r_currentscenetype ) {
8662                 // store the old scenetype
8663                 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
8664                 r_currentscenetype = scenetype;
8665                 // move in the new scene
8666                 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
8667         }
8668 }
8669
8670 /*
8671 ================
8672 R_GetScenePointer
8673 ================
8674 */
8675 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
8676 {
8677         // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
8678         if( scenetype == r_currentscenetype ) {
8679                 return &r_refdef.scene;
8680         } else {
8681                 return &r_scenes_store[ scenetype ];
8682         }
8683 }
8684
8685 /*
8686 ================
8687 R_RenderView
8688 ================
8689 */
8690 void R_RenderView(void)
8691 {
8692         if (r_timereport_active)
8693                 R_TimeReport("start");
8694         r_textureframe++; // used only by R_GetCurrentTexture
8695         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
8696
8697         if (!r_drawentities.integer)
8698                 r_refdef.scene.numentities = 0;
8699
8700         R_AnimCache_ClearCache();
8701         R_FrameData_NewFrame();
8702
8703         if (r_refdef.view.isoverlay)
8704         {
8705                 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
8706                 GL_Clear( GL_DEPTH_BUFFER_BIT );
8707                 R_TimeReport("depthclear");
8708
8709                 r_refdef.view.showdebug = false;
8710
8711                 r_waterstate.enabled = false;
8712                 r_waterstate.numwaterplanes = 0;
8713
8714                 R_RenderScene();
8715
8716                 CHECKGLERROR
8717                 return;
8718         }
8719
8720         if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
8721                 return; //Host_Error ("R_RenderView: NULL worldmodel");
8722
8723         r_refdef.view.colorscale = r_hdr_scenebrightness.value;
8724
8725         R_RenderView_UpdateViewVectors();
8726
8727         R_Shadow_UpdateWorldLightSelection();
8728
8729         R_Bloom_StartFrame();
8730         R_Water_StartFrame();
8731
8732         CHECKGLERROR
8733         if (r_timereport_active)
8734                 R_TimeReport("viewsetup");
8735
8736         R_ResetViewRendering3D();
8737
8738         if (r_refdef.view.clear || r_refdef.fogenabled)
8739         {
8740                 R_ClearScreen(r_refdef.fogenabled);
8741                 if (r_timereport_active)
8742                         R_TimeReport("viewclear");
8743         }
8744         r_refdef.view.clear = true;
8745
8746         // this produces a bloom texture to be used in R_BlendView() later
8747         if (r_hdr.integer && r_bloomstate.bloomwidth)
8748         {
8749                 R_HDR_RenderBloomTexture();
8750                 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
8751                 r_textureframe++; // used only by R_GetCurrentTexture
8752         }
8753
8754         r_refdef.view.showdebug = true;
8755
8756         R_View_Update();
8757         if (r_timereport_active)
8758                 R_TimeReport("visibility");
8759
8760         r_waterstate.numwaterplanes = 0;
8761         if (r_waterstate.enabled)
8762                 R_RenderWaterPlanes();
8763
8764         R_RenderScene();
8765         r_waterstate.numwaterplanes = 0;
8766
8767         R_BlendView();
8768         if (r_timereport_active)
8769                 R_TimeReport("blendview");
8770
8771         GL_Scissor(0, 0, vid.width, vid.height);
8772         GL_ScissorTest(false);
8773
8774         CHECKGLERROR
8775 }
8776
8777 void R_RenderWaterPlanes(void)
8778 {
8779         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
8780         {
8781                 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
8782                 if (r_timereport_active)
8783                         R_TimeReport("waterworld");
8784         }
8785
8786         // don't let sound skip if going slow
8787         if (r_refdef.scene.extraupdate)
8788                 S_ExtraUpdate ();
8789
8790         R_DrawModelsAddWaterPlanes();
8791         if (r_timereport_active)
8792                 R_TimeReport("watermodels");
8793
8794         if (r_waterstate.numwaterplanes)
8795         {
8796                 R_Water_ProcessPlanes();
8797                 if (r_timereport_active)
8798                         R_TimeReport("waterscenes");
8799         }
8800 }
8801
8802 extern void R_DrawLightningBeams (void);
8803 extern void VM_CL_AddPolygonsToMeshQueue (void);
8804 extern void R_DrawPortals (void);
8805 extern cvar_t cl_locs_show;
8806 static void R_DrawLocs(void);
8807 static void R_DrawEntityBBoxes(void);
8808 static void R_DrawModelDecals(void);
8809 extern void R_DrawModelShadows(void);
8810 extern void R_DrawModelShadowMaps(void);
8811 extern cvar_t cl_decals_newsystem;
8812 extern qboolean r_shadow_usingdeferredprepass;
8813 void R_RenderScene(void)
8814 {
8815         qboolean shadowmapping = false;
8816
8817         if (r_timereport_active)
8818                 R_TimeReport("beginscene");
8819
8820         r_refdef.stats.renders++;
8821
8822         R_UpdateFogColor();
8823
8824         // don't let sound skip if going slow
8825         if (r_refdef.scene.extraupdate)
8826                 S_ExtraUpdate ();
8827
8828         R_MeshQueue_BeginScene();
8829
8830         R_SkyStartFrame();
8831
8832         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);
8833
8834         if (r_timereport_active)
8835                 R_TimeReport("skystartframe");
8836
8837         if (cl.csqc_vidvars.drawworld)
8838         {
8839                 // don't let sound skip if going slow
8840                 if (r_refdef.scene.extraupdate)
8841                         S_ExtraUpdate ();
8842
8843                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
8844                 {
8845                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
8846                         if (r_timereport_active)
8847                                 R_TimeReport("worldsky");
8848                 }
8849
8850                 if (R_DrawBrushModelsSky() && r_timereport_active)
8851                         R_TimeReport("bmodelsky");
8852
8853                 if (skyrendermasked && skyrenderlater)
8854                 {
8855                         // we have to force off the water clipping plane while rendering sky
8856                         R_SetupView(false);
8857                         R_Sky();
8858                         R_SetupView(true);
8859                         if (r_timereport_active)
8860                                 R_TimeReport("sky");
8861                 }
8862         }
8863
8864         R_AnimCache_CacheVisibleEntities();
8865         if (r_timereport_active)
8866                 R_TimeReport("animation");
8867
8868         R_Shadow_PrepareLights();
8869         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
8870                 R_Shadow_PrepareModelShadows();
8871         if (r_timereport_active)
8872                 R_TimeReport("preparelights");
8873
8874         if (R_Shadow_ShadowMappingEnabled())
8875                 shadowmapping = true;
8876
8877         if (r_shadow_usingdeferredprepass)
8878                 R_Shadow_DrawPrepass();
8879
8880         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
8881         {
8882                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
8883                 if (r_timereport_active)
8884                         R_TimeReport("worlddepth");
8885         }
8886         if (r_depthfirst.integer >= 2)
8887         {
8888                 R_DrawModelsDepth();
8889                 if (r_timereport_active)
8890                         R_TimeReport("modeldepth");
8891         }
8892
8893         if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
8894         {
8895                 R_DrawModelShadowMaps();
8896                 R_ResetViewRendering3D();
8897                 // don't let sound skip if going slow
8898                 if (r_refdef.scene.extraupdate)
8899                         S_ExtraUpdate ();
8900         }
8901
8902         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
8903         {
8904                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
8905                 if (r_timereport_active)
8906                         R_TimeReport("world");
8907         }
8908
8909         // don't let sound skip if going slow
8910         if (r_refdef.scene.extraupdate)
8911                 S_ExtraUpdate ();
8912
8913         R_DrawModels();
8914         if (r_timereport_active)
8915                 R_TimeReport("models");
8916
8917         // don't let sound skip if going slow
8918         if (r_refdef.scene.extraupdate)
8919                 S_ExtraUpdate ();
8920
8921         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8922         {
8923                 R_DrawModelShadows();
8924                 R_ResetViewRendering3D();
8925                 // don't let sound skip if going slow
8926                 if (r_refdef.scene.extraupdate)
8927                         S_ExtraUpdate ();
8928         }
8929
8930         if (!r_shadow_usingdeferredprepass)
8931         {
8932                 R_Shadow_DrawLights();
8933                 if (r_timereport_active)
8934                         R_TimeReport("rtlights");
8935         }
8936
8937         // don't let sound skip if going slow
8938         if (r_refdef.scene.extraupdate)
8939                 S_ExtraUpdate ();
8940
8941         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8942         {
8943                 R_DrawModelShadows();
8944                 R_ResetViewRendering3D();
8945                 // don't let sound skip if going slow
8946                 if (r_refdef.scene.extraupdate)
8947                         S_ExtraUpdate ();
8948         }
8949
8950         if (cl.csqc_vidvars.drawworld)
8951         {
8952                 if (cl_decals_newsystem.integer)
8953                 {
8954                         R_DrawModelDecals();
8955                         if (r_timereport_active)
8956                                 R_TimeReport("modeldecals");
8957                 }
8958                 else
8959                 {
8960                         R_DrawDecals();
8961                         if (r_timereport_active)
8962                                 R_TimeReport("decals");
8963                 }
8964
8965                 R_DrawParticles();
8966                 if (r_timereport_active)
8967                         R_TimeReport("particles");
8968
8969                 R_DrawExplosions();
8970                 if (r_timereport_active)
8971                         R_TimeReport("explosions");
8972
8973                 R_DrawLightningBeams();
8974                 if (r_timereport_active)
8975                         R_TimeReport("lightning");
8976         }
8977
8978         VM_CL_AddPolygonsToMeshQueue();
8979
8980         if (r_refdef.view.showdebug)
8981         {
8982                 if (cl_locs_show.integer)
8983                 {
8984                         R_DrawLocs();
8985                         if (r_timereport_active)
8986                                 R_TimeReport("showlocs");
8987                 }
8988
8989                 if (r_drawportals.integer)
8990                 {
8991                         R_DrawPortals();
8992                         if (r_timereport_active)
8993                                 R_TimeReport("portals");
8994                 }
8995
8996                 if (r_showbboxes.value > 0)
8997                 {
8998                         R_DrawEntityBBoxes();
8999                         if (r_timereport_active)
9000                                 R_TimeReport("bboxes");
9001                 }
9002         }
9003
9004         R_MeshQueue_RenderTransparent();
9005         if (r_timereport_active)
9006                 R_TimeReport("drawtrans");
9007
9008         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))
9009         {
9010                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9011                 if (r_timereport_active)
9012                         R_TimeReport("worlddebug");
9013                 R_DrawModelsDebug();
9014                 if (r_timereport_active)
9015                         R_TimeReport("modeldebug");
9016         }
9017
9018         if (cl.csqc_vidvars.drawworld)
9019         {
9020                 R_Shadow_DrawCoronas();
9021                 if (r_timereport_active)
9022                         R_TimeReport("coronas");
9023         }
9024
9025 #if 0
9026         {
9027                 GL_DepthTest(false);
9028                 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
9029                 GL_Color(1, 1, 1, 1);
9030                 qglBegin(GL_POLYGON);
9031                 qglVertex3f(r_refdef.view.frustumcorner[0][0], r_refdef.view.frustumcorner[0][1], r_refdef.view.frustumcorner[0][2]);
9032                 qglVertex3f(r_refdef.view.frustumcorner[1][0], r_refdef.view.frustumcorner[1][1], r_refdef.view.frustumcorner[1][2]);
9033                 qglVertex3f(r_refdef.view.frustumcorner[3][0], r_refdef.view.frustumcorner[3][1], r_refdef.view.frustumcorner[3][2]);
9034                 qglVertex3f(r_refdef.view.frustumcorner[2][0], r_refdef.view.frustumcorner[2][1], r_refdef.view.frustumcorner[2][2]);
9035                 qglEnd();
9036                 qglBegin(GL_POLYGON);
9037                 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]);
9038                 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]);
9039                 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]);
9040                 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]);
9041                 qglEnd();
9042                 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
9043         }
9044 #endif
9045
9046         // don't let sound skip if going slow
9047         if (r_refdef.scene.extraupdate)
9048                 S_ExtraUpdate ();
9049
9050         R_ResetViewRendering2D();
9051 }
9052
9053 static const unsigned short bboxelements[36] =
9054 {
9055         5, 1, 3, 5, 3, 7,
9056         6, 2, 0, 6, 0, 4,
9057         7, 3, 2, 7, 2, 6,
9058         4, 0, 1, 4, 1, 5,
9059         4, 5, 7, 4, 7, 6,
9060         1, 0, 2, 1, 2, 3,
9061 };
9062
9063 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9064 {
9065         int i;
9066         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9067
9068         RSurf_ActiveWorldEntity();
9069
9070         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9071         GL_DepthMask(false);
9072         GL_DepthRange(0, 1);
9073         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9074         R_Mesh_ResetTextureState();
9075
9076         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9077         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9078         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9079         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9080         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9081         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9082         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9083         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9084         R_FillColors(color4f, 8, cr, cg, cb, ca);
9085         if (r_refdef.fogenabled)
9086         {
9087                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9088                 {
9089                         f1 = RSurf_FogVertex(v);
9090                         f2 = 1 - f1;
9091                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9092                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9093                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9094                 }
9095         }
9096         R_Mesh_VertexPointer(vertex3f, 0, 0);
9097         R_Mesh_ColorPointer(color4f, 0, 0);
9098         R_Mesh_ResetTextureState();
9099         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9100         R_Mesh_Draw(0, 8, 0, 12, NULL, bboxelements, 0, 0);
9101 }
9102
9103 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9104 {
9105         int i;
9106         float color[4];
9107         prvm_edict_t *edict;
9108         prvm_prog_t *prog_save = prog;
9109
9110         // this function draws bounding boxes of server entities
9111         if (!sv.active)
9112                 return;
9113
9114         GL_CullFace(GL_NONE);
9115         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9116
9117         prog = 0;
9118         SV_VM_Begin();
9119         for (i = 0;i < numsurfaces;i++)
9120         {
9121                 edict = PRVM_EDICT_NUM(surfacelist[i]);
9122                 switch ((int)edict->fields.server->solid)
9123                 {
9124                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
9125                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
9126                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
9127                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9128                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
9129                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
9130                 }
9131                 color[3] *= r_showbboxes.value;
9132                 color[3] = bound(0, color[3], 1);
9133                 GL_DepthTest(!r_showdisabledepthtest.integer);
9134                 GL_CullFace(r_refdef.view.cullface_front);
9135                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9136         }
9137         SV_VM_End();
9138         prog = prog_save;
9139 }
9140
9141 static void R_DrawEntityBBoxes(void)
9142 {
9143         int i;
9144         prvm_edict_t *edict;
9145         vec3_t center;
9146         prvm_prog_t *prog_save = prog;
9147
9148         // this function draws bounding boxes of server entities
9149         if (!sv.active)
9150                 return;
9151
9152         prog = 0;
9153         SV_VM_Begin();
9154         for (i = 0;i < prog->num_edicts;i++)
9155         {
9156                 edict = PRVM_EDICT_NUM(i);
9157                 if (edict->priv.server->free)
9158                         continue;
9159                 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9160                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9161                         continue;
9162                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9163                         continue;
9164                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9165                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9166         }
9167         SV_VM_End();
9168         prog = prog_save;
9169 }
9170
9171 static const int nomodelelement3i[24] =
9172 {
9173         5, 2, 0,
9174         5, 1, 2,
9175         5, 0, 3,
9176         5, 3, 1,
9177         0, 2, 4,
9178         2, 1, 4,
9179         3, 0, 4,
9180         1, 3, 4
9181 };
9182
9183 static const unsigned short nomodelelement3s[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 float nomodelvertex3f[6*3] =
9196 {
9197         -16,   0,   0,
9198          16,   0,   0,
9199           0, -16,   0,
9200           0,  16,   0,
9201           0,   0, -16,
9202           0,   0,  16
9203 };
9204
9205 static const float nomodelcolor4f[6*4] =
9206 {
9207         0.0f, 0.0f, 0.5f, 1.0f,
9208         0.0f, 0.0f, 0.5f, 1.0f,
9209         0.0f, 0.5f, 0.0f, 1.0f,
9210         0.0f, 0.5f, 0.0f, 1.0f,
9211         0.5f, 0.0f, 0.0f, 1.0f,
9212         0.5f, 0.0f, 0.0f, 1.0f
9213 };
9214
9215 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9216 {
9217         int i;
9218         float f1, f2, *c;
9219         float color4f[6*4];
9220
9221         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);
9222
9223         // this is only called once per entity so numsurfaces is always 1, and
9224         // surfacelist is always {0}, so this code does not handle batches
9225
9226         if (rsurface.ent_flags & RENDER_ADDITIVE)
9227         {
9228                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9229                 GL_DepthMask(false);
9230         }
9231         else if (rsurface.colormod[3] < 1)
9232         {
9233                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9234                 GL_DepthMask(false);
9235         }
9236         else
9237         {
9238                 GL_BlendFunc(GL_ONE, GL_ZERO);
9239                 GL_DepthMask(true);
9240         }
9241         GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9242         GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9243         GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9244         GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9245         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9246         R_Mesh_VertexPointer(rsurface.vertex3f, rsurface.vertex3f_bufferobject, rsurface.vertex3f_bufferoffset);
9247         memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9248         R_Mesh_ColorPointer(color4f, 0, 0);
9249         for (i = 0, c = color4f;i < 6;i++, c += 4)
9250         {
9251                 c[0] *= rsurface.colormod[0];
9252                 c[1] *= rsurface.colormod[1];
9253                 c[2] *= rsurface.colormod[2];
9254                 c[3] *= rsurface.colormod[3];
9255         }
9256         if (r_refdef.fogenabled)
9257         {
9258                 for (i = 0, c = color4f;i < 6;i++, c += 4)
9259                 {
9260                         f1 = RSurf_FogVertex(rsurface.vertex3f + 3*i);
9261                         f2 = 1 - f1;
9262                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9263                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9264                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9265                 }
9266         }
9267         R_Mesh_ResetTextureState();
9268         R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, nomodelelement3s, 0, 0);
9269 }
9270
9271 void R_DrawNoModel(entity_render_t *ent)
9272 {
9273         vec3_t org;
9274         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9275         if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9276                 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9277         else
9278                 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9279 }
9280
9281 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9282 {
9283         vec3_t right1, right2, diff, normal;
9284
9285         VectorSubtract (org2, org1, normal);
9286
9287         // calculate 'right' vector for start
9288         VectorSubtract (r_refdef.view.origin, org1, diff);
9289         CrossProduct (normal, diff, right1);
9290         VectorNormalize (right1);
9291
9292         // calculate 'right' vector for end
9293         VectorSubtract (r_refdef.view.origin, org2, diff);
9294         CrossProduct (normal, diff, right2);
9295         VectorNormalize (right2);
9296
9297         vert[ 0] = org1[0] + width * right1[0];
9298         vert[ 1] = org1[1] + width * right1[1];
9299         vert[ 2] = org1[2] + width * right1[2];
9300         vert[ 3] = org1[0] - width * right1[0];
9301         vert[ 4] = org1[1] - width * right1[1];
9302         vert[ 5] = org1[2] - width * right1[2];
9303         vert[ 6] = org2[0] - width * right2[0];
9304         vert[ 7] = org2[1] - width * right2[1];
9305         vert[ 8] = org2[2] - width * right2[2];
9306         vert[ 9] = org2[0] + width * right2[0];
9307         vert[10] = org2[1] + width * right2[1];
9308         vert[11] = org2[2] + width * right2[2];
9309 }
9310
9311 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)
9312 {
9313         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9314         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9315         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9316         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9317         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9318         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9319         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9320         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9321         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9322         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9323         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9324         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9325 }
9326
9327 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9328 {
9329         int i;
9330         float *vertex3f;
9331         float v[3];
9332         VectorSet(v, x, y, z);
9333         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9334                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9335                         break;
9336         if (i == mesh->numvertices)
9337         {
9338                 if (mesh->numvertices < mesh->maxvertices)
9339                 {
9340                         VectorCopy(v, vertex3f);
9341                         mesh->numvertices++;
9342                 }
9343                 return mesh->numvertices;
9344         }
9345         else
9346                 return i;
9347 }
9348
9349 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9350 {
9351         int i;
9352         int *e, element[3];
9353         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9354         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9355         e = mesh->element3i + mesh->numtriangles * 3;
9356         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9357         {
9358                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9359                 if (mesh->numtriangles < mesh->maxtriangles)
9360                 {
9361                         *e++ = element[0];
9362                         *e++ = element[1];
9363                         *e++ = element[2];
9364                         mesh->numtriangles++;
9365                 }
9366                 element[1] = element[2];
9367         }
9368 }
9369
9370 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9371 {
9372         int i;
9373         int *e, element[3];
9374         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9375         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9376         e = mesh->element3i + mesh->numtriangles * 3;
9377         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9378         {
9379                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9380                 if (mesh->numtriangles < mesh->maxtriangles)
9381                 {
9382                         *e++ = element[0];
9383                         *e++ = element[1];
9384                         *e++ = element[2];
9385                         mesh->numtriangles++;
9386                 }
9387                 element[1] = element[2];
9388         }
9389 }
9390
9391 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9392 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9393 {
9394         int planenum, planenum2;
9395         int w;
9396         int tempnumpoints;
9397         mplane_t *plane, *plane2;
9398         double maxdist;
9399         double temppoints[2][256*3];
9400         // figure out how large a bounding box we need to properly compute this brush
9401         maxdist = 0;
9402         for (w = 0;w < numplanes;w++)
9403                 maxdist = max(maxdist, fabs(planes[w].dist));
9404         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9405         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9406         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9407         {
9408                 w = 0;
9409                 tempnumpoints = 4;
9410                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9411                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9412                 {
9413                         if (planenum2 == planenum)
9414                                 continue;
9415                         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);
9416                         w = !w;
9417                 }
9418                 if (tempnumpoints < 3)
9419                         continue;
9420                 // generate elements forming a triangle fan for this polygon
9421                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9422         }
9423 }
9424
9425 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)
9426 {
9427         texturelayer_t *layer;
9428         layer = t->currentlayers + t->currentnumlayers++;
9429         layer->type = type;
9430         layer->depthmask = depthmask;
9431         layer->blendfunc1 = blendfunc1;
9432         layer->blendfunc2 = blendfunc2;
9433         layer->texture = texture;
9434         layer->texmatrix = *matrix;
9435         layer->color[0] = r;
9436         layer->color[1] = g;
9437         layer->color[2] = b;
9438         layer->color[3] = a;
9439 }
9440
9441 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
9442 {
9443         if(parms[0] == 0 && parms[1] == 0)
9444                 return false;
9445         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9446                 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
9447                         return false;
9448         return true;
9449 }
9450
9451 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9452 {
9453         double index, f;
9454         index = parms[2] + r_refdef.scene.time * parms[3];
9455         index -= floor(index);
9456         switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
9457         {
9458         default:
9459         case Q3WAVEFUNC_NONE:
9460         case Q3WAVEFUNC_NOISE:
9461         case Q3WAVEFUNC_COUNT:
9462                 f = 0;
9463                 break;
9464         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
9465         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
9466         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
9467         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
9468         case Q3WAVEFUNC_TRIANGLE:
9469                 index *= 4;
9470                 f = index - floor(index);
9471                 if (index < 1)
9472                         f = f;
9473                 else if (index < 2)
9474                         f = 1 - f;
9475                 else if (index < 3)
9476                         f = -f;
9477                 else
9478                         f = -(1 - f);
9479                 break;
9480         }
9481         f = parms[0] + parms[1] * f;
9482         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9483                 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
9484         return (float) f;
9485 }
9486
9487 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
9488 {
9489         int w, h, idx;
9490         float f;
9491         float tcmat[12];
9492         matrix4x4_t matrix, temp;
9493         switch(tcmod->tcmod)
9494         {
9495                 case Q3TCMOD_COUNT:
9496                 case Q3TCMOD_NONE:
9497                         if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9498                                 matrix = r_waterscrollmatrix;
9499                         else
9500                                 matrix = identitymatrix;
9501                         break;
9502                 case Q3TCMOD_ENTITYTRANSLATE:
9503                         // this is used in Q3 to allow the gamecode to control texcoord
9504                         // scrolling on the entity, which is not supported in darkplaces yet.
9505                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
9506                         break;
9507                 case Q3TCMOD_ROTATE:
9508                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
9509                         Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
9510                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
9511                         break;
9512                 case Q3TCMOD_SCALE:
9513                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
9514                         break;
9515                 case Q3TCMOD_SCROLL:
9516                         Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
9517                         break;
9518                 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
9519                         w = (int) tcmod->parms[0];
9520                         h = (int) tcmod->parms[1];
9521                         f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
9522                         f = f - floor(f);
9523                         idx = (int) floor(f * w * h);
9524                         Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
9525                         break;
9526                 case Q3TCMOD_STRETCH:
9527                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
9528                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
9529                         break;
9530                 case Q3TCMOD_TRANSFORM:
9531                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
9532                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
9533                         VectorSet(tcmat +  6, 0                   , 0                , 1);
9534                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
9535                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
9536                         break;
9537                 case Q3TCMOD_TURBULENT:
9538                         // this is handled in the RSurf_PrepareVertices function
9539                         matrix = identitymatrix;
9540                         break;
9541         }
9542         temp = *texmatrix;
9543         Matrix4x4_Concat(texmatrix, &matrix, &temp);
9544 }
9545
9546 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
9547 {
9548         int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
9549         char name[MAX_QPATH];
9550         skinframe_t *skinframe;
9551         unsigned char pixels[296*194];
9552         strlcpy(cache->name, skinname, sizeof(cache->name));
9553         dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
9554         if (developer_loading.integer)
9555                 Con_Printf("loading %s\n", name);
9556         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
9557         if (!skinframe || !skinframe->base)
9558         {
9559                 unsigned char *f;
9560                 fs_offset_t filesize;
9561                 skinframe = NULL;
9562                 f = FS_LoadFile(name, tempmempool, true, &filesize);
9563                 if (f)
9564                 {
9565                         if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
9566                                 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
9567                         Mem_Free(f);
9568                 }
9569         }
9570         cache->skinframe = skinframe;
9571 }
9572
9573 texture_t *R_GetCurrentTexture(texture_t *t)
9574 {
9575         int i;
9576         const entity_render_t *ent = rsurface.entity;
9577         dp_model_t *model = ent->model;
9578         q3shaderinfo_layer_tcmod_t *tcmod;
9579
9580         if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
9581                 return t->currentframe;
9582         t->update_lastrenderframe = r_textureframe;
9583         t->update_lastrenderentity = (void *)ent;
9584
9585         if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
9586                 t->camera_entity = ent->entitynumber;
9587         else
9588                 t->camera_entity = 0;
9589
9590         // switch to an alternate material if this is a q1bsp animated material
9591         {
9592                 texture_t *texture = t;
9593                 int s = rsurface.ent_skinnum;
9594                 if ((unsigned int)s >= (unsigned int)model->numskins)
9595                         s = 0;
9596                 if (model->skinscenes)
9597                 {
9598                         if (model->skinscenes[s].framecount > 1)
9599                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
9600                         else
9601                                 s = model->skinscenes[s].firstframe;
9602                 }
9603                 if (s > 0)
9604                         t = t + s * model->num_surfaces;
9605                 if (t->animated)
9606                 {
9607                         // use an alternate animation if the entity's frame is not 0,
9608                         // and only if the texture has an alternate animation
9609                         if (rsurface.ent_alttextures && t->anim_total[1])
9610                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
9611                         else
9612                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
9613                 }
9614                 texture->currentframe = t;
9615         }
9616
9617         // update currentskinframe to be a qw skin or animation frame
9618         if (rsurface.ent_qwskin >= 0)
9619         {
9620                 i = rsurface.ent_qwskin;
9621                 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
9622                 {
9623                         r_qwskincache_size = cl.maxclients;
9624                         if (r_qwskincache)
9625                                 Mem_Free(r_qwskincache);
9626                         r_qwskincache = Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
9627                 }
9628                 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
9629                         R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
9630                 t->currentskinframe = r_qwskincache[i].skinframe;
9631                 if (t->currentskinframe == NULL)
9632                         t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9633         }
9634         else if (t->numskinframes >= 2)
9635                 t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9636         if (t->backgroundnumskinframes >= 2)
9637                 t->backgroundcurrentskinframe = t->backgroundskinframes[(unsigned int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
9638
9639         t->currentmaterialflags = t->basematerialflags;
9640         t->currentalpha = rsurface.colormod[3];
9641         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
9642                 t->currentalpha *= r_wateralpha.value;
9643         if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
9644                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW; // we apply wateralpha later
9645         if(!r_waterstate.enabled || r_refdef.view.isoverlay)
9646                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
9647         if (!(rsurface.ent_flags & RENDER_LIGHT))
9648                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
9649         else if (FAKELIGHT_ENABLED)
9650         {
9651                         // no modellight if using fakelight for the map
9652         }
9653         else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
9654         {
9655                 // pick a model lighting mode
9656                 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
9657                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
9658                 else
9659                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
9660         }
9661         if (rsurface.ent_flags & RENDER_ADDITIVE)
9662                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9663         else if (t->currentalpha < 1)
9664                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9665         if (rsurface.ent_flags & RENDER_DOUBLESIDED)
9666                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
9667         if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
9668                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
9669         if (t->backgroundnumskinframes)
9670                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
9671         if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
9672         {
9673                 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
9674                         t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
9675         }
9676         else
9677                 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
9678         if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
9679                 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
9680
9681         // there is no tcmod
9682         if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9683         {
9684                 t->currenttexmatrix = r_waterscrollmatrix;
9685                 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
9686         }
9687         else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
9688         {
9689                 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
9690                 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
9691         }
9692
9693         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9694                 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
9695         for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9696                 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
9697
9698         t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
9699         if (t->currentskinframe->qpixels)
9700                 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
9701         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
9702         if (!t->basetexture)
9703                 t->basetexture = r_texture_notexture;
9704         t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
9705         t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
9706         t->nmaptexture = t->currentskinframe->nmap;
9707         if (!t->nmaptexture)
9708                 t->nmaptexture = r_texture_blanknormalmap;
9709         t->glosstexture = r_texture_black;
9710         t->glowtexture = t->currentskinframe->glow;
9711         t->fogtexture = t->currentskinframe->fog;
9712         t->reflectmasktexture = t->currentskinframe->reflect;
9713         if (t->backgroundnumskinframes)
9714         {
9715                 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
9716                 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
9717                 t->backgroundglosstexture = r_texture_black;
9718                 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
9719                 if (!t->backgroundnmaptexture)
9720                         t->backgroundnmaptexture = r_texture_blanknormalmap;
9721         }
9722         else
9723         {
9724                 t->backgroundbasetexture = t->backgroundnumskinframes ? ((!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base) : r_texture_white;
9725                 t->backgroundnmaptexture = r_texture_blanknormalmap;
9726                 t->backgroundglosstexture = r_texture_black;
9727                 t->backgroundglowtexture = NULL;
9728         }
9729         t->specularpower = r_shadow_glossexponent.value;
9730         // TODO: store reference values for these in the texture?
9731         t->specularscale = 0;
9732         if (r_shadow_gloss.integer > 0)
9733         {
9734                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
9735                 {
9736                         if (r_shadow_glossintensity.value > 0)
9737                         {
9738                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
9739                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
9740                                 t->specularscale = r_shadow_glossintensity.value;
9741                         }
9742                 }
9743                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
9744                 {
9745                         t->glosstexture = r_texture_white;
9746                         t->backgroundglosstexture = r_texture_white;
9747                         t->specularscale = r_shadow_gloss2intensity.value;
9748                         t->specularpower = r_shadow_gloss2exponent.value;
9749                 }
9750         }
9751         t->specularscale *= t->specularscalemod;
9752         t->specularpower *= t->specularpowermod;
9753
9754         // lightmaps mode looks bad with dlights using actual texturing, so turn
9755         // off the colormap and glossmap, but leave the normalmap on as it still
9756         // accurately represents the shading involved
9757         if (gl_lightmaps.integer)
9758         {
9759                 t->basetexture = r_texture_grey128;
9760                 t->pantstexture = r_texture_black;
9761                 t->shirttexture = r_texture_black;
9762                 t->nmaptexture = r_texture_blanknormalmap;
9763                 t->glosstexture = r_texture_black;
9764                 t->glowtexture = NULL;
9765                 t->fogtexture = NULL;
9766                 t->reflectmasktexture = NULL;
9767                 t->backgroundbasetexture = NULL;
9768                 t->backgroundnmaptexture = r_texture_blanknormalmap;
9769                 t->backgroundglosstexture = r_texture_black;
9770                 t->backgroundglowtexture = NULL;
9771                 t->specularscale = 0;
9772                 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
9773         }
9774
9775         Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
9776         VectorClear(t->dlightcolor);
9777         t->currentnumlayers = 0;
9778         if (t->currentmaterialflags & MATERIALFLAG_WALL)
9779         {
9780                 int blendfunc1, blendfunc2;
9781                 qboolean depthmask;
9782                 if (t->currentmaterialflags & MATERIALFLAG_ADD)
9783                 {
9784                         blendfunc1 = GL_SRC_ALPHA;
9785                         blendfunc2 = GL_ONE;
9786                 }
9787                 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
9788                 {
9789                         blendfunc1 = GL_SRC_ALPHA;
9790                         blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
9791                 }
9792                 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
9793                 {
9794                         blendfunc1 = t->customblendfunc[0];
9795                         blendfunc2 = t->customblendfunc[1];
9796                 }
9797                 else
9798                 {
9799                         blendfunc1 = GL_ONE;
9800                         blendfunc2 = GL_ZERO;
9801                 }
9802                 // don't colormod evilblend textures
9803                 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
9804                         VectorSet(t->lightmapcolor, 1, 1, 1);
9805                 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
9806                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
9807                 {
9808                         // fullbright is not affected by r_refdef.lightmapintensity
9809                         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]);
9810                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9811                                 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]);
9812                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9813                                 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]);
9814                 }
9815                 else
9816                 {
9817                         vec3_t ambientcolor;
9818                         float colorscale;
9819                         // set the color tint used for lights affecting this surface
9820                         VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
9821                         colorscale = 2;
9822                         // q3bsp has no lightmap updates, so the lightstylevalue that
9823                         // would normally be baked into the lightmap must be
9824                         // applied to the color
9825                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
9826                         if (model->type == mod_brushq3)
9827                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
9828                         colorscale *= r_refdef.lightmapintensity;
9829                         VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
9830                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
9831                         // basic lit geometry
9832                         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]);
9833                         // add pants/shirt if needed
9834                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9835                                 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]);
9836                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9837                                 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]);
9838                         // now add ambient passes if needed
9839                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
9840                         {
9841                                 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]);
9842                                 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9843                                         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]);
9844                                 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9845                                         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]);
9846                         }
9847                 }
9848                 if (t->glowtexture != NULL && !gl_lightmaps.integer)
9849                         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]);
9850                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
9851                 {
9852                         // if this is opaque use alpha blend which will darken the earlier
9853                         // passes cheaply.
9854                         //
9855                         // if this is an alpha blended material, all the earlier passes
9856                         // were darkened by fog already, so we only need to add the fog
9857                         // color ontop through the fog mask texture
9858                         //
9859                         // if this is an additive blended material, all the earlier passes
9860                         // were darkened by fog already, and we should not add fog color
9861                         // (because the background was not darkened, there is no fog color
9862                         // that was lost behind it).
9863                         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]);
9864                 }
9865         }
9866
9867         return t->currentframe;
9868 }
9869
9870 rsurfacestate_t rsurface;
9871
9872 void R_Mesh_ResizeArrays(int newvertices)
9873 {
9874         float *base;
9875         if (rsurface.array_size >= newvertices)
9876                 return;
9877         if (rsurface.array_modelvertex3f)
9878                 Mem_Free(rsurface.array_modelvertex3f);
9879         rsurface.array_size = (newvertices + 1023) & ~1023;
9880         base = (float *)Mem_Alloc(r_main_mempool, rsurface.array_size * sizeof(float[33]));
9881         rsurface.array_modelvertex3f     = base + rsurface.array_size * 0;
9882         rsurface.array_modelsvector3f    = base + rsurface.array_size * 3;
9883         rsurface.array_modeltvector3f    = base + rsurface.array_size * 6;
9884         rsurface.array_modelnormal3f     = base + rsurface.array_size * 9;
9885         rsurface.array_deformedvertex3f  = base + rsurface.array_size * 12;
9886         rsurface.array_deformedsvector3f = base + rsurface.array_size * 15;
9887         rsurface.array_deformedtvector3f = base + rsurface.array_size * 18;
9888         rsurface.array_deformednormal3f  = base + rsurface.array_size * 21;
9889         rsurface.array_texcoord3f        = base + rsurface.array_size * 24;
9890         rsurface.array_color4f           = base + rsurface.array_size * 27;
9891         rsurface.array_generatedtexcoordtexture2f = base + rsurface.array_size * 31;
9892 }
9893
9894 void RSurf_ActiveWorldEntity(void)
9895 {
9896         dp_model_t *model = r_refdef.scene.worldmodel;
9897         //if (rsurface.entity == r_refdef.scene.worldentity)
9898         //      return;
9899         rsurface.entity = r_refdef.scene.worldentity;
9900         rsurface.skeleton = NULL;
9901         memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
9902         rsurface.ent_skinnum = 0;
9903         rsurface.ent_qwskin = -1;
9904         rsurface.ent_shadertime = 0;
9905         rsurface.ent_flags = r_refdef.scene.worldentity->flags;
9906         if (rsurface.array_size < model->surfmesh.num_vertices)
9907                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9908         rsurface.matrix = identitymatrix;
9909         rsurface.inversematrix = identitymatrix;
9910         rsurface.matrixscale = 1;
9911         rsurface.inversematrixscale = 1;
9912         R_EntityMatrix(&identitymatrix);
9913         VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
9914         Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
9915         rsurface.fograngerecip = r_refdef.fograngerecip;
9916         rsurface.fogheightfade = r_refdef.fogheightfade;
9917         rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
9918         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9919         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9920         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9921         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9922         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9923         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9924         VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
9925         rsurface.colormod[3] = 1;
9926         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);
9927         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9928         rsurface.frameblend[0].lerp = 1;
9929         rsurface.ent_alttextures = false;
9930         rsurface.basepolygonfactor = r_refdef.polygonfactor;
9931         rsurface.basepolygonoffset = r_refdef.polygonoffset;
9932         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
9933         rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
9934         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9935         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9936         rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
9937         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9938         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9939         rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
9940         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9941         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
9942         rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
9943         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9944         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
9945         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
9946         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9947         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
9948         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
9949         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9950         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
9951         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
9952         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9953         rsurface.modelelement3i = model->surfmesh.data_element3i;
9954         rsurface.modelelement3s = model->surfmesh.data_element3s;
9955         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo3i;
9956         rsurface.modelelement3s_bufferobject = model->surfmesh.ebo3s;
9957         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9958         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
9959         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
9960         rsurface.modelsurfaces = model->data_surfaces;
9961         rsurface.generatedvertex = false;
9962         rsurface.vertex3f  = rsurface.modelvertex3f;
9963         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
9964         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
9965         rsurface.svector3f = rsurface.modelsvector3f;
9966         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
9967         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
9968         rsurface.tvector3f = rsurface.modeltvector3f;
9969         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
9970         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
9971         rsurface.normal3f  = rsurface.modelnormal3f;
9972         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
9973         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
9974         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
9975 }
9976
9977 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
9978 {
9979         dp_model_t *model = ent->model;
9980         //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
9981         //      return;
9982         rsurface.entity = (entity_render_t *)ent;
9983         rsurface.skeleton = ent->skeleton;
9984         memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
9985         rsurface.ent_skinnum = ent->skinnum;
9986         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;
9987         rsurface.ent_shadertime = ent->shadertime;
9988         rsurface.ent_flags = ent->flags;
9989         if (rsurface.array_size < model->surfmesh.num_vertices)
9990                 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9991         rsurface.matrix = ent->matrix;
9992         rsurface.inversematrix = ent->inversematrix;
9993         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9994         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9995         R_EntityMatrix(&rsurface.matrix);
9996         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9997         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9998         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9999         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10000         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10001         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10002         VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10003         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10004         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10005         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10006         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10007         VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10008         rsurface.colormod[3] = ent->alpha;
10009         VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10010         memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10011         rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10012         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10013         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10014         if (ent->model->brush.submodel && !prepass)
10015         {
10016                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10017                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10018         }
10019         if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10020         {
10021                 if (ent->animcache_vertex3f && !r_framedata_failed)
10022                 {
10023                         rsurface.modelvertex3f = ent->animcache_vertex3f;
10024                         rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10025                         rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10026                         rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10027                 }
10028                 else if (wanttangents)
10029                 {
10030                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10031                         rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10032                         rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10033                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10034                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
10035                 }
10036                 else if (wantnormals)
10037                 {
10038                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10039                         rsurface.modelsvector3f = NULL;
10040                         rsurface.modeltvector3f = NULL;
10041                         rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10042                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
10043                 }
10044                 else
10045                 {
10046                         rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10047                         rsurface.modelsvector3f = NULL;
10048                         rsurface.modeltvector3f = NULL;
10049                         rsurface.modelnormal3f = NULL;
10050                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
10051                 }
10052                 rsurface.modelvertex3f_bufferobject = 0;
10053                 rsurface.modelvertex3f_bufferoffset = 0;
10054                 rsurface.modelsvector3f_bufferobject = 0;
10055                 rsurface.modelsvector3f_bufferoffset = 0;
10056                 rsurface.modeltvector3f_bufferobject = 0;
10057                 rsurface.modeltvector3f_bufferoffset = 0;
10058                 rsurface.modelnormal3f_bufferobject = 0;
10059                 rsurface.modelnormal3f_bufferoffset = 0;
10060                 rsurface.generatedvertex = true;
10061         }
10062         else
10063         {
10064                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
10065                 rsurface.modelvertex3f_bufferobject = model->surfmesh.vbo;
10066                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10067                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10068                 rsurface.modelsvector3f_bufferobject = model->surfmesh.vbo;
10069                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10070                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10071                 rsurface.modeltvector3f_bufferobject = model->surfmesh.vbo;
10072                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10073                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
10074                 rsurface.modelnormal3f_bufferobject = model->surfmesh.vbo;
10075                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10076                 rsurface.generatedvertex = false;
10077         }
10078         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
10079         rsurface.modellightmapcolor4f_bufferobject = model->surfmesh.vbo;
10080         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10081         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
10082         rsurface.modeltexcoordtexture2f_bufferobject = model->surfmesh.vbo;
10083         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10084         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
10085         rsurface.modeltexcoordlightmap2f_bufferobject = model->surfmesh.vbo;
10086         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10087         rsurface.modelelement3i = model->surfmesh.data_element3i;
10088         rsurface.modelelement3s = model->surfmesh.data_element3s;
10089         rsurface.modelelement3i_bufferobject = model->surfmesh.ebo3i;
10090         rsurface.modelelement3s_bufferobject = model->surfmesh.ebo3s;
10091         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10092         rsurface.modelnum_vertices = model->surfmesh.num_vertices;
10093         rsurface.modelnum_triangles = model->surfmesh.num_triangles;
10094         rsurface.modelsurfaces = model->data_surfaces;
10095         rsurface.vertex3f  = rsurface.modelvertex3f;
10096         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
10097         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10098         rsurface.svector3f = rsurface.modelsvector3f;
10099         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
10100         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10101         rsurface.tvector3f = rsurface.modeltvector3f;
10102         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
10103         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10104         rsurface.normal3f  = rsurface.modelnormal3f;
10105         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
10106         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10107         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
10108 }
10109
10110 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)
10111 {
10112         rsurface.entity = r_refdef.scene.worldentity;
10113         rsurface.skeleton = NULL;
10114         rsurface.ent_skinnum = 0;
10115         rsurface.ent_qwskin = -1;
10116         rsurface.ent_shadertime = shadertime;
10117         rsurface.ent_flags = entflags;
10118         rsurface.modelnum_vertices = numvertices;
10119         rsurface.modelnum_triangles = numtriangles;
10120         if (rsurface.array_size < rsurface.modelnum_vertices)
10121                 R_Mesh_ResizeArrays(rsurface.modelnum_vertices);
10122         rsurface.matrix = *matrix;
10123         rsurface.inversematrix = *inversematrix;
10124         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10125         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10126         R_EntityMatrix(&rsurface.matrix);
10127         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10128         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10129         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10130         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10131         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10132         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10133         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10134         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10135         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10136         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10137         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10138         Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10139         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);
10140         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10141         rsurface.frameblend[0].lerp = 1;
10142         rsurface.ent_alttextures = false;
10143         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10144         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10145         if (wanttangents)
10146         {
10147                 rsurface.modelvertex3f = vertex3f;
10148                 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
10149                 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
10150                 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10151         }
10152         else if (wantnormals)
10153         {
10154                 rsurface.modelvertex3f = vertex3f;
10155                 rsurface.modelsvector3f = NULL;
10156                 rsurface.modeltvector3f = NULL;
10157                 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10158         }
10159         else
10160         {
10161                 rsurface.modelvertex3f = vertex3f;
10162                 rsurface.modelsvector3f = NULL;
10163                 rsurface.modeltvector3f = NULL;
10164                 rsurface.modelnormal3f = NULL;
10165         }
10166         rsurface.modelvertex3f_bufferobject = 0;
10167         rsurface.modelvertex3f_bufferoffset = 0;
10168         rsurface.modelsvector3f_bufferobject = 0;
10169         rsurface.modelsvector3f_bufferoffset = 0;
10170         rsurface.modeltvector3f_bufferobject = 0;
10171         rsurface.modeltvector3f_bufferoffset = 0;
10172         rsurface.modelnormal3f_bufferobject = 0;
10173         rsurface.modelnormal3f_bufferoffset = 0;
10174         rsurface.generatedvertex = true;
10175         rsurface.modellightmapcolor4f  = color4f;
10176         rsurface.modellightmapcolor4f_bufferobject = 0;
10177         rsurface.modellightmapcolor4f_bufferoffset = 0;
10178         rsurface.modeltexcoordtexture2f  = texcoord2f;
10179         rsurface.modeltexcoordtexture2f_bufferobject = 0;
10180         rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10181         rsurface.modeltexcoordlightmap2f  = NULL;
10182         rsurface.modeltexcoordlightmap2f_bufferobject = 0;
10183         rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10184         rsurface.modelelement3i = element3i;
10185         rsurface.modelelement3s = element3s;
10186         rsurface.modelelement3i_bufferobject = 0;
10187         rsurface.modelelement3s_bufferobject = 0;
10188         rsurface.modellightmapoffsets = NULL;
10189         rsurface.modelsurfaces = NULL;
10190         rsurface.vertex3f  = rsurface.modelvertex3f;
10191         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
10192         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10193         rsurface.svector3f = rsurface.modelsvector3f;
10194         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
10195         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10196         rsurface.tvector3f = rsurface.modeltvector3f;
10197         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
10198         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10199         rsurface.normal3f  = rsurface.modelnormal3f;
10200         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
10201         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10202         rsurface.texcoordtexture2f = rsurface.modeltexcoordtexture2f;
10203
10204         if (rsurface.modelnum_vertices && rsurface.modelelement3i)
10205         {
10206                 if ((wantnormals || wanttangents) && !normal3f)
10207                         Mod_BuildNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10208                 if (wanttangents && !svector3f)
10209                         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);
10210         }
10211 }
10212
10213 float RSurf_FogPoint(const float *v)
10214 {
10215         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10216         float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10217         float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10218         float FogHeightFade = r_refdef.fogheightfade;
10219         float fogfrac;
10220         unsigned int fogmasktableindex;
10221         if (r_refdef.fogplaneviewabove)
10222                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10223         else
10224                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10225         fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10226         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10227 }
10228
10229 float RSurf_FogVertex(const float *v)
10230 {
10231         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10232         float FogPlaneViewDist = rsurface.fogplaneviewdist;
10233         float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10234         float FogHeightFade = rsurface.fogheightfade;
10235         float fogfrac;
10236         unsigned int fogmasktableindex;
10237         if (r_refdef.fogplaneviewabove)
10238                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10239         else
10240                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10241         fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10242         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10243 }
10244
10245 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10246 void RSurf_PrepareVerticesForBatch(qboolean generatenormals, qboolean generatetangents, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10247 {
10248         int deformindex;
10249         int texturesurfaceindex;
10250         int i, j;
10251         float amplitude;
10252         float animpos;
10253         float scale;
10254         const float *v1, *in_tc;
10255         float *out_tc;
10256         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10257         float waveparms[4];
10258         q3shaderinfo_deform_t *deform;
10259         // 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
10260         if (rsurface.generatedvertex)
10261         {
10262                 if (rsurface.texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
10263                         generatenormals = true;
10264                 for (i = 0;i < Q3MAXDEFORMS;i++)
10265                 {
10266                         if (rsurface.texture->deforms[i].deform == Q3DEFORM_AUTOSPRITE)
10267                         {
10268                                 generatetangents = true;
10269                                 generatenormals = true;
10270                         }
10271                         if (rsurface.texture->deforms[i].deform != Q3DEFORM_NONE)
10272                                 generatenormals = true;
10273                 }
10274                 if (generatenormals && !rsurface.modelnormal3f)
10275                 {
10276                         rsurface.normal3f = rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10277                         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject = 0;
10278                         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset = 0;
10279                         Mod_BuildNormals(0, rsurface.modelnum_vertices, rsurface.modelnum_triangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10280                 }
10281                 if (generatetangents && !rsurface.modelsvector3f)
10282                 {
10283                         rsurface.svector3f = rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10284                         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject = 0;
10285                         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset = 0;
10286                         rsurface.tvector3f = rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10287                         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject = 0;
10288                         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset = 0;
10289                         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);
10290                 }
10291         }
10292         rsurface.vertex3f  = rsurface.modelvertex3f;
10293         rsurface.vertex3f_bufferobject = rsurface.modelvertex3f_bufferobject;
10294         rsurface.vertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10295         rsurface.svector3f = rsurface.modelsvector3f;
10296         rsurface.svector3f_bufferobject = rsurface.modelsvector3f_bufferobject;
10297         rsurface.svector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10298         rsurface.tvector3f = rsurface.modeltvector3f;
10299         rsurface.tvector3f_bufferobject = rsurface.modeltvector3f_bufferobject;
10300         rsurface.tvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10301         rsurface.normal3f  = rsurface.modelnormal3f;
10302         rsurface.normal3f_bufferobject = rsurface.modelnormal3f_bufferobject;
10303         rsurface.normal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10304         // if vertices are deformed (sprite flares and things in maps, possibly
10305         // water waves, bulges and other deformations), generate them into
10306         // rsurface.deform* arrays from whatever the rsurface.* arrays point to
10307         // (may be static model data or generated data for an animated model, or
10308         //  the previous deform pass)
10309         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10310         {
10311                 switch (deform->deform)
10312                 {
10313                 default:
10314                 case Q3DEFORM_PROJECTIONSHADOW:
10315                 case Q3DEFORM_TEXT0:
10316                 case Q3DEFORM_TEXT1:
10317                 case Q3DEFORM_TEXT2:
10318                 case Q3DEFORM_TEXT3:
10319                 case Q3DEFORM_TEXT4:
10320                 case Q3DEFORM_TEXT5:
10321                 case Q3DEFORM_TEXT6:
10322                 case Q3DEFORM_TEXT7:
10323                 case Q3DEFORM_NONE:
10324                         break;
10325                 case Q3DEFORM_AUTOSPRITE:
10326                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10327                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10328                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10329                         VectorNormalize(newforward);
10330                         VectorNormalize(newright);
10331                         VectorNormalize(newup);
10332                         // make deformed versions of only the model vertices used by the specified surfaces
10333                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10334                         {
10335                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10336                                 // a single autosprite surface can contain multiple sprites...
10337                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
10338                                 {
10339                                         VectorClear(center);
10340                                         for (i = 0;i < 4;i++)
10341                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
10342                                         VectorScale(center, 0.25f, center);
10343                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, forward);
10344                                         VectorCopy((rsurface.svector3f + 3 * surface->num_firstvertex) + j*3, right);
10345                                         VectorCopy((rsurface.tvector3f + 3 * surface->num_firstvertex) + j*3, up);
10346                                         for (i = 0;i < 4;i++)
10347                                         {
10348                                                 VectorSubtract((rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i)*3, center, v);
10349                                                 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
10350                                         }
10351                                 }
10352                                 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);
10353                                 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);
10354                         }
10355                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10356                         rsurface.vertex3f_bufferobject = 0;
10357                         rsurface.vertex3f_bufferoffset = 0;
10358                         rsurface.svector3f = rsurface.array_deformedsvector3f;
10359                         rsurface.svector3f_bufferobject = 0;
10360                         rsurface.svector3f_bufferoffset = 0;
10361                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
10362                         rsurface.tvector3f_bufferobject = 0;
10363                         rsurface.tvector3f_bufferoffset = 0;
10364                         rsurface.normal3f = rsurface.array_deformednormal3f;
10365                         rsurface.normal3f_bufferobject = 0;
10366                         rsurface.normal3f_bufferoffset = 0;
10367                         break;
10368                 case Q3DEFORM_AUTOSPRITE2:
10369                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10370                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10371                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10372                         VectorNormalize(newforward);
10373                         VectorNormalize(newright);
10374                         VectorNormalize(newup);
10375                         // make deformed versions of only the model vertices used by the specified surfaces
10376                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10377                         {
10378                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10379                                 const float *v1, *v2;
10380                                 vec3_t start, end;
10381                                 float f, l;
10382                                 struct
10383                                 {
10384                                         float length2;
10385                                         const float *v1;
10386                                         const float *v2;
10387                                 }
10388                                 shortest[2];
10389                                 memset(shortest, 0, sizeof(shortest));
10390                                 // a single autosprite surface can contain multiple sprites...
10391                                 for (j = 0;j < surface->num_vertices - 3;j += 4)
10392                                 {
10393                                         VectorClear(center);
10394                                         for (i = 0;i < 4;i++)
10395                                                 VectorAdd(center, (rsurface.vertex3f + 3 * surface->num_firstvertex) + (j+i) * 3, center);
10396                                         VectorScale(center, 0.25f, center);
10397                                         // find the two shortest edges, then use them to define the
10398                                         // axis vectors for rotating around the central axis
10399                                         for (i = 0;i < 6;i++)
10400                                         {
10401                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][0]);
10402                                                 v2 = rsurface.vertex3f + 3 * (surface->num_firstvertex + quadedges[i][1]);
10403 #if 0
10404                                                 Debug_PolygonBegin(NULL, 0);
10405                                                 Debug_PolygonVertex(v1[0], v1[1], v1[2], 0, 0, 1, 0, 0, 1);
10406                                                 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);
10407                                                 Debug_PolygonVertex(v2[0], v2[1], v2[2], 0, 0, 1, 0, 0, 1);
10408                                                 Debug_PolygonEnd();
10409 #endif
10410                                                 l = VectorDistance2(v1, v2);
10411                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
10412                                                 if (v1[2] != v2[2])
10413                                                         l += (1.0f / 1024.0f);
10414                                                 if (shortest[0].length2 > l || i == 0)
10415                                                 {
10416                                                         shortest[1] = shortest[0];
10417                                                         shortest[0].length2 = l;
10418                                                         shortest[0].v1 = v1;
10419                                                         shortest[0].v2 = v2;
10420                                                 }
10421                                                 else if (shortest[1].length2 > l || i == 1)
10422                                                 {
10423                                                         shortest[1].length2 = l;
10424                                                         shortest[1].v1 = v1;
10425                                                         shortest[1].v2 = v2;
10426                                                 }
10427                                         }
10428                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
10429                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
10430 #if 0
10431                                         Debug_PolygonBegin(NULL, 0);
10432                                         Debug_PolygonVertex(start[0], start[1], start[2], 0, 0, 1, 1, 0, 1);
10433                                         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);
10434                                         Debug_PolygonVertex(end[0], end[1], end[2], 0, 0, 0, 1, 1, 1);
10435                                         Debug_PolygonEnd();
10436 #endif
10437                                         // this calculates the right vector from the shortest edge
10438                                         // and the up vector from the edge midpoints
10439                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
10440                                         VectorNormalize(right);
10441                                         VectorSubtract(end, start, up);
10442                                         VectorNormalize(up);
10443                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
10444                                         VectorSubtract(rsurface.localvieworigin, center, forward);
10445                                         //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
10446                                         VectorNegate(forward, forward);
10447                                         VectorReflect(forward, 0, up, forward);
10448                                         VectorNormalize(forward);
10449                                         CrossProduct(up, forward, newright);
10450                                         VectorNormalize(newright);
10451 #if 0
10452                                         Debug_PolygonBegin(NULL, 0);
10453                                         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);
10454                                         Debug_PolygonVertex(center[0] + right[0] * 8, center[1] + right[1] * 8, center[2] + right[2] * 8, 0, 0, 0, 1, 0, 1);
10455                                         Debug_PolygonVertex(center[0] + up   [0] * 8, center[1] + up   [1] * 8, center[2] + up   [2] * 8, 0, 0, 0, 0, 1, 1);
10456                                         Debug_PolygonEnd();
10457 #endif
10458 #if 0
10459                                         Debug_PolygonBegin(NULL, 0);
10460                                         Debug_PolygonVertex(center[0] + forward [0] * 8, center[1] + forward [1] * 8, center[2] + forward [2] * 8, 0, 0, 1, 0, 0, 1);
10461                                         Debug_PolygonVertex(center[0] + newright[0] * 8, center[1] + newright[1] * 8, center[2] + newright[2] * 8, 0, 0, 0, 1, 0, 1);
10462                                         Debug_PolygonVertex(center[0] + up      [0] * 8, center[1] + up      [1] * 8, center[2] + up      [2] * 8, 0, 0, 0, 0, 1, 1);
10463                                         Debug_PolygonEnd();
10464 #endif
10465                                         // rotate the quad around the up axis vector, this is made
10466                                         // especially easy by the fact we know the quad is flat,
10467                                         // so we only have to subtract the center position and
10468                                         // measure distance along the right vector, and then
10469                                         // multiply that by the newright vector and add back the
10470                                         // center position
10471                                         // we also need to subtract the old position to undo the
10472                                         // displacement from the center, which we do with a
10473                                         // DotProduct, the subtraction/addition of center is also
10474                                         // optimized into DotProducts here
10475                                         l = DotProduct(right, center);
10476                                         for (i = 0;i < 4;i++)
10477                                         {
10478                                                 v1 = rsurface.vertex3f + 3 * (surface->num_firstvertex + j + i);
10479                                                 f = DotProduct(right, v1) - l;
10480                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_deformedvertex3f + (surface->num_firstvertex+i+j) * 3);
10481                                         }
10482                                 }
10483                                 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);
10484                                 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);
10485                         }
10486                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10487                         rsurface.vertex3f_bufferobject = 0;
10488                         rsurface.vertex3f_bufferoffset = 0;
10489                         rsurface.svector3f = rsurface.array_deformedsvector3f;
10490                         rsurface.svector3f_bufferobject = 0;
10491                         rsurface.svector3f_bufferoffset = 0;
10492                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
10493                         rsurface.tvector3f_bufferobject = 0;
10494                         rsurface.tvector3f_bufferoffset = 0;
10495                         rsurface.normal3f = rsurface.array_deformednormal3f;
10496                         rsurface.normal3f_bufferobject = 0;
10497                         rsurface.normal3f_bufferoffset = 0;
10498                         break;
10499                 case Q3DEFORM_NORMAL:
10500                         // deform the normals to make reflections wavey
10501                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10502                         {
10503                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10504                                 for (j = 0;j < surface->num_vertices;j++)
10505                                 {
10506                                         float vertex[3];
10507                                         float *normal = (rsurface.array_deformednormal3f  + 3 * surface->num_firstvertex) + j*3;
10508                                         VectorScale((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, 0.98f, vertex);
10509                                         VectorCopy((rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, normal);
10510                                         normal[0] += deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10511                                         normal[1] += deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10512                                         normal[2] += deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10513                                         VectorNormalize(normal);
10514                                 }
10515                                 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);
10516                         }
10517                         rsurface.svector3f = rsurface.array_deformedsvector3f;
10518                         rsurface.svector3f_bufferobject = 0;
10519                         rsurface.svector3f_bufferoffset = 0;
10520                         rsurface.tvector3f = rsurface.array_deformedtvector3f;
10521                         rsurface.tvector3f_bufferobject = 0;
10522                         rsurface.tvector3f_bufferoffset = 0;
10523                         rsurface.normal3f = rsurface.array_deformednormal3f;
10524                         rsurface.normal3f_bufferobject = 0;
10525                         rsurface.normal3f_bufferoffset = 0;
10526                         break;
10527                 case Q3DEFORM_WAVE:
10528                         // deform vertex array to make wavey water and flags and such
10529                         waveparms[0] = deform->waveparms[0];
10530                         waveparms[1] = deform->waveparms[1];
10531                         waveparms[2] = deform->waveparms[2];
10532                         waveparms[3] = deform->waveparms[3];
10533                         if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
10534                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
10535                         // this is how a divisor of vertex influence on deformation
10536                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
10537                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10538                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10539                         {
10540                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10541                                 for (j = 0;j < surface->num_vertices;j++)
10542                                 {
10543                                         float *vertex = (rsurface.array_deformedvertex3f  + 3 * surface->num_firstvertex) + j*3;
10544                                         VectorCopy((rsurface.vertex3f  + 3 * surface->num_firstvertex) + j*3, vertex);
10545                                         // if the wavefunc depends on time, evaluate it per-vertex
10546                                         if (waveparms[3])
10547                                         {
10548                                                 waveparms[2] = deform->waveparms[2] + (vertex[0] + vertex[1] + vertex[2]) * animpos;
10549                                                 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10550                                         }
10551                                         VectorMA(vertex, scale, (rsurface.normal3f  + 3 * surface->num_firstvertex) + j*3, vertex);
10552                                 }
10553                         }
10554                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10555                         rsurface.vertex3f_bufferobject = 0;
10556                         rsurface.vertex3f_bufferoffset = 0;
10557                         break;
10558                 case Q3DEFORM_BULGE:
10559                         // deform vertex array to make the surface have moving bulges
10560                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10561                         {
10562                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10563                                 for (j = 0;j < surface->num_vertices;j++)
10564                                 {
10565                                         scale = sin((rsurface.modeltexcoordtexture2f[2 * (surface->num_firstvertex + j)] * deform->parms[0] + r_refdef.scene.time * deform->parms[2])) * deform->parms[1];
10566                                         VectorMA(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), scale, rsurface.normal3f + 3 * (surface->num_firstvertex + j), rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
10567                                 }
10568                         }
10569                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10570                         rsurface.vertex3f_bufferobject = 0;
10571                         rsurface.vertex3f_bufferoffset = 0;
10572                         break;
10573                 case Q3DEFORM_MOVE:
10574                         // deform vertex array
10575                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
10576                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
10577                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
10578                         VectorScale(deform->parms, scale, waveparms);
10579                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10580                         {
10581                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10582                                 for (j = 0;j < surface->num_vertices;j++)
10583                                         VectorAdd(rsurface.vertex3f + 3 * (surface->num_firstvertex + j), waveparms, rsurface.array_deformedvertex3f + 3 * (surface->num_firstvertex + j));
10584                         }
10585                         rsurface.vertex3f = rsurface.array_deformedvertex3f;
10586                         rsurface.vertex3f_bufferobject = 0;
10587                         rsurface.vertex3f_bufferoffset = 0;
10588                         break;
10589                 }
10590         }
10591         // generate texcoords based on the chosen texcoord source
10592         switch(rsurface.texture->tcgen.tcgen)
10593         {
10594         default:
10595         case Q3TCGEN_TEXTURE:
10596                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordtexture2f;
10597                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordtexture2f_bufferobject;
10598                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
10599                 break;
10600         case Q3TCGEN_LIGHTMAP:
10601                 rsurface.texcoordtexture2f               = rsurface.modeltexcoordlightmap2f;
10602                 rsurface.texcoordtexture2f_bufferobject  = rsurface.modeltexcoordlightmap2f_bufferobject;
10603                 rsurface.texcoordtexture2f_bufferoffset  = rsurface.modeltexcoordlightmap2f_bufferoffset;
10604                 break;
10605         case Q3TCGEN_VECTOR:
10606                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10607                 {
10608                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10609                         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)
10610                         {
10611                                 out_tc[0] = DotProduct(v1, rsurface.texture->tcgen.parms);
10612                                 out_tc[1] = DotProduct(v1, rsurface.texture->tcgen.parms + 3);
10613                         }
10614                 }
10615                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
10616                 rsurface.texcoordtexture2f_bufferobject  = 0;
10617                 rsurface.texcoordtexture2f_bufferoffset  = 0;
10618                 break;
10619         case Q3TCGEN_ENVIRONMENT:
10620                 // make environment reflections using a spheremap
10621                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10622                 {
10623                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10624                         const float *vertex = rsurface.modelvertex3f + 3 * surface->num_firstvertex;
10625                         const float *normal = rsurface.modelnormal3f + 3 * surface->num_firstvertex;
10626                         float *out_tc = rsurface.array_generatedtexcoordtexture2f + 2 * surface->num_firstvertex;
10627                         for (j = 0;j < surface->num_vertices;j++, vertex += 3, normal += 3, out_tc += 2)
10628                         {
10629                                 // identical to Q3A's method, but executed in worldspace so
10630                                 // carried models can be shiny too
10631
10632                                 float viewer[3], d, reflected[3], worldreflected[3];
10633
10634                                 VectorSubtract(rsurface.localvieworigin, vertex, viewer);
10635                                 // VectorNormalize(viewer);
10636
10637                                 d = DotProduct(normal, viewer);
10638
10639                                 reflected[0] = normal[0]*2*d - viewer[0];
10640                                 reflected[1] = normal[1]*2*d - viewer[1];
10641                                 reflected[2] = normal[2]*2*d - viewer[2];
10642                                 // note: this is proportinal to viewer, so we can normalize later
10643
10644                                 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
10645                                 VectorNormalize(worldreflected);
10646
10647                                 // note: this sphere map only uses world x and z!
10648                                 // so positive and negative y will LOOK THE SAME.
10649                                 out_tc[0] = 0.5 + 0.5 * worldreflected[1];
10650                                 out_tc[1] = 0.5 - 0.5 * worldreflected[2];
10651                         }
10652                 }
10653                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
10654                 rsurface.texcoordtexture2f_bufferobject  = 0;
10655                 rsurface.texcoordtexture2f_bufferoffset  = 0;
10656                 break;
10657         }
10658         // the only tcmod that needs software vertex processing is turbulent, so
10659         // check for it here and apply the changes if needed
10660         // and we only support that as the first one
10661         // (handling a mixture of turbulent and other tcmods would be problematic
10662         //  without punting it entirely to a software path)
10663         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10664         {
10665                 amplitude = rsurface.texture->tcmods[0].parms[1];
10666                 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
10667                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10668                 {
10669                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10670                         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)
10671                         {
10672                                 out_tc[0] = in_tc[0] + amplitude * sin(((v1[0] + v1[2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10673                                 out_tc[1] = in_tc[1] + amplitude * sin(((v1[1]        ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10674                         }
10675                 }
10676                 rsurface.texcoordtexture2f               = rsurface.array_generatedtexcoordtexture2f;
10677                 rsurface.texcoordtexture2f_bufferobject  = 0;
10678                 rsurface.texcoordtexture2f_bufferoffset  = 0;
10679         }
10680         rsurface.texcoordlightmap2f              = rsurface.modeltexcoordlightmap2f;
10681         rsurface.texcoordlightmap2f_bufferobject = rsurface.modeltexcoordlightmap2f_bufferobject;
10682         rsurface.texcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
10683         R_Mesh_VertexPointer(rsurface.vertex3f, rsurface.vertex3f_bufferobject, rsurface.vertex3f_bufferoffset);
10684 }
10685
10686 void RSurf_DrawBatch_Simple(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10687 {
10688         int i, j;
10689         const msurface_t *surface = texturesurfacelist[0];
10690         const msurface_t *surface2;
10691         int firstvertex;
10692         int endvertex;
10693         int numvertices;
10694         int numtriangles;
10695         // TODO: lock all array ranges before render, rather than on each surface
10696         if (texturenumsurfaces == 1)
10697                 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);
10698         else if (r_batchmode.integer == 2)
10699         {
10700                 #define MAXBATCHTRIANGLES 65536
10701                 int batchtriangles = 0;
10702                 static int batchelements[MAXBATCHTRIANGLES*3];
10703                 for (i = 0;i < texturenumsurfaces;i = j)
10704                 {
10705                         surface = texturesurfacelist[i];
10706                         j = i + 1;
10707                         if (surface->num_triangles > MAXBATCHTRIANGLES)
10708                         {
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                                 continue;
10711                         }
10712                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
10713                         batchtriangles = surface->num_triangles;
10714                         firstvertex = surface->num_firstvertex;
10715                         endvertex = surface->num_firstvertex + surface->num_vertices;
10716                         for (;j < texturenumsurfaces;j++)
10717                         {
10718                                 surface2 = texturesurfacelist[j];
10719                                 if (batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
10720                                         break;
10721                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
10722                                 batchtriangles += surface2->num_triangles;
10723                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
10724                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
10725                         }
10726                         surface2 = texturesurfacelist[j-1];
10727                         numvertices = endvertex - firstvertex;
10728                         R_Mesh_Draw(firstvertex, numvertices, 0, batchtriangles, batchelements, NULL, 0, 0);
10729                 }
10730         }
10731         else if (r_batchmode.integer == 1)
10732         {
10733                 for (i = 0;i < texturenumsurfaces;i = j)
10734                 {
10735                         surface = texturesurfacelist[i];
10736                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
10737                                 if (texturesurfacelist[j] != surface2)
10738                                         break;
10739                         surface2 = texturesurfacelist[j-1];
10740                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
10741                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
10742                         R_Mesh_Draw(surface->num_firstvertex, numvertices, surface->num_firsttriangle, numtriangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10743                 }
10744         }
10745         else
10746         {
10747                 for (i = 0;i < texturenumsurfaces;i++)
10748                 {
10749                         surface = texturesurfacelist[i];
10750                         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);
10751                 }
10752         }
10753 }
10754
10755 static void RSurf_BindLightmapForSurface(const msurface_t *surface)
10756 {
10757         switch(vid.renderpath)
10758         {
10759         case RENDERPATH_CGGL:
10760 #ifdef SUPPORTCG
10761                 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , surface->lightmaptexture );CHECKCGERROR
10762                 if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, surface->deluxemaptexture);CHECKCGERROR
10763 #endif
10764                 break;
10765         case RENDERPATH_GL20:
10766                 if (r_glsl_permutation->loc_Texture_Lightmap  >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , surface->lightmaptexture );
10767                 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, surface->deluxemaptexture);
10768                 break;
10769         case RENDERPATH_GL13:
10770         case RENDERPATH_GL11:
10771                 R_Mesh_TexBind(0, surface->lightmaptexture);
10772                 break;
10773         }
10774 }
10775
10776 static void RSurf_BindReflectionForSurface(const msurface_t *surface)
10777 {
10778         // pick the closest matching water plane and bind textures
10779         int planeindex, vertexindex;
10780         float d, bestd;
10781         vec3_t vert;
10782         const float *v;
10783         r_waterstate_waterplane_t *p, *bestp;
10784         bestd = 0;
10785         bestp = NULL;
10786         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
10787         {
10788                 if(p->camera_entity != rsurface.texture->camera_entity)
10789                         continue;
10790                 d = 0;
10791                 for (vertexindex = 0, v = rsurface.modelvertex3f + surface->num_firstvertex * 3;vertexindex < surface->num_vertices;vertexindex++, v += 3)
10792                 {
10793                         Matrix4x4_Transform(&rsurface.matrix, v, vert);
10794                         d += fabs(PlaneDiff(vert, &p->plane));
10795                 }
10796                 if (bestd > d || !bestp)
10797                 {
10798                         bestd = d;
10799                         bestp = p;
10800                 }
10801         }
10802         switch(vid.renderpath)
10803         {
10804         case RENDERPATH_CGGL:
10805 #ifdef SUPPORTCG
10806                 if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
10807                 else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
10808                 if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
10809 #endif
10810                 break;
10811         case RENDERPATH_GL20:
10812                 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
10813                 else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
10814                 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
10815                 break;
10816         case RENDERPATH_GL13:
10817         case RENDERPATH_GL11:
10818                 break;
10819         }
10820 }
10821
10822 static void RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10823 {
10824         int i;
10825         const msurface_t *surface;
10826         if (r_waterstate.renderingscene)
10827                 return;
10828         for (i = 0;i < texturenumsurfaces;i++)
10829         {
10830                 surface = texturesurfacelist[i];
10831                 RSurf_BindLightmapForSurface(surface);
10832                 RSurf_BindReflectionForSurface(surface);
10833                 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);
10834         }
10835 }
10836
10837 static void RSurf_DrawBatch_WithLightmapSwitching(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10838 {
10839         int i;
10840         int j;
10841         const msurface_t *surface = texturesurfacelist[0];
10842         const msurface_t *surface2;
10843         int firstvertex;
10844         int endvertex;
10845         int numvertices;
10846         int numtriangles;
10847         if (texturenumsurfaces == 1)
10848         {
10849                 RSurf_BindLightmapForSurface(surface);
10850                 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);
10851         }
10852         else if (r_batchmode.integer == 2)
10853         {
10854                 int batchtriangles = 0;
10855                 static int batchelements[MAXBATCHTRIANGLES*3];
10856                 for (i = 0;i < texturenumsurfaces;i = j)
10857                 {
10858                         surface = texturesurfacelist[i];
10859                         RSurf_BindLightmapForSurface(surface);
10860                         j = i + 1;
10861                         if (surface->num_triangles > MAXBATCHTRIANGLES)
10862                         {
10863                                 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);
10864                                 continue;
10865                         }
10866                         memcpy(batchelements, rsurface.modelelement3i + 3 * surface->num_firsttriangle, surface->num_triangles * sizeof(int[3]));
10867                         batchtriangles = surface->num_triangles;
10868                         firstvertex = surface->num_firstvertex;
10869                         endvertex = surface->num_firstvertex + surface->num_vertices;
10870                         for (;j < texturenumsurfaces;j++)
10871                         {
10872                                 surface2 = texturesurfacelist[j];
10873                                 if (surface2->lightmaptexture != surface->lightmaptexture || batchtriangles + surface2->num_triangles > MAXBATCHTRIANGLES)
10874                                         break;
10875                                 memcpy(batchelements + batchtriangles * 3, rsurface.modelelement3i + 3 * surface2->num_firsttriangle, surface2->num_triangles * sizeof(int[3]));
10876                                 batchtriangles += surface2->num_triangles;
10877                                 firstvertex = min(firstvertex, surface2->num_firstvertex);
10878                                 endvertex = max(endvertex, surface2->num_firstvertex + surface2->num_vertices);
10879                         }
10880                         surface2 = texturesurfacelist[j-1];
10881                         numvertices = endvertex - firstvertex;
10882                         R_Mesh_Draw(firstvertex, numvertices, 0, batchtriangles, batchelements, NULL, 0, 0);
10883                 }
10884         }
10885         else if (r_batchmode.integer == 1)
10886         {
10887 #if 0
10888                 Con_Printf("%s batch sizes ignoring lightmap:", rsurface.texture->name);
10889                 for (i = 0;i < texturenumsurfaces;i = j)
10890                 {
10891                         surface = texturesurfacelist[i];
10892                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
10893                                 if (texturesurfacelist[j] != surface2)
10894                                         break;
10895                         Con_Printf(" %i", j - i);
10896                 }
10897                 Con_Printf("\n");
10898                 Con_Printf("%s batch sizes honoring lightmap:", rsurface.texture->name);
10899 #endif
10900                 for (i = 0;i < texturenumsurfaces;i = j)
10901                 {
10902                         surface = texturesurfacelist[i];
10903                         RSurf_BindLightmapForSurface(surface);
10904                         for (j = i + 1, surface2 = surface + 1;j < texturenumsurfaces;j++, surface2++)
10905                                 if (texturesurfacelist[j] != surface2 || texturesurfacelist[j]->lightmaptexture != surface->lightmaptexture)
10906                                         break;
10907 #if 0
10908                         Con_Printf(" %i", j - i);
10909 #endif
10910                         surface2 = texturesurfacelist[j-1];
10911                         numvertices = surface2->num_firstvertex + surface2->num_vertices - surface->num_firstvertex;
10912                         numtriangles = surface2->num_firsttriangle + surface2->num_triangles - surface->num_firsttriangle;
10913                         R_Mesh_Draw(surface->num_firstvertex, numvertices, surface->num_firsttriangle, numtriangles, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10914                 }
10915 #if 0
10916                 Con_Printf("\n");
10917 #endif
10918         }
10919         else
10920         {
10921                 for (i = 0;i < texturenumsurfaces;i++)
10922                 {
10923                         surface = texturesurfacelist[i];
10924                         RSurf_BindLightmapForSurface(surface);
10925                         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);
10926                 }
10927         }
10928 }
10929
10930 static void RSurf_DrawBatch_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10931 {
10932         int j;
10933         int texturesurfaceindex;
10934         if (r_showsurfaces.integer == 2)
10935         {
10936                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10937                 {
10938                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10939                         for (j = 0;j < surface->num_triangles;j++)
10940                         {
10941                                 float f = ((j + surface->num_firsttriangle) & 31) * (1.0f / 31.0f) * r_refdef.view.colorscale;
10942                                 GL_Color(f, f, f, 1);
10943                                 R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle + j, 1, rsurface.modelelement3i, rsurface.modelelement3s, rsurface.modelelement3i_bufferobject, rsurface.modelelement3s_bufferobject);
10944                         }
10945                 }
10946         }
10947         else
10948         {
10949                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10950                 {
10951                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10952                         int k = (int)(((size_t)surface) / sizeof(msurface_t));
10953                         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);
10954                         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);
10955                 }
10956         }
10957 }
10958
10959 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10960 {
10961         int texturesurfaceindex;
10962         int i;
10963         const float *v;
10964         float *c2;
10965         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10966         {
10967                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10968                 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)
10969                 {
10970                         c2[0] = 0.5;
10971                         c2[1] = 0.5;
10972                         c2[2] = 0.5;
10973                         c2[3] = 1;
10974                 }
10975         }
10976         rsurface.lightmapcolor4f = rsurface.array_color4f;
10977         rsurface.lightmapcolor4f_bufferobject = 0;
10978         rsurface.lightmapcolor4f_bufferoffset = 0;
10979 }
10980
10981 static void RSurf_DrawBatch_GL11_ApplyFog(int texturenumsurfaces, const msurface_t **texturesurfacelist)
10982 {
10983         int texturesurfaceindex;
10984         int i;
10985         float f;
10986         const float *v;
10987         const float *c;
10988         float *c2;
10989         if (rsurface.lightmapcolor4f)
10990         {
10991                 // generate color arrays for the surfaces in this list
10992                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
10993                 {
10994                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
10995                         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)
10996                         {
10997                                 f = RSurf_FogVertex(v);
10998                                 c2[0] = c[0] * f;
10999                                 c2[1] = c[1] * f;
11000                                 c2[2] = c[2] * f;
11001                                 c2[3] = c[3];
11002                         }
11003                 }
11004         }
11005         else
11006         {
11007                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11008                 {
11009                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11010                         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)
11011                         {
11012                                 f = RSurf_FogVertex(v);
11013                                 c2[0] = f;
11014                                 c2[1] = f;
11015                                 c2[2] = f;
11016                                 c2[3] = 1;
11017                         }
11018                 }
11019         }
11020         rsurface.lightmapcolor4f = rsurface.array_color4f;
11021         rsurface.lightmapcolor4f_bufferobject = 0;
11022         rsurface.lightmapcolor4f_bufferoffset = 0;
11023 }
11024
11025 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11026 {
11027         int texturesurfaceindex;
11028         int i;
11029         float f;
11030         const float *v;
11031         const float *c;
11032         float *c2;
11033         if (!rsurface.lightmapcolor4f)
11034                 return;
11035         // generate color arrays for the surfaces in this list
11036         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11037         {
11038                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11039                 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)
11040                 {
11041                         f = RSurf_FogVertex(v);
11042                         c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11043                         c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11044                         c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11045                         c2[3] = c[3];
11046                 }
11047         }
11048         rsurface.lightmapcolor4f = rsurface.array_color4f;
11049         rsurface.lightmapcolor4f_bufferobject = 0;
11050         rsurface.lightmapcolor4f_bufferoffset = 0;
11051 }
11052
11053 static void RSurf_DrawBatch_GL11_ApplyColor(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a)
11054 {
11055         int texturesurfaceindex;
11056         int i;
11057         const float *c;
11058         float *c2;
11059         if (!rsurface.lightmapcolor4f)
11060                 return;
11061         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11062         {
11063                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11064                 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)
11065                 {
11066                         c2[0] = c[0] * r;
11067                         c2[1] = c[1] * g;
11068                         c2[2] = c[2] * b;
11069                         c2[3] = c[3] * a;
11070                 }
11071         }
11072         rsurface.lightmapcolor4f = rsurface.array_color4f;
11073         rsurface.lightmapcolor4f_bufferobject = 0;
11074         rsurface.lightmapcolor4f_bufferoffset = 0;
11075 }
11076
11077 static void RSurf_DrawBatch_GL11_ApplyAmbient(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11078 {
11079         int texturesurfaceindex;
11080         int i;
11081         const float *c;
11082         float *c2;
11083         if (!rsurface.lightmapcolor4f)
11084                 return;
11085         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11086         {
11087                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11088                 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)
11089                 {
11090                         c2[0] = c[0] + r_refdef.scene.ambient;
11091                         c2[1] = c[1] + r_refdef.scene.ambient;
11092                         c2[2] = c[2] + r_refdef.scene.ambient;
11093                         c2[3] = c[3];
11094                 }
11095         }
11096         rsurface.lightmapcolor4f = rsurface.array_color4f;
11097         rsurface.lightmapcolor4f_bufferobject = 0;
11098         rsurface.lightmapcolor4f_bufferoffset = 0;
11099 }
11100
11101 static void RSurf_DrawBatch_GL11_Lightmap(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11102 {
11103         // TODO: optimize
11104         rsurface.lightmapcolor4f = NULL;
11105         rsurface.lightmapcolor4f_bufferobject = 0;
11106         rsurface.lightmapcolor4f_bufferoffset = 0;
11107         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11108         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11109         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11110         GL_Color(r, g, b, a);
11111         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist);
11112 }
11113
11114 static void RSurf_DrawBatch_GL11_Unlit(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11115 {
11116         // TODO: optimize applyfog && applycolor case
11117         // just apply fog if necessary, and tint the fog color array if necessary
11118         rsurface.lightmapcolor4f = NULL;
11119         rsurface.lightmapcolor4f_bufferobject = 0;
11120         rsurface.lightmapcolor4f_bufferoffset = 0;
11121         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11122         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11123         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11124         GL_Color(r, g, b, a);
11125         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11126 }
11127
11128 static void RSurf_DrawBatch_GL11_VertexColor(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11129 {
11130         int texturesurfaceindex;
11131         int i;
11132         float *c;
11133         // TODO: optimize
11134         if (texturesurfacelist[0]->lightmapinfo)
11135         {
11136                 // generate color arrays for the surfaces in this list
11137                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11138                 {
11139                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11140                         for (i = 0, c = rsurface.array_color4f + 4 * surface->num_firstvertex;i < surface->num_vertices;i++, c += 4)
11141                         {
11142                                 if (surface->lightmapinfo->samples)
11143                                 {
11144                                         const unsigned char *lm = surface->lightmapinfo->samples + (rsurface.modellightmapoffsets + surface->num_firstvertex)[i];
11145                                         float scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]] * (1.0f / 32768.0f);
11146                                         VectorScale(lm, scale, c);
11147                                         if (surface->lightmapinfo->styles[1] != 255)
11148                                         {
11149                                                 int size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11150                                                 lm += size3;
11151                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]] * (1.0f / 32768.0f);
11152                                                 VectorMA(c, scale, lm, c);
11153                                                 if (surface->lightmapinfo->styles[2] != 255)
11154                                                 {
11155                                                         lm += size3;
11156                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]] * (1.0f / 32768.0f);
11157                                                         VectorMA(c, scale, lm, c);
11158                                                         if (surface->lightmapinfo->styles[3] != 255)
11159                                                         {
11160                                                                 lm += size3;
11161                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]] * (1.0f / 32768.0f);
11162                                                                 VectorMA(c, scale, lm, c);
11163                                                         }
11164                                                 }
11165                                         }
11166                                 }
11167                                 else
11168                                         VectorClear(c);
11169                                 c[3] = 1;
11170                         }
11171                 }
11172                 rsurface.lightmapcolor4f = rsurface.array_color4f;
11173                 rsurface.lightmapcolor4f_bufferobject = 0;
11174                 rsurface.lightmapcolor4f_bufferoffset = 0;
11175         }
11176         else
11177         {
11178                 rsurface.lightmapcolor4f = rsurface.modellightmapcolor4f;
11179                 rsurface.lightmapcolor4f_bufferobject = rsurface.modellightmapcolor4f_bufferobject;
11180                 rsurface.lightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11181         }
11182         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11183         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11184         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11185         GL_Color(r, g, b, a);
11186         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11187 }
11188
11189 static void RSurf_DrawBatch_GL11_ApplyFakeLight(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11190 {
11191         int texturesurfaceindex;
11192         int i;
11193         float f;
11194         const float *v;
11195         const float *n;
11196         float *c;
11197         //vec3_t eyedir;
11198
11199         // fake shading
11200         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11201         {
11202                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11203                 int numverts = surface->num_vertices;
11204                 v = rsurface.vertex3f + 3 * surface->num_firstvertex;
11205                 n = rsurface.normal3f + 3 * surface->num_firstvertex;
11206                 c = rsurface.array_color4f + 4 * surface->num_firstvertex;
11207                 for (i = 0;i < numverts;i++, v += 3, n += 3, c += 4)
11208                 {
11209                         f = -DotProduct(r_refdef.view.forward, n);
11210                         f = max(0, f);
11211                         f = f * 0.85 + 0.15; // work around so stuff won't get black
11212                         f *= r_refdef.lightmapintensity;
11213                         Vector4Set(c, f, f, f, 1);
11214                 }
11215         }
11216
11217         rsurface.lightmapcolor4f = rsurface.array_color4f;
11218         rsurface.lightmapcolor4f_bufferobject = 0;
11219         rsurface.lightmapcolor4f_bufferoffset = 0;
11220 }
11221
11222 static void RSurf_DrawBatch_GL11_FakeLight(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11223 {
11224         RSurf_DrawBatch_GL11_ApplyFakeLight(texturenumsurfaces, texturesurfacelist);
11225         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11226         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11227         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11228         GL_Color(r, g, b, a);
11229         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11230 }
11231
11232 static void RSurf_DrawBatch_GL11_ApplyVertexShade(int texturenumsurfaces, const msurface_t **texturesurfacelist, float *r, float *g, float *b, float *a, qboolean *applycolor)
11233 {
11234         int texturesurfaceindex;
11235         int i;
11236         float f;
11237         float alpha;
11238         const float *v;
11239         const float *n;
11240         float *c;
11241         vec3_t ambientcolor;
11242         vec3_t diffusecolor;
11243         vec3_t lightdir;
11244         // TODO: optimize
11245         // model lighting
11246         VectorCopy(rsurface.modellight_lightdir, lightdir);
11247         f = 0.5f * r_refdef.lightmapintensity;
11248         ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11249         ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11250         ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11251         diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11252         diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11253         diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11254         alpha = *a;
11255         if (VectorLength2(diffusecolor) > 0 && rsurface.normal3f)
11256         {
11257                 // generate color arrays for the surfaces in this list
11258                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11259                 {
11260                         const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11261                         int numverts = surface->num_vertices;
11262                         v = rsurface.vertex3f + 3 * surface->num_firstvertex;
11263                         n = rsurface.normal3f + 3 * surface->num_firstvertex;
11264                         c = rsurface.array_color4f + 4 * surface->num_firstvertex;
11265                         // q3-style directional shading
11266                         for (i = 0;i < numverts;i++, v += 3, n += 3, c += 4)
11267                         {
11268                                 if ((f = DotProduct(n, lightdir)) > 0)
11269                                         VectorMA(ambientcolor, f, diffusecolor, c);
11270                                 else
11271                                         VectorCopy(ambientcolor, c);
11272                                 c[3] = alpha;
11273                         }
11274                 }
11275                 *r = 1;
11276                 *g = 1;
11277                 *b = 1;
11278                 *a = 1;
11279                 rsurface.lightmapcolor4f = rsurface.array_color4f;
11280                 rsurface.lightmapcolor4f_bufferobject = 0;
11281                 rsurface.lightmapcolor4f_bufferoffset = 0;
11282                 *applycolor = false;
11283         }
11284         else
11285         {
11286                 *r = ambientcolor[0];
11287                 *g = ambientcolor[1];
11288                 *b = ambientcolor[2];
11289                 rsurface.lightmapcolor4f = NULL;
11290                 rsurface.lightmapcolor4f_bufferobject = 0;
11291                 rsurface.lightmapcolor4f_bufferoffset = 0;
11292         }
11293 }
11294
11295 static void RSurf_DrawBatch_GL11_VertexShade(int texturenumsurfaces, const msurface_t **texturesurfacelist, float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11296 {
11297         RSurf_DrawBatch_GL11_ApplyVertexShade(texturenumsurfaces, texturesurfacelist, &r, &g, &b, &a, &applycolor);
11298         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog(texturenumsurfaces, texturesurfacelist);
11299         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, r, g, b, a);
11300         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11301         GL_Color(r, g, b, a);
11302         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11303 }
11304
11305 void RSurf_SetupDepthAndCulling(void)
11306 {
11307         // submodels are biased to avoid z-fighting with world surfaces that they
11308         // may be exactly overlapping (avoids z-fighting artifacts on certain
11309         // doors and things in Quake maps)
11310         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
11311         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
11312         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
11313         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11314 }
11315
11316 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11317 {
11318         // transparent sky would be ridiculous
11319         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11320                 return;
11321         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11322         skyrenderlater = true;
11323         RSurf_SetupDepthAndCulling();
11324         GL_DepthMask(true);
11325         // LordHavoc: HalfLife maps have freaky skypolys so don't use
11326         // skymasking on them, and Quake3 never did sky masking (unlike
11327         // software Quake and software Quake2), so disable the sky masking
11328         // in Quake3 maps as it causes problems with q3map2 sky tricks,
11329         // and skymasking also looks very bad when noclipping outside the
11330         // level, so don't use it then either.
11331         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
11332         {
11333                 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
11334                 R_Mesh_ColorPointer(NULL, 0, 0);
11335                 R_Mesh_ResetTextureState();
11336                 if (skyrendermasked)
11337                 {
11338                         R_SetupShader_DepthOrShadow();
11339                         // depth-only (masking)
11340                         GL_ColorMask(0,0,0,0);
11341                         // just to make sure that braindead drivers don't draw
11342                         // anything despite that colormask...
11343                         GL_BlendFunc(GL_ZERO, GL_ONE);
11344                 }
11345                 else
11346                 {
11347                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11348                         // fog sky
11349                         GL_BlendFunc(GL_ONE, GL_ZERO);
11350                 }
11351                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11352                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11353                 if (skyrendermasked)
11354                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11355         }
11356         R_Mesh_ResetTextureState();
11357         GL_Color(1, 1, 1, 1);
11358 }
11359
11360 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
11361 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
11362 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11363 {
11364         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
11365                 return;
11366         RSurf_PrepareVerticesForBatch(true, true, texturenumsurfaces, texturesurfacelist);
11367         if (prepass)
11368         {
11369                 // render screenspace normalmap to texture
11370                 GL_DepthMask(true);
11371                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY);
11372                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11373         }
11374         else if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
11375         {
11376                 // render water or distortion background, then blend surface on top
11377                 GL_DepthMask(true);
11378                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND);
11379                 RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist);
11380                 GL_DepthMask(false);
11381                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
11382                 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11383                         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist);
11384                 else
11385                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11386         }
11387         else
11388         {
11389                 // render surface normally
11390                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11391                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE);
11392                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
11393                         RSurf_DrawBatch_WithLightmapSwitching_WithWaterTextureSwitching(texturenumsurfaces, texturesurfacelist);
11394                 else if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11395                         RSurf_DrawBatch_WithLightmapSwitching(texturenumsurfaces, texturesurfacelist);
11396                 else
11397                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11398         }
11399 }
11400
11401 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11402 {
11403         // OpenGL 1.3 path - anything not completely ancient
11404         int texturesurfaceindex;
11405         qboolean applycolor;
11406         qboolean applyfog;
11407         int layerindex;
11408         const texturelayer_t *layer;
11409         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11410
11411         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11412         {
11413                 vec4_t layercolor;
11414                 int layertexrgbscale;
11415                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11416                 {
11417                         if (layerindex == 0)
11418                                 GL_AlphaTest(true);
11419                         else
11420                         {
11421                                 GL_AlphaTest(false);
11422                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11423                         }
11424                 }
11425                 GL_DepthMask(layer->depthmask && writedepth);
11426                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11427                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
11428                 {
11429                         layertexrgbscale = 4;
11430                         VectorScale(layer->color, 0.25f, layercolor);
11431                 }
11432                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
11433                 {
11434                         layertexrgbscale = 2;
11435                         VectorScale(layer->color, 0.5f, layercolor);
11436                 }
11437                 else
11438                 {
11439                         layertexrgbscale = 1;
11440                         VectorScale(layer->color, 1.0f, layercolor);
11441                 }
11442                 layercolor[3] = layer->color[3];
11443                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
11444                 R_Mesh_ColorPointer(NULL, 0, 0);
11445                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11446                 switch (layer->type)
11447                 {
11448                 case TEXTURELAYERTYPE_LITTEXTURE:
11449                         // single-pass lightmapped texture with 2x rgbscale
11450                         R_Mesh_TexBind(0, r_texture_white);
11451                         R_Mesh_TexMatrix(0, NULL);
11452                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11453                         R_Mesh_TexCoordPointer(0, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
11454                         R_Mesh_TexBind(1, layer->texture);
11455                         R_Mesh_TexMatrix(1, &layer->texmatrix);
11456                         R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11457                         R_Mesh_TexCoordPointer(1, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11458                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11459                                 RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11460                         else if (FAKELIGHT_ENABLED)
11461                                 RSurf_DrawBatch_GL11_FakeLight(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11462                         else if (rsurface.uselightmaptexture)
11463                                 RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11464                         else
11465                                 RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11466                         break;
11467                 case TEXTURELAYERTYPE_TEXTURE:
11468                         // singletexture unlit texture with transparency support
11469                         R_Mesh_TexBind(0, layer->texture);
11470                         R_Mesh_TexMatrix(0, &layer->texmatrix);
11471                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11472                         R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11473                         R_Mesh_TexBind(1, 0);
11474                         R_Mesh_TexCoordPointer(1, 2, NULL, 0, 0);
11475                         RSurf_DrawBatch_GL11_Unlit(texturenumsurfaces, texturesurfacelist, layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11476                         break;
11477                 case TEXTURELAYERTYPE_FOG:
11478                         // singletexture fogging
11479                         if (layer->texture)
11480                         {
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                         }
11486                         else
11487                         {
11488                                 R_Mesh_TexBind(0, 0);
11489                                 R_Mesh_TexCoordPointer(0, 2, NULL, 0, 0);
11490                         }
11491                         R_Mesh_TexBind(1, 0);
11492                         R_Mesh_TexCoordPointer(1, 2, NULL, 0, 0);
11493                         // generate a color array for the fog pass
11494                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
11495                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11496                         {
11497                                 int i;
11498                                 float f;
11499                                 const float *v;
11500                                 float *c;
11501                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11502                                 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)
11503                                 {
11504                                         f = 1 - RSurf_FogVertex(v);
11505                                         c[0] = layercolor[0];
11506                                         c[1] = layercolor[1];
11507                                         c[2] = layercolor[2];
11508                                         c[3] = f * layercolor[3];
11509                                 }
11510                         }
11511                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11512                         break;
11513                 default:
11514                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11515                 }
11516         }
11517         CHECKGLERROR
11518         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11519         {
11520                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11521                 GL_AlphaTest(false);
11522         }
11523 }
11524
11525 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11526 {
11527         // OpenGL 1.1 - crusty old voodoo path
11528         int texturesurfaceindex;
11529         qboolean applyfog;
11530         int layerindex;
11531         const texturelayer_t *layer;
11532         RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11533
11534         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11535         {
11536                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11537                 {
11538                         if (layerindex == 0)
11539                                 GL_AlphaTest(true);
11540                         else
11541                         {
11542                                 GL_AlphaTest(false);
11543                                 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11544                         }
11545                 }
11546                 GL_DepthMask(layer->depthmask && writedepth);
11547                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11548                 R_Mesh_ColorPointer(NULL, 0, 0);
11549                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11550                 switch (layer->type)
11551                 {
11552                 case TEXTURELAYERTYPE_LITTEXTURE:
11553                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
11554                         {
11555                                 // two-pass lit texture with 2x rgbscale
11556                                 // first the lightmap pass
11557                                 R_Mesh_TexBind(0, r_texture_white);
11558                                 R_Mesh_TexMatrix(0, NULL);
11559                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11560                                 R_Mesh_TexCoordPointer(0, 2, rsurface.modeltexcoordlightmap2f, rsurface.modeltexcoordlightmap2f_bufferobject, rsurface.modeltexcoordlightmap2f_bufferoffset);
11561                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11562                                         RSurf_DrawBatch_GL11_VertexShade(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11563                                 else if (FAKELIGHT_ENABLED)
11564                                         RSurf_DrawBatch_GL11_FakeLight(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11565                                 else if (rsurface.uselightmaptexture)
11566                                         RSurf_DrawBatch_GL11_Lightmap(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11567                                 else
11568                                         RSurf_DrawBatch_GL11_VertexColor(texturenumsurfaces, texturesurfacelist, 1, 1, 1, 1, false, false);
11569                                 // then apply the texture to it
11570                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
11571                                 R_Mesh_TexBind(0, layer->texture);
11572                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11573                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11574                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11575                                 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);
11576                         }
11577                         else
11578                         {
11579                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
11580                                 R_Mesh_TexBind(0, layer->texture);
11581                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11582                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11583                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11584                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11585                                         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);
11586                                 else
11587                                         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);
11588                         }
11589                         break;
11590                 case TEXTURELAYERTYPE_TEXTURE:
11591                         // singletexture unlit texture with 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                         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);
11597                         break;
11598                 case TEXTURELAYERTYPE_FOG:
11599                         // singletexture fogging
11600                         if (layer->texture)
11601                         {
11602                                 R_Mesh_TexBind(0, layer->texture);
11603                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
11604                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11605                                 R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset);
11606                         }
11607                         else
11608                         {
11609                                 R_Mesh_TexBind(0, 0);
11610                                 R_Mesh_TexCoordPointer(0, 2, NULL, 0, 0);
11611                         }
11612                         // generate a color array for the fog pass
11613                         R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0);
11614                         for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11615                         {
11616                                 int i;
11617                                 float f;
11618                                 const float *v;
11619                                 float *c;
11620                                 const msurface_t *surface = texturesurfacelist[texturesurfaceindex];
11621                                 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)
11622                                 {
11623                                         f = 1 - RSurf_FogVertex(v);
11624                                         c[0] = layer->color[0];
11625                                         c[1] = layer->color[1];
11626                                         c[2] = layer->color[2];
11627                                         c[3] = f * layer->color[3];
11628                                 }
11629                         }
11630                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11631                         break;
11632                 default:
11633                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11634                 }
11635         }
11636         CHECKGLERROR
11637         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11638         {
11639                 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11640                 GL_AlphaTest(false);
11641         }
11642 }
11643
11644 static void R_DrawTextureSurfaceList_ShowSurfaces3(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11645 {
11646         float c[4];
11647
11648         GL_AlphaTest(false);
11649         R_Mesh_ColorPointer(NULL, 0, 0);
11650         R_Mesh_ResetTextureState();
11651         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11652
11653         if(rsurface.texture && rsurface.texture->currentskinframe)
11654         {
11655                 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
11656                 c[3] *= rsurface.texture->currentalpha;
11657         }
11658         else
11659         {
11660                 c[0] = 1;
11661                 c[1] = 0;
11662                 c[2] = 1;
11663                 c[3] = 1;
11664         }
11665
11666         if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
11667         {
11668                 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
11669                 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
11670                 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
11671         }
11672
11673         // brighten it up (as texture value 127 means "unlit")
11674         c[0] *= 2 * r_refdef.view.colorscale;
11675         c[1] *= 2 * r_refdef.view.colorscale;
11676         c[2] *= 2 * r_refdef.view.colorscale;
11677
11678         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
11679                 c[3] *= r_wateralpha.value;
11680
11681         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
11682         {
11683                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11684                 GL_DepthMask(false);
11685         }
11686         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
11687         {
11688                 GL_BlendFunc(GL_ONE, GL_ONE);
11689                 GL_DepthMask(false);
11690         }
11691         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11692         {
11693                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
11694                 GL_DepthMask(false);
11695         }
11696         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
11697         {
11698                 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
11699                 GL_DepthMask(false);
11700         }
11701         else
11702         {
11703                 GL_BlendFunc(GL_ONE, GL_ZERO);
11704                 GL_DepthMask(writedepth);
11705         }
11706
11707         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
11708         {
11709                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11710
11711                 rsurface.lightmapcolor4f = NULL;
11712                 rsurface.lightmapcolor4f_bufferobject = 0;
11713                 rsurface.lightmapcolor4f_bufferoffset = 0;
11714         }
11715         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11716         {
11717                 qboolean applycolor = true;
11718                 float one = 1.0;
11719
11720                 RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11721
11722                 r_refdef.lightmapintensity = 1;
11723                 RSurf_DrawBatch_GL11_ApplyVertexShade(texturenumsurfaces, texturesurfacelist, &one, &one, &one, &one, &applycolor);
11724                 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11725         }
11726         else if (FAKELIGHT_ENABLED)
11727         {
11728                 RSurf_PrepareVerticesForBatch(true, false, texturenumsurfaces, texturesurfacelist);
11729
11730                 r_refdef.lightmapintensity = r_fakelight_intensity.value;
11731                 RSurf_DrawBatch_GL11_ApplyFakeLight(texturenumsurfaces, texturesurfacelist);
11732                 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11733         }
11734         else
11735         {
11736                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11737
11738                 rsurface.lightmapcolor4f = rsurface.modellightmapcolor4f;
11739                 rsurface.lightmapcolor4f_bufferobject = rsurface.modellightmapcolor4f_bufferobject;
11740                 rsurface.lightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11741         }
11742
11743         if(!rsurface.lightmapcolor4f)
11744                 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(texturenumsurfaces, texturesurfacelist);
11745
11746         RSurf_DrawBatch_GL11_ApplyAmbient(texturenumsurfaces, texturesurfacelist);
11747         RSurf_DrawBatch_GL11_ApplyColor(texturenumsurfaces, texturesurfacelist, c[0], c[1], c[2], c[3]);
11748         if(r_refdef.fogenabled)
11749                 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(texturenumsurfaces, texturesurfacelist);
11750
11751         R_Mesh_ColorPointer(rsurface.lightmapcolor4f, rsurface.lightmapcolor4f_bufferobject, rsurface.lightmapcolor4f_bufferoffset);
11752         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11753 }
11754
11755 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11756 {
11757         CHECKGLERROR
11758         RSurf_SetupDepthAndCulling();
11759         if (r_showsurfaces.integer == 3 && !prepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY))
11760         {
11761                 R_DrawTextureSurfaceList_ShowSurfaces3(texturenumsurfaces, texturesurfacelist, writedepth);
11762                 return;
11763         }
11764         switch (vid.renderpath)
11765         {
11766         case RENDERPATH_GL20:
11767         case RENDERPATH_CGGL:
11768                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11769                 break;
11770         case RENDERPATH_GL13:
11771                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11772                 break;
11773         case RENDERPATH_GL11:
11774                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11775                 break;
11776         }
11777         CHECKGLERROR
11778 }
11779
11780 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11781 {
11782         CHECKGLERROR
11783         RSurf_SetupDepthAndCulling();
11784         if (r_showsurfaces.integer == 3 && !prepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY))
11785         {
11786                 R_DrawTextureSurfaceList_ShowSurfaces3(texturenumsurfaces, texturesurfacelist, writedepth);
11787                 return;
11788         }
11789         switch (vid.renderpath)
11790         {
11791         case RENDERPATH_GL20:
11792         case RENDERPATH_CGGL:
11793                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11794                 break;
11795         case RENDERPATH_GL13:
11796                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11797                 break;
11798         case RENDERPATH_GL11:
11799                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11800                 break;
11801         }
11802         CHECKGLERROR
11803 }
11804
11805 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
11806 {
11807         int i, j;
11808         int texturenumsurfaces, endsurface;
11809         texture_t *texture;
11810         const msurface_t *surface;
11811 #define MAXBATCH_TRANSPARENTSURFACES 256
11812         const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
11813
11814         // if the model is static it doesn't matter what value we give for
11815         // wantnormals and wanttangents, so this logic uses only rules applicable
11816         // to a model, knowing that they are meaningless otherwise
11817         if (ent == r_refdef.scene.worldentity)
11818                 RSurf_ActiveWorldEntity();
11819         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11820                 RSurf_ActiveModelEntity(ent, false, false, false);
11821         else
11822         {
11823                 switch (vid.renderpath)
11824                 {
11825                 case RENDERPATH_GL20:
11826                 case RENDERPATH_CGGL:
11827                         RSurf_ActiveModelEntity(ent, true, true, false);
11828                         break;
11829                 case RENDERPATH_GL13:
11830                 case RENDERPATH_GL11:
11831                         RSurf_ActiveModelEntity(ent, true, false, false);
11832                         break;
11833                 }
11834         }
11835
11836         if (r_transparentdepthmasking.integer)
11837         {
11838                 qboolean setup = false;
11839                 for (i = 0;i < numsurfaces;i = j)
11840                 {
11841                         j = i + 1;
11842                         surface = rsurface.modelsurfaces + surfacelist[i];
11843                         texture = surface->texture;
11844                         rsurface.texture = R_GetCurrentTexture(texture);
11845                         // scan ahead until we find a different texture
11846                         endsurface = min(i + 1024, numsurfaces);
11847                         texturenumsurfaces = 0;
11848                         texturesurfacelist[texturenumsurfaces++] = surface;
11849                         if(FAKELIGHT_ENABLED)
11850                         {
11851                                 rsurface.uselightmaptexture = false;
11852                                 for (;j < endsurface;j++)
11853                                 {
11854                                         surface = rsurface.modelsurfaces + surfacelist[j];
11855                                         if (texture != surface->texture)
11856                                                 break;
11857                                         texturesurfacelist[texturenumsurfaces++] = surface;
11858                                 }
11859                         }
11860                         else
11861                         {
11862                                 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11863                                 for (;j < endsurface;j++)
11864                                 {
11865                                         surface = rsurface.modelsurfaces + surfacelist[j];
11866                                         if (texture != surface->texture || rsurface.uselightmaptexture != (surface->lightmaptexture != NULL))
11867                                                 break;
11868                                         texturesurfacelist[texturenumsurfaces++] = surface;
11869                                 }
11870                         }
11871                         if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
11872                                 continue;
11873                         // render the range of surfaces as depth
11874                         if (!setup)
11875                         {
11876                                 setup = true;
11877                                 GL_ColorMask(0,0,0,0);
11878                                 GL_Color(1,1,1,1);
11879                                 GL_DepthTest(true);
11880                                 GL_BlendFunc(GL_ONE, GL_ZERO);
11881                                 GL_DepthMask(true);
11882                                 GL_AlphaTest(false);
11883                                 R_Mesh_ColorPointer(NULL, 0, 0);
11884                                 R_Mesh_ResetTextureState();
11885                                 R_SetupShader_DepthOrShadow();
11886                         }
11887                         RSurf_SetupDepthAndCulling();
11888                         RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11889                         RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11890                 }
11891                 if (setup)
11892                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11893         }
11894
11895         for (i = 0;i < numsurfaces;i = j)
11896         {
11897                 j = i + 1;
11898                 surface = rsurface.modelsurfaces + surfacelist[i];
11899                 texture = surface->texture;
11900                 rsurface.texture = R_GetCurrentTexture(texture);
11901                 // scan ahead until we find a different texture
11902                 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
11903                 texturenumsurfaces = 0;
11904                 texturesurfacelist[texturenumsurfaces++] = surface;
11905                 if(FAKELIGHT_ENABLED)
11906                 {
11907                         rsurface.uselightmaptexture = false;
11908                         for (;j < endsurface;j++)
11909                         {
11910                                 surface = rsurface.modelsurfaces + surfacelist[j];
11911                                 if (texture != surface->texture)
11912                                         break;
11913                                 texturesurfacelist[texturenumsurfaces++] = surface;
11914                         }
11915                 }
11916                 else
11917                 {
11918                         rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11919                         for (;j < endsurface;j++)
11920                         {
11921                                 surface = rsurface.modelsurfaces + surfacelist[j];
11922                                 if (texture != surface->texture || rsurface.uselightmaptexture != (surface->lightmaptexture != NULL))
11923                                         break;
11924                                 texturesurfacelist[texturenumsurfaces++] = surface;
11925                         }
11926                 }
11927                 // render the range of surfaces
11928                 if (ent == r_refdef.scene.worldentity)
11929                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11930                 else
11931                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11932         }
11933         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11934         GL_AlphaTest(false);
11935 }
11936
11937 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
11938 {
11939         // transparent surfaces get pushed off into the transparent queue
11940         int surfacelistindex;
11941         const msurface_t *surface;
11942         vec3_t tempcenter, center;
11943         for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
11944         {
11945                 surface = texturesurfacelist[surfacelistindex];
11946                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
11947                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
11948                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
11949                 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
11950                 if (queueentity->transparent_offset) // transparent offset
11951                 {
11952                         center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
11953                         center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
11954                         center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
11955                 }
11956                 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
11957         }
11958 }
11959
11960 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
11961 {
11962         const entity_render_t *queueentity = r_refdef.scene.worldentity;
11963         CHECKGLERROR
11964         if (depthonly)
11965         {
11966                 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
11967                         return;
11968                 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
11969                         return;
11970                 RSurf_SetupDepthAndCulling();
11971                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11972                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11973         }
11974         else if (prepass)
11975         {
11976                 if (!rsurface.texture->currentnumlayers)
11977                         return;
11978                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11979                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11980                 else
11981                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11982         }
11983         else if (r_showsurfaces.integer && !r_refdef.view.showdebug && !prepass)
11984         {
11985                 RSurf_SetupDepthAndCulling();
11986                 GL_AlphaTest(false);
11987                 R_Mesh_ColorPointer(NULL, 0, 0);
11988                 R_Mesh_ResetTextureState();
11989                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11990                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
11991                 GL_DepthMask(true);
11992                 GL_BlendFunc(GL_ONE, GL_ZERO);
11993                 GL_Color(0, 0, 0, 1);
11994                 GL_DepthTest(writedepth);
11995                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
11996         }
11997         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3 && !prepass)
11998         {
11999                 RSurf_SetupDepthAndCulling();
12000                 GL_AlphaTest(false);
12001                 R_Mesh_ColorPointer(NULL, 0, 0);
12002                 R_Mesh_ResetTextureState();
12003                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12004                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12005                 GL_DepthMask(true);
12006                 GL_BlendFunc(GL_ONE, GL_ZERO);
12007                 GL_DepthTest(true);
12008                 RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
12009         }
12010         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
12011                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12012         else if (!rsurface.texture->currentnumlayers)
12013                 return;
12014         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12015         {
12016                 // in the deferred case, transparent surfaces were queued during prepass
12017                 if (!r_shadow_usingdeferredprepass)
12018                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12019         }
12020         else
12021         {
12022                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12023                 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12024         }
12025         CHECKGLERROR
12026 }
12027
12028 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12029 {
12030         int i, j;
12031         texture_t *texture;
12032         // break the surface list down into batches by texture and use of lightmapping
12033         for (i = 0;i < numsurfaces;i = j)
12034         {
12035                 j = i + 1;
12036                 // texture is the base texture pointer, rsurface.texture is the
12037                 // current frame/skin the texture is directing us to use (for example
12038                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12039                 // use skin 1 instead)
12040                 texture = surfacelist[i]->texture;
12041                 rsurface.texture = R_GetCurrentTexture(texture);
12042                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12043                 {
12044                         // if this texture is not the kind we want, skip ahead to the next one
12045                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12046                                 ;
12047                         continue;
12048                 }
12049                 if(FAKELIGHT_ENABLED || depthonly || prepass)
12050                 {
12051                         rsurface.uselightmaptexture = false;
12052                         // simply scan ahead until we find a different texture or lightmap state
12053                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12054                                 ;
12055                 }
12056                 else
12057                 {
12058                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12059                         // simply scan ahead until we find a different texture or lightmap state
12060                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
12061                                 ;
12062                 }
12063                 // render the range of surfaces
12064                 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12065         }
12066 }
12067
12068 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12069 {
12070         CHECKGLERROR
12071         if (depthonly)
12072         {
12073                 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12074                         return;
12075                 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12076                         return;
12077                 RSurf_SetupDepthAndCulling();
12078                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12079                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
12080         }
12081         else if (prepass)
12082         {
12083                 if (!rsurface.texture->currentnumlayers)
12084                         return;
12085                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12086                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12087                 else
12088                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12089         }
12090         else if (r_showsurfaces.integer && !r_refdef.view.showdebug)
12091         {
12092                 RSurf_SetupDepthAndCulling();
12093                 GL_AlphaTest(false);
12094                 R_Mesh_ColorPointer(NULL, 0, 0);
12095                 R_Mesh_ResetTextureState();
12096                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12097                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12098                 GL_DepthMask(true);
12099                 GL_BlendFunc(GL_ONE, GL_ZERO);
12100                 GL_Color(0, 0, 0, 1);
12101                 GL_DepthTest(writedepth);
12102                 RSurf_DrawBatch_Simple(texturenumsurfaces, texturesurfacelist);
12103         }
12104         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12105         {
12106                 RSurf_SetupDepthAndCulling();
12107                 GL_AlphaTest(false);
12108                 R_Mesh_ColorPointer(NULL, 0, 0);
12109                 R_Mesh_ResetTextureState();
12110                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12111                 RSurf_PrepareVerticesForBatch(false, false, texturenumsurfaces, texturesurfacelist);
12112                 GL_DepthMask(true);
12113                 GL_BlendFunc(GL_ONE, GL_ZERO);
12114                 GL_DepthTest(true);
12115                 RSurf_DrawBatch_ShowSurfaces(texturenumsurfaces, texturesurfacelist);
12116         }
12117         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY)
12118                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12119         else if (!rsurface.texture->currentnumlayers)
12120                 return;
12121         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12122         {
12123                 // in the deferred case, transparent surfaces were queued during prepass
12124                 if (!r_shadow_usingdeferredprepass)
12125                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12126         }
12127         else
12128         {
12129                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12130                 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12131         }
12132         CHECKGLERROR
12133 }
12134
12135 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12136 {
12137         int i, j;
12138         texture_t *texture;
12139         // break the surface list down into batches by texture and use of lightmapping
12140         for (i = 0;i < numsurfaces;i = j)
12141         {
12142                 j = i + 1;
12143                 // texture is the base texture pointer, rsurface.texture is the
12144                 // current frame/skin the texture is directing us to use (for example
12145                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12146                 // use skin 1 instead)
12147                 texture = surfacelist[i]->texture;
12148                 rsurface.texture = R_GetCurrentTexture(texture);
12149                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12150                 {
12151                         // if this texture is not the kind we want, skip ahead to the next one
12152                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12153                                 ;
12154                         continue;
12155                 }
12156                 if(FAKELIGHT_ENABLED || depthonly || prepass)
12157                 {
12158                         rsurface.uselightmaptexture = false;
12159                         // simply scan ahead until we find a different texture or lightmap state
12160                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12161                                 ;
12162                 }
12163                 else
12164                 {
12165                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12166                         // simply scan ahead until we find a different texture or lightmap state
12167                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.uselightmaptexture == (surfacelist[j]->lightmaptexture != NULL);j++)
12168                                 ;
12169                 }
12170                 // render the range of surfaces
12171                 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12172         }
12173 }
12174
12175 float locboxvertex3f[6*4*3] =
12176 {
12177         1,0,1, 1,0,0, 1,1,0, 1,1,1,
12178         0,1,1, 0,1,0, 0,0,0, 0,0,1,
12179         1,1,1, 1,1,0, 0,1,0, 0,1,1,
12180         0,0,1, 0,0,0, 1,0,0, 1,0,1,
12181         0,0,1, 1,0,1, 1,1,1, 0,1,1,
12182         1,0,0, 0,0,0, 0,1,0, 1,1,0
12183 };
12184
12185 unsigned short locboxelements[6*2*3] =
12186 {
12187          0, 1, 2, 0, 2, 3,
12188          4, 5, 6, 4, 6, 7,
12189          8, 9,10, 8,10,11,
12190         12,13,14, 12,14,15,
12191         16,17,18, 16,18,19,
12192         20,21,22, 20,22,23
12193 };
12194
12195 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12196 {
12197         int i, j;
12198         cl_locnode_t *loc = (cl_locnode_t *)ent;
12199         vec3_t mins, size;
12200         float vertex3f[6*4*3];
12201         CHECKGLERROR
12202         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12203         GL_DepthMask(false);
12204         GL_DepthRange(0, 1);
12205         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12206         GL_DepthTest(true);
12207         GL_CullFace(GL_NONE);
12208         R_EntityMatrix(&identitymatrix);
12209
12210         R_Mesh_VertexPointer(vertex3f, 0, 0);
12211         R_Mesh_ColorPointer(NULL, 0, 0);
12212         R_Mesh_ResetTextureState();
12213         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12214
12215         i = surfacelist[0];
12216         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12217                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12218                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12219                         surfacelist[0] < 0 ? 0.5f : 0.125f);
12220
12221         if (VectorCompare(loc->mins, loc->maxs))
12222         {
12223                 VectorSet(size, 2, 2, 2);
12224                 VectorMA(loc->mins, -0.5f, size, mins);
12225         }
12226         else
12227         {
12228                 VectorCopy(loc->mins, mins);
12229                 VectorSubtract(loc->maxs, loc->mins, size);
12230         }
12231
12232         for (i = 0;i < 6*4*3;)
12233                 for (j = 0;j < 3;j++, i++)
12234                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12235
12236         R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, locboxelements, 0, 0);
12237 }
12238
12239 void R_DrawLocs(void)
12240 {
12241         int index;
12242         cl_locnode_t *loc, *nearestloc;
12243         vec3_t center;
12244         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12245         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12246         {
12247                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12248                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12249         }
12250 }
12251
12252 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12253 {
12254         if (decalsystem->decals)
12255                 Mem_Free(decalsystem->decals);
12256         memset(decalsystem, 0, sizeof(*decalsystem));
12257 }
12258
12259 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)
12260 {
12261         tridecal_t *decal;
12262         tridecal_t *decals;
12263         int i;
12264
12265         // expand or initialize the system
12266         if (decalsystem->maxdecals <= decalsystem->numdecals)
12267         {
12268                 decalsystem_t old = *decalsystem;
12269                 qboolean useshortelements;
12270                 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12271                 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12272                 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)));
12273                 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12274                 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12275                 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12276                 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12277                 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12278                 if (decalsystem->numdecals)
12279                         memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12280                 if (old.decals)
12281                         Mem_Free(old.decals);
12282                 for (i = 0;i < decalsystem->maxdecals*3;i++)
12283                         decalsystem->element3i[i] = i;
12284                 if (useshortelements)
12285                         for (i = 0;i < decalsystem->maxdecals*3;i++)
12286                                 decalsystem->element3s[i] = i;
12287         }
12288
12289         // grab a decal and search for another free slot for the next one
12290         decals = decalsystem->decals;
12291         decal = decalsystem->decals + (i = decalsystem->freedecal++);
12292         for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12293                 ;
12294         decalsystem->freedecal = i;
12295         if (decalsystem->numdecals <= i)
12296                 decalsystem->numdecals = i + 1;
12297
12298         // initialize the decal
12299         decal->lived = 0;
12300         decal->triangleindex = triangleindex;
12301         decal->surfaceindex = surfaceindex;
12302         decal->decalsequence = decalsequence;
12303         decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
12304         decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
12305         decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
12306         decal->color4ub[0][3] = 255;
12307         decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
12308         decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
12309         decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
12310         decal->color4ub[1][3] = 255;
12311         decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
12312         decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
12313         decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
12314         decal->color4ub[2][3] = 255;
12315         decal->vertex3f[0][0] = v0[0];
12316         decal->vertex3f[0][1] = v0[1];
12317         decal->vertex3f[0][2] = v0[2];
12318         decal->vertex3f[1][0] = v1[0];
12319         decal->vertex3f[1][1] = v1[1];
12320         decal->vertex3f[1][2] = v1[2];
12321         decal->vertex3f[2][0] = v2[0];
12322         decal->vertex3f[2][1] = v2[1];
12323         decal->vertex3f[2][2] = v2[2];
12324         decal->texcoord2f[0][0] = t0[0];
12325         decal->texcoord2f[0][1] = t0[1];
12326         decal->texcoord2f[1][0] = t1[0];
12327         decal->texcoord2f[1][1] = t1[1];
12328         decal->texcoord2f[2][0] = t2[0];
12329         decal->texcoord2f[2][1] = t2[1];
12330 }
12331
12332 extern cvar_t cl_decals_bias;
12333 extern cvar_t cl_decals_models;
12334 extern cvar_t cl_decals_newsystem_intensitymultiplier;
12335 // baseparms, parms, temps
12336 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)
12337 {
12338         int cornerindex;
12339         int index;
12340         float v[9][3];
12341         const float *vertex3f;
12342         int numpoints;
12343         float points[2][9][3];
12344         float temp[3];
12345         float tc[9][2];
12346         float f;
12347         float c[9][4];
12348         const int *e;
12349
12350         e = rsurface.modelelement3i + 3*triangleindex;
12351
12352         vertex3f = rsurface.modelvertex3f;
12353
12354         for (cornerindex = 0;cornerindex < 3;cornerindex++)
12355         {
12356                 index = 3*e[cornerindex];
12357                 VectorCopy(vertex3f + index, v[cornerindex]);
12358         }
12359         // cull backfaces
12360         //TriangleNormal(v[0], v[1], v[2], normal);
12361         //if (DotProduct(normal, localnormal) < 0.0f)
12362         //      continue;
12363         // clip by each of the box planes formed from the projection matrix
12364         // if anything survives, we emit the decal
12365         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]);
12366         if (numpoints < 3)
12367                 return;
12368         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]);
12369         if (numpoints < 3)
12370                 return;
12371         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]);
12372         if (numpoints < 3)
12373                 return;
12374         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]);
12375         if (numpoints < 3)
12376                 return;
12377         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]);
12378         if (numpoints < 3)
12379                 return;
12380         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]);
12381         if (numpoints < 3)
12382                 return;
12383         // some part of the triangle survived, so we have to accept it...
12384         if (dynamic)
12385         {
12386                 // dynamic always uses the original triangle
12387                 numpoints = 3;
12388                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12389                 {
12390                         index = 3*e[cornerindex];
12391                         VectorCopy(vertex3f + index, v[cornerindex]);
12392                 }
12393         }
12394         for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
12395         {
12396                 // convert vertex positions to texcoords
12397                 Matrix4x4_Transform(projection, v[cornerindex], temp);
12398                 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
12399                 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
12400                 // calculate distance fade from the projection origin
12401                 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
12402                 f = bound(0.0f, f, 1.0f);
12403                 c[cornerindex][0] = r * f;
12404                 c[cornerindex][1] = g * f;
12405                 c[cornerindex][2] = b * f;
12406                 c[cornerindex][3] = 1.0f;
12407                 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
12408         }
12409         if (dynamic)
12410                 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);
12411         else
12412                 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
12413                         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);
12414 }
12415 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)
12416 {
12417         matrix4x4_t projection;
12418         decalsystem_t *decalsystem;
12419         qboolean dynamic;
12420         dp_model_t *model;
12421         const msurface_t *surface;
12422         const msurface_t *surfaces;
12423         const int *surfacelist;
12424         const texture_t *texture;
12425         int numtriangles;
12426         int numsurfacelist;
12427         int surfacelistindex;
12428         int surfaceindex;
12429         int triangleindex;
12430         float localorigin[3];
12431         float localnormal[3];
12432         float localmins[3];
12433         float localmaxs[3];
12434         float localsize;
12435         //float normal[3];
12436         float planes[6][4];
12437         float angles[3];
12438         bih_t *bih;
12439         int bih_triangles_count;
12440         int bih_triangles[256];
12441         int bih_surfaces[256];
12442
12443         decalsystem = &ent->decalsystem;
12444         model = ent->model;
12445         if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
12446         {
12447                 R_DecalSystem_Reset(&ent->decalsystem);
12448                 return;
12449         }
12450
12451         if (!model->brush.data_nodes && !cl_decals_models.integer)
12452         {
12453                 if (decalsystem->model)
12454                         R_DecalSystem_Reset(decalsystem);
12455                 return;
12456         }
12457
12458         if (decalsystem->model != model)
12459                 R_DecalSystem_Reset(decalsystem);
12460         decalsystem->model = model;
12461
12462         RSurf_ActiveModelEntity(ent, false, false, false);
12463
12464         Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
12465         Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
12466         VectorNormalize(localnormal);
12467         localsize = worldsize*rsurface.inversematrixscale;
12468         localmins[0] = localorigin[0] - localsize;
12469         localmins[1] = localorigin[1] - localsize;
12470         localmins[2] = localorigin[2] - localsize;
12471         localmaxs[0] = localorigin[0] + localsize;
12472         localmaxs[1] = localorigin[1] + localsize;
12473         localmaxs[2] = localorigin[2] + localsize;
12474
12475         //VectorCopy(localnormal, planes[4]);
12476         //VectorVectors(planes[4], planes[2], planes[0]);
12477         AnglesFromVectors(angles, localnormal, NULL, false);
12478         AngleVectors(angles, planes[0], planes[2], planes[4]);
12479         VectorNegate(planes[0], planes[1]);
12480         VectorNegate(planes[2], planes[3]);
12481         VectorNegate(planes[4], planes[5]);
12482         planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
12483         planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
12484         planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
12485         planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
12486         planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
12487         planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
12488
12489 #if 1
12490 // works
12491 {
12492         matrix4x4_t forwardprojection;
12493         Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
12494         Matrix4x4_Invert_Simple(&projection, &forwardprojection);
12495 }
12496 #else
12497 // broken
12498 {
12499         float projectionvector[4][3];
12500         VectorScale(planes[0], ilocalsize, projectionvector[0]);
12501         VectorScale(planes[2], ilocalsize, projectionvector[1]);
12502         VectorScale(planes[4], ilocalsize, projectionvector[2]);
12503         projectionvector[0][0] = planes[0][0] * ilocalsize;
12504         projectionvector[0][1] = planes[1][0] * ilocalsize;
12505         projectionvector[0][2] = planes[2][0] * ilocalsize;
12506         projectionvector[1][0] = planes[0][1] * ilocalsize;
12507         projectionvector[1][1] = planes[1][1] * ilocalsize;
12508         projectionvector[1][2] = planes[2][1] * ilocalsize;
12509         projectionvector[2][0] = planes[0][2] * ilocalsize;
12510         projectionvector[2][1] = planes[1][2] * ilocalsize;
12511         projectionvector[2][2] = planes[2][2] * ilocalsize;
12512         projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
12513         projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
12514         projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
12515         Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
12516 }
12517 #endif
12518
12519         dynamic = model->surfmesh.isanimated;
12520         numsurfacelist = model->nummodelsurfaces;
12521         surfacelist = model->sortedmodelsurfaces;
12522         surfaces = model->data_surfaces;
12523
12524         bih = NULL;
12525         bih_triangles_count = -1;
12526         if(!dynamic)
12527         {
12528                 if(model->render_bih.numleafs)
12529                         bih = &model->render_bih;
12530                 else if(model->collision_bih.numleafs)
12531                         bih = &model->collision_bih;
12532         }
12533         if(bih)
12534                 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
12535         if(bih_triangles_count == 0)
12536                 return;
12537         if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
12538                 return;
12539         if(bih_triangles_count > 0)
12540         {
12541                 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
12542                 {
12543                         surfaceindex = bih_surfaces[triangleindex];
12544                         surface = surfaces + surfaceindex;
12545                         texture = surface->texture;
12546                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12547                                 continue;
12548                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12549                                 continue;
12550                         R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
12551                 }
12552         }
12553         else
12554         {
12555                 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
12556                 {
12557                         surfaceindex = surfacelist[surfacelistindex];
12558                         surface = surfaces + surfaceindex;
12559                         // check cull box first because it rejects more than any other check
12560                         if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
12561                                 continue;
12562                         // skip transparent surfaces
12563                         texture = surface->texture;
12564                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12565                                 continue;
12566                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12567                                 continue;
12568                         numtriangles = surface->num_triangles;
12569                         for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
12570                                 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
12571                 }
12572         }
12573 }
12574
12575 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
12576 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)
12577 {
12578         int renderentityindex;
12579         float worldmins[3];
12580         float worldmaxs[3];
12581         entity_render_t *ent;
12582
12583         if (!cl_decals_newsystem.integer)
12584                 return;
12585
12586         worldmins[0] = worldorigin[0] - worldsize;
12587         worldmins[1] = worldorigin[1] - worldsize;
12588         worldmins[2] = worldorigin[2] - worldsize;
12589         worldmaxs[0] = worldorigin[0] + worldsize;
12590         worldmaxs[1] = worldorigin[1] + worldsize;
12591         worldmaxs[2] = worldorigin[2] + worldsize;
12592
12593         R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12594
12595         for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
12596         {
12597                 ent = r_refdef.scene.entities[renderentityindex];
12598                 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
12599                         continue;
12600
12601                 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12602         }
12603 }
12604
12605 typedef struct r_decalsystem_splatqueue_s
12606 {
12607         vec3_t worldorigin;
12608         vec3_t worldnormal;
12609         float color[4];
12610         float tcrange[4];
12611         float worldsize;
12612         int decalsequence;
12613 }
12614 r_decalsystem_splatqueue_t;
12615
12616 int r_decalsystem_numqueued = 0;
12617 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
12618
12619 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)
12620 {
12621         r_decalsystem_splatqueue_t *queue;
12622
12623         if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
12624                 return;
12625
12626         queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
12627         VectorCopy(worldorigin, queue->worldorigin);
12628         VectorCopy(worldnormal, queue->worldnormal);
12629         Vector4Set(queue->color, r, g, b, a);
12630         Vector4Set(queue->tcrange, s1, t1, s2, t2);
12631         queue->worldsize = worldsize;
12632         queue->decalsequence = cl.decalsequence++;
12633 }
12634
12635 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
12636 {
12637         int i;
12638         r_decalsystem_splatqueue_t *queue;
12639
12640         for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
12641                 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);
12642         r_decalsystem_numqueued = 0;
12643 }
12644
12645 extern cvar_t cl_decals_max;
12646 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
12647 {
12648         int i;
12649         decalsystem_t *decalsystem = &ent->decalsystem;
12650         int numdecals;
12651         int killsequence;
12652         tridecal_t *decal;
12653         float frametime;
12654         float lifetime;
12655
12656         if (!decalsystem->numdecals)
12657                 return;
12658
12659         if (r_showsurfaces.integer)
12660                 return;
12661
12662         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12663         {
12664                 R_DecalSystem_Reset(decalsystem);
12665                 return;
12666         }
12667
12668         killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
12669         lifetime = cl_decals_time.value + cl_decals_fadetime.value;
12670
12671         if (decalsystem->lastupdatetime)
12672                 frametime = (cl.time - decalsystem->lastupdatetime);
12673         else
12674                 frametime = 0;
12675         decalsystem->lastupdatetime = cl.time;
12676         decal = decalsystem->decals;
12677         numdecals = decalsystem->numdecals;
12678
12679         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12680         {
12681                 if (decal->color4ub[0][3])
12682                 {
12683                         decal->lived += frametime;
12684                         if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
12685                         {
12686                                 memset(decal, 0, sizeof(*decal));
12687                                 if (decalsystem->freedecal > i)
12688                                         decalsystem->freedecal = i;
12689                         }
12690                 }
12691         }
12692         decal = decalsystem->decals;
12693         while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
12694                 numdecals--;
12695
12696         // collapse the array by shuffling the tail decals into the gaps
12697         for (;;)
12698         {
12699                 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
12700                         decalsystem->freedecal++;
12701                 if (decalsystem->freedecal == numdecals)
12702                         break;
12703                 decal[decalsystem->freedecal] = decal[--numdecals];
12704         }
12705
12706         decalsystem->numdecals = numdecals;
12707
12708         if (numdecals <= 0)
12709         {
12710                 // if there are no decals left, reset decalsystem
12711                 R_DecalSystem_Reset(decalsystem);
12712         }
12713 }
12714
12715 extern skinframe_t *decalskinframe;
12716 static void R_DrawModelDecals_Entity(entity_render_t *ent)
12717 {
12718         int i;
12719         decalsystem_t *decalsystem = &ent->decalsystem;
12720         int numdecals;
12721         tridecal_t *decal;
12722         float faderate;
12723         float alpha;
12724         float *v3f;
12725         float *c4f;
12726         float *t2f;
12727         const int *e;
12728         const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
12729         int numtris = 0;
12730
12731         numdecals = decalsystem->numdecals;
12732         if (!numdecals)
12733                 return;
12734
12735         if (r_showsurfaces.integer)
12736                 return;
12737
12738         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12739         {
12740                 R_DecalSystem_Reset(decalsystem);
12741                 return;
12742         }
12743
12744         // if the model is static it doesn't matter what value we give for
12745         // wantnormals and wanttangents, so this logic uses only rules applicable
12746         // to a model, knowing that they are meaningless otherwise
12747         if (ent == r_refdef.scene.worldentity)
12748                 RSurf_ActiveWorldEntity();
12749         else
12750                 RSurf_ActiveModelEntity(ent, false, false, false);
12751
12752         decalsystem->lastupdatetime = cl.time;
12753         decal = decalsystem->decals;
12754
12755         faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
12756
12757         // update vertex positions for animated models
12758         v3f = decalsystem->vertex3f;
12759         c4f = decalsystem->color4f;
12760         t2f = decalsystem->texcoord2f;
12761         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12762         {
12763                 if (!decal->color4ub[0][3])
12764                         continue;
12765
12766                 if (surfacevisible && !surfacevisible[decal->surfaceindex])
12767                         continue;
12768
12769                 // update color values for fading decals
12770                 if (decal->lived >= cl_decals_time.value)
12771                 {
12772                         alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
12773                         alpha *= (1.0f/255.0f);
12774                 }
12775                 else
12776                         alpha = 1.0f/255.0f;
12777
12778                 c4f[ 0] = decal->color4ub[0][0] * alpha;
12779                 c4f[ 1] = decal->color4ub[0][1] * alpha;
12780                 c4f[ 2] = decal->color4ub[0][2] * alpha;
12781                 c4f[ 3] = 1;
12782                 c4f[ 4] = decal->color4ub[1][0] * alpha;
12783                 c4f[ 5] = decal->color4ub[1][1] * alpha;
12784                 c4f[ 6] = decal->color4ub[1][2] * alpha;
12785                 c4f[ 7] = 1;
12786                 c4f[ 8] = decal->color4ub[2][0] * alpha;
12787                 c4f[ 9] = decal->color4ub[2][1] * alpha;
12788                 c4f[10] = decal->color4ub[2][2] * alpha;
12789                 c4f[11] = 1;
12790
12791                 t2f[0] = decal->texcoord2f[0][0];
12792                 t2f[1] = decal->texcoord2f[0][1];
12793                 t2f[2] = decal->texcoord2f[1][0];
12794                 t2f[3] = decal->texcoord2f[1][1];
12795                 t2f[4] = decal->texcoord2f[2][0];
12796                 t2f[5] = decal->texcoord2f[2][1];
12797
12798                 // update vertex positions for animated models
12799                 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnum_triangles)
12800                 {
12801                         e = rsurface.modelelement3i + 3*decal->triangleindex;
12802                         VectorCopy(rsurface.vertex3f + 3*e[0], v3f);
12803                         VectorCopy(rsurface.vertex3f + 3*e[1], v3f + 3);
12804                         VectorCopy(rsurface.vertex3f + 3*e[2], v3f + 6);
12805                 }
12806                 else
12807                 {
12808                         VectorCopy(decal->vertex3f[0], v3f);
12809                         VectorCopy(decal->vertex3f[1], v3f + 3);
12810                         VectorCopy(decal->vertex3f[2], v3f + 6);
12811                 }
12812
12813                 if (r_refdef.fogenabled)
12814                 {
12815                         alpha = RSurf_FogVertex(v3f);
12816                         VectorScale(c4f, alpha, c4f);
12817                         alpha = RSurf_FogVertex(v3f + 3);
12818                         VectorScale(c4f + 4, alpha, c4f + 4);
12819                         alpha = RSurf_FogVertex(v3f + 6);
12820                         VectorScale(c4f + 8, alpha, c4f + 8);
12821                 }
12822
12823                 v3f += 9;
12824                 c4f += 12;
12825                 t2f += 6;
12826                 numtris++;
12827         }
12828
12829         if (numtris > 0)
12830         {
12831                 r_refdef.stats.drawndecals += numtris;
12832
12833                 // now render the decals all at once
12834                 // (this assumes they all use one particle font texture!)
12835                 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);
12836                 R_Mesh_ResetTextureState();
12837                 R_Mesh_VertexPointer(decalsystem->vertex3f, 0, 0);
12838                 R_Mesh_TexCoordPointer(0, 2, decalsystem->texcoord2f, 0, 0);
12839                 R_Mesh_ColorPointer(decalsystem->color4f, 0, 0);
12840                 GL_DepthMask(false);
12841                 GL_DepthRange(0, 1);
12842                 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
12843                 GL_DepthTest(true);
12844                 GL_CullFace(GL_NONE);
12845                 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
12846                 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
12847                 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, decalsystem->element3s, 0, 0);
12848         }
12849 }
12850
12851 static void R_DrawModelDecals(void)
12852 {
12853         int i, numdecals;
12854
12855         // fade faster when there are too many decals
12856         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12857         for (i = 0;i < r_refdef.scene.numentities;i++)
12858                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12859
12860         R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
12861         for (i = 0;i < r_refdef.scene.numentities;i++)
12862                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12863                         R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
12864
12865         R_DecalSystem_ApplySplatEntitiesQueue();
12866
12867         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12868         for (i = 0;i < r_refdef.scene.numentities;i++)
12869                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12870
12871         r_refdef.stats.totaldecals += numdecals;
12872
12873         if (r_showsurfaces.integer)
12874                 return;
12875
12876         R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
12877
12878         for (i = 0;i < r_refdef.scene.numentities;i++)
12879         {
12880                 if (!r_refdef.viewcache.entityvisible[i])
12881                         continue;
12882                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12883                         R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
12884         }
12885 }
12886
12887 extern cvar_t mod_collision_bih;
12888 void R_DrawDebugModel(void)
12889 {
12890         entity_render_t *ent = rsurface.entity;
12891         int i, j, k, l, flagsmask;
12892         const msurface_t *surface;
12893         dp_model_t *model = ent->model;
12894         vec3_t v;
12895
12896         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
12897
12898         R_Mesh_ColorPointer(NULL, 0, 0);
12899         R_Mesh_ResetTextureState();
12900         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12901         GL_DepthRange(0, 1);
12902         GL_DepthTest(!r_showdisabledepthtest.integer);
12903         GL_DepthMask(false);
12904         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12905
12906         if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
12907         {
12908                 int triangleindex;
12909                 int bihleafindex;
12910                 qboolean cullbox = ent == r_refdef.scene.worldentity;
12911                 const q3mbrush_t *brush;
12912                 const bih_t *bih = &model->collision_bih;
12913                 const bih_leaf_t *bihleaf;
12914                 float vertex3f[3][3];
12915                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
12916                 cullbox = false;
12917                 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
12918                 {
12919                         if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
12920                                 continue;
12921                         switch (bihleaf->type)
12922                         {
12923                         case BIH_BRUSH:
12924                                 brush = model->brush.data_brushes + bihleaf->itemindex;
12925                                 if (brush->colbrushf && brush->colbrushf->numtriangles)
12926                                 {
12927                                         R_Mesh_VertexPointer(brush->colbrushf->points->v, 0, 0);
12928                                         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);
12929                                         R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, 0);
12930                                 }
12931                                 break;
12932                         case BIH_COLLISIONTRIANGLE:
12933                                 triangleindex = bihleaf->itemindex;
12934                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
12935                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
12936                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
12937                                 R_Mesh_VertexPointer(vertex3f[0], 0, 0);
12938                                 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);
12939                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, polygonelement3s, 0, 0);
12940                                 break;
12941                         case BIH_RENDERTRIANGLE:
12942                                 triangleindex = bihleaf->itemindex;
12943                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
12944                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
12945                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
12946                                 R_Mesh_VertexPointer(vertex3f[0], 0, 0);
12947                                 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);
12948                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, polygonelement3s, 0, 0);
12949                                 break;
12950                         }
12951                 }
12952         }
12953
12954         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12955
12956         if (r_showtris.integer || r_shownormals.integer)
12957         {
12958                 if (r_showdisabledepthtest.integer)
12959                 {
12960                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12961                         GL_DepthMask(false);
12962                 }
12963                 else
12964                 {
12965                         GL_BlendFunc(GL_ONE, GL_ZERO);
12966                         GL_DepthMask(true);
12967                 }
12968                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
12969                 {
12970                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
12971                                 continue;
12972                         rsurface.texture = R_GetCurrentTexture(surface->texture);
12973                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
12974                         {
12975                                 RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
12976                                 if (r_showtris.value > 0)
12977                                 {
12978                                         if (!rsurface.texture->currentlayers->depthmask)
12979                                                 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
12980                                         else if (ent == r_refdef.scene.worldentity)
12981                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
12982                                         else
12983                                                 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
12984                                         R_Mesh_VertexPointer(rsurface.vertex3f, 0, 0);
12985                                         R_Mesh_ColorPointer(NULL, 0, 0);
12986                                         R_Mesh_TexCoordPointer(0, 0, NULL, 0, 0);
12987                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
12988                                         //R_Mesh_Draw(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, model->surfmesh.data_element3i, NULL, 0, 0);
12989                                         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);
12990                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
12991                                         CHECKGLERROR
12992                                 }
12993                                 if (r_shownormals.value < 0)
12994                                 {
12995                                         qglBegin(GL_LINES);
12996                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12997                                         {
12998                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
12999                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13000                                                 qglVertex3f(v[0], v[1], v[2]);
13001                                                 VectorMA(v, -r_shownormals.value, rsurface.svector3f + l * 3, v);
13002                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13003                                                 qglVertex3f(v[0], v[1], v[2]);
13004                                         }
13005                                         qglEnd();
13006                                         CHECKGLERROR
13007                                 }
13008                                 if (r_shownormals.value > 0)
13009                                 {
13010                                         qglBegin(GL_LINES);
13011                                         for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13012                                         {
13013                                                 VectorCopy(rsurface.vertex3f + l * 3, v);
13014                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13015                                                 qglVertex3f(v[0], v[1], v[2]);
13016                                                 VectorMA(v, r_shownormals.value, rsurface.svector3f + l * 3, v);
13017                                                 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13018                                                 qglVertex3f(v[0], v[1], v[2]);
13019                                         }
13020                                         qglEnd();
13021                                         CHECKGLERROR
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(0, r_refdef.view.colorscale, 0, 1);
13027                                                 qglVertex3f(v[0], v[1], v[2]);
13028                                                 VectorMA(v, r_shownormals.value, rsurface.tvector3f + 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, 0, r_refdef.view.colorscale, 1);
13039                                                 qglVertex3f(v[0], v[1], v[2]);
13040                                                 VectorMA(v, r_shownormals.value, rsurface.normal3f + 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                                 }
13047                         }
13048                 }
13049                 rsurface.texture = NULL;
13050         }
13051 }
13052
13053 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13054 int r_maxsurfacelist = 0;
13055 const msurface_t **r_surfacelist = NULL;
13056 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13057 {
13058         int i, j, endj, flagsmask;
13059         dp_model_t *model = r_refdef.scene.worldmodel;
13060         msurface_t *surfaces;
13061         unsigned char *update;
13062         int numsurfacelist = 0;
13063         if (model == NULL)
13064                 return;
13065
13066         if (r_maxsurfacelist < model->num_surfaces)
13067         {
13068                 r_maxsurfacelist = model->num_surfaces;
13069                 if (r_surfacelist)
13070                         Mem_Free((msurface_t**)r_surfacelist);
13071                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13072         }
13073
13074         RSurf_ActiveWorldEntity();
13075
13076         surfaces = model->data_surfaces;
13077         update = model->brushq1.lightmapupdateflags;
13078
13079         // update light styles on this submodel
13080         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13081         {
13082                 model_brush_lightstyleinfo_t *style;
13083                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13084                 {
13085                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
13086                         {
13087                                 int *list = style->surfacelist;
13088                                 style->value = r_refdef.scene.lightstylevalue[style->style];
13089                                 for (j = 0;j < style->numsurfaces;j++)
13090                                         update[list[j]] = true;
13091                         }
13092                 }
13093         }
13094
13095         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13096
13097         if (debug)
13098         {
13099                 R_DrawDebugModel();
13100                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13101                 return;
13102         }
13103
13104         rsurface.uselightmaptexture = false;
13105         rsurface.texture = NULL;
13106         rsurface.rtlight = NULL;
13107         numsurfacelist = 0;
13108         // add visible surfaces to draw list
13109         for (i = 0;i < model->nummodelsurfaces;i++)
13110         {
13111                 j = model->sortedmodelsurfaces[i];
13112                 if (r_refdef.viewcache.world_surfacevisible[j])
13113                         r_surfacelist[numsurfacelist++] = surfaces + j;
13114         }
13115         // update lightmaps if needed
13116         if (model->brushq1.firstrender)
13117         {
13118                 model->brushq1.firstrender = false;
13119                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13120                         if (update[j])
13121                                 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13122         }
13123         else if (update)
13124         {
13125                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13126                         if (r_refdef.viewcache.world_surfacevisible[j])
13127                                 if (update[j])
13128                                         R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13129         }
13130         // don't do anything if there were no surfaces
13131         if (!numsurfacelist)
13132         {
13133                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13134                 return;
13135         }
13136         R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13137         GL_AlphaTest(false);
13138
13139         // add to stats if desired
13140         if (r_speeds.integer && !skysurfaces && !depthonly)
13141         {
13142                 r_refdef.stats.world_surfaces += numsurfacelist;
13143                 for (j = 0;j < numsurfacelist;j++)
13144                         r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13145         }
13146
13147         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13148 }
13149
13150 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13151 {
13152         int i, j, endj, flagsmask;
13153         dp_model_t *model = ent->model;
13154         msurface_t *surfaces;
13155         unsigned char *update;
13156         int numsurfacelist = 0;
13157         if (model == NULL)
13158                 return;
13159
13160         if (r_maxsurfacelist < model->num_surfaces)
13161         {
13162                 r_maxsurfacelist = model->num_surfaces;
13163                 if (r_surfacelist)
13164                         Mem_Free((msurface_t **)r_surfacelist);
13165                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13166         }
13167
13168         // if the model is static it doesn't matter what value we give for
13169         // wantnormals and wanttangents, so this logic uses only rules applicable
13170         // to a model, knowing that they are meaningless otherwise
13171         if (ent == r_refdef.scene.worldentity)
13172                 RSurf_ActiveWorldEntity();
13173         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13174                 RSurf_ActiveModelEntity(ent, false, false, false);
13175         else if (prepass)
13176                 RSurf_ActiveModelEntity(ent, true, true, true);
13177         else if (depthonly)
13178         {
13179                 switch (vid.renderpath)
13180                 {
13181                 case RENDERPATH_GL20:
13182                 case RENDERPATH_CGGL:
13183                         RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
13184                         break;
13185                 case RENDERPATH_GL13:
13186                 case RENDERPATH_GL11:
13187                         RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
13188                         break;
13189                 }
13190         }
13191         else
13192         {
13193                 switch (vid.renderpath)
13194                 {
13195                 case RENDERPATH_GL20:
13196                 case RENDERPATH_CGGL:
13197                         RSurf_ActiveModelEntity(ent, true, true, false);
13198                         break;
13199                 case RENDERPATH_GL13:
13200                 case RENDERPATH_GL11:
13201                         RSurf_ActiveModelEntity(ent, true, false, false);
13202                         break;
13203                 }
13204         }
13205
13206         surfaces = model->data_surfaces;
13207         update = model->brushq1.lightmapupdateflags;
13208
13209         // update light styles
13210         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13211         {
13212                 model_brush_lightstyleinfo_t *style;
13213                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13214                 {
13215                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
13216                         {
13217                                 int *list = style->surfacelist;
13218                                 style->value = r_refdef.scene.lightstylevalue[style->style];
13219                                 for (j = 0;j < style->numsurfaces;j++)
13220                                         update[list[j]] = true;
13221                         }
13222                 }
13223         }
13224
13225         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13226
13227         if (debug)
13228         {
13229                 R_DrawDebugModel();
13230                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13231                 return;
13232         }
13233
13234         rsurface.uselightmaptexture = false;
13235         rsurface.texture = NULL;
13236         rsurface.rtlight = NULL;
13237         numsurfacelist = 0;
13238         // add visible surfaces to draw list
13239         for (i = 0;i < model->nummodelsurfaces;i++)
13240                 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13241         // don't do anything if there were no surfaces
13242         if (!numsurfacelist)
13243         {
13244                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13245                 return;
13246         }
13247         // update lightmaps if needed
13248         if (update)
13249         {
13250                 int updated = 0;
13251                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13252                 {
13253                         if (update[j])
13254                         {
13255                                 updated++;
13256                                 R_BuildLightMap(ent, surfaces + j);
13257                         }
13258                 }
13259         }
13260         if (update)
13261                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13262                         if (update[j])
13263                                 R_BuildLightMap(ent, surfaces + j);
13264         R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13265         GL_AlphaTest(false);
13266
13267         // add to stats if desired
13268         if (r_speeds.integer && !skysurfaces && !depthonly)
13269         {
13270                 r_refdef.stats.entities_surfaces += numsurfacelist;
13271                 for (j = 0;j < numsurfacelist;j++)
13272                         r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13273         }
13274
13275         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13276 }
13277
13278 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13279 {
13280         static texture_t texture;
13281         static msurface_t surface;
13282         const msurface_t *surfacelist = &surface;
13283
13284         // fake enough texture and surface state to render this geometry
13285
13286         texture.update_lastrenderframe = -1; // regenerate this texture
13287         texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
13288         texture.currentskinframe = skinframe;
13289         texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
13290         texture.offsetmapping = OFFSETMAPPING_OFF;
13291         texture.offsetscale = 1;
13292         texture.specularscalemod = 1;
13293         texture.specularpowermod = 1;
13294
13295         surface.texture = &texture;
13296         surface.num_triangles = numtriangles;
13297         surface.num_firsttriangle = firsttriangle;
13298         surface.num_vertices = numvertices;
13299         surface.num_firstvertex = firstvertex;
13300
13301         // now render it
13302         rsurface.texture = R_GetCurrentTexture(surface.texture);
13303         rsurface.uselightmaptexture = false;
13304         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13305 }
13306
13307 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)
13308 {
13309         static msurface_t surface;
13310         const msurface_t *surfacelist = &surface;
13311
13312         // fake enough texture and surface state to render this geometry
13313
13314         surface.texture = texture;
13315         surface.num_triangles = numtriangles;
13316         surface.num_firsttriangle = firsttriangle;
13317         surface.num_vertices = numvertices;
13318         surface.num_firstvertex = firstvertex;
13319
13320         // now render it
13321         rsurface.texture = R_GetCurrentTexture(surface.texture);
13322         rsurface.uselightmaptexture = false;
13323         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13324 }