]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_rmain.c
oops, forgot to include the shader code for the r_shadow_bouncegrid feature
[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 #include "dpsoftrast.h"
31
32 #ifdef SUPPORTD3D
33 #include <d3d9.h>
34 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
35 #endif
36
37 mempool_t *r_main_mempool;
38 rtexturepool_t *r_main_texturepool;
39
40 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
41
42 static qboolean r_loadnormalmap;
43 static qboolean r_loadgloss;
44 qboolean r_loadfog;
45 static qboolean r_loaddds;
46 static qboolean r_savedds;
47
48 //
49 // screen size info
50 //
51 r_refdef_t r_refdef;
52
53 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
54 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
55 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
56 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
57 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)"};
58 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
59 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
60 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
61
62 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
63 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"};
64 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
65 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)"};
66 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
67
68 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"};
69 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
70 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
71 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
72 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
73 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%,  10 = 100%)"};
74 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)"};
75 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
76 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
77 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"};
78 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"};
79 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
80 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"};
81 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"};
82 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"};
83 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
84 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
85 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
86 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
87 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
88 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
89 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
90 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)"};
91 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)"};
92 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
93 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
94 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
95 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
96
97 cvar_t r_fakelight = {0, "r_fakelight","0", "render 'fake' lighting instead of real lightmaps"};
98 cvar_t r_fakelight_intensity = {0, "r_fakelight_intensity","0.75", "fakelight intensity modifier"};
99 #define FAKELIGHT_ENABLED (r_fakelight.integer >= 2 || (r_fakelight.integer && r_refdef.scene.worldmodel && !r_refdef.scene.worldmodel->lit))
100
101 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
102 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
103 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
104 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."};
105 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
106 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
107 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
108 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."};
109 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
110 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
111 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
112 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
113 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"};
114 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"};
115 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
116 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
117 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
118 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
119 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"};
120
121 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
122 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
123 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
124 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
125 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
126 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
127 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
128 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
129
130 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)"};
131 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"};
132
133 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
134 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
135 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
136 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
137 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
138
139 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
140 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
141 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
142
143 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)"};
144 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
145 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
146 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
147 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
148 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)"};
149 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)"};
150 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)"};
151 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)"};
152 cvar_t r_glsl_postprocess_uservec1_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec1_enable", "1", "enables postprocessing uservec1 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
153 cvar_t r_glsl_postprocess_uservec2_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec2_enable", "1", "enables postprocessing uservec2 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
154 cvar_t r_glsl_postprocess_uservec3_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec3_enable", "1", "enables postprocessing uservec3 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
155 cvar_t r_glsl_postprocess_uservec4_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec4_enable", "1", "enables postprocessing uservec4 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
156
157 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)"};
158 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
159 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"};
160 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
161 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
162 cvar_t r_water_scissormode = {0, "r_water_scissormode", "3", "scissor (1) or cull (2) or both (3) water renders"};
163
164 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
165 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
166 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
167 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
168
169 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
170 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
171 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
172 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
173 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
174 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exaggerated the glow is"};
175 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
176
177 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
178 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
179 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
180 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivalent to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
181 cvar_t r_hdr_irisadaptation = {CVAR_SAVE, "r_hdr_irisadaptation", "0", "adjust scene brightness according to light intensity at player location"};
182 cvar_t r_hdr_irisadaptation_multiplier = {CVAR_SAVE, "r_hdr_irisadaptation_multiplier", "2", "brightness at which value will be 1.0"};
183 cvar_t r_hdr_irisadaptation_minvalue = {CVAR_SAVE, "r_hdr_irisadaptation_minvalue", "0.5", "minimum value that can result from multiplier / brightness"};
184 cvar_t r_hdr_irisadaptation_maxvalue = {CVAR_SAVE, "r_hdr_irisadaptation_maxvalue", "4", "maximum value that can result from multiplier / brightness"};
185 cvar_t r_hdr_irisadaptation_value = {0, "r_hdr_irisadaptation_value", "1", "current value as scenebrightness multiplier, changes continuously when irisadaptation is active"};
186 cvar_t r_hdr_irisadaptation_fade = {CVAR_SAVE, "r_hdr_irisadaptation_fade", "1", "fade rate at which value adjusts"};
187
188 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"};
189
190 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"};
191
192 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
193
194 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
195 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"};
196 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accordingly, 2: Make it a continuous rotation"};
197 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
198 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
199 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "5", "fake perspective effect for SPR_OVERHEAD sprites"};
200 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "15", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
201 cvar_t r_overheadsprites_scalex = {CVAR_SAVE, "r_overheadsprites_scalex", "1", "additional scale for overhead sprites for x axis"};
202 cvar_t r_overheadsprites_scaley = {CVAR_SAVE, "r_overheadsprites_scaley", "1", "additional scale for overhead sprites for y axis"};
203
204 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
205 cvar_t r_glsl_saturation_redcompensate = {CVAR_SAVE, "r_glsl_saturation_redcompensate", "0", "a 'vampire sight' addition to desaturation effect, does compensation for red color, r_glsl_restart is required"};
206
207 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "0.5", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
208
209 extern cvar_t v_glslgamma;
210
211 extern qboolean v_flipped_state;
212
213 static struct r_bloomstate_s
214 {
215         qboolean enabled;
216         qboolean hdr;
217
218         int bloomwidth, bloomheight;
219
220         int screentexturewidth, screentextureheight;
221         rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
222
223         int bloomtexturewidth, bloomtextureheight;
224         rtexture_t *texture_bloom;
225
226         // arrays for rendering the screen passes
227         float screentexcoord2f[8];
228         float bloomtexcoord2f[8];
229         float offsettexcoord2f[8];
230
231         r_viewport_t viewport;
232 }
233 r_bloomstate;
234
235 r_waterstate_t r_waterstate;
236
237 /// shadow volume bsp struct with automatically growing nodes buffer
238 svbsp_t r_svbsp;
239
240 rtexture_t *r_texture_blanknormalmap;
241 rtexture_t *r_texture_white;
242 rtexture_t *r_texture_grey128;
243 rtexture_t *r_texture_black;
244 rtexture_t *r_texture_notexture;
245 rtexture_t *r_texture_whitecube;
246 rtexture_t *r_texture_normalizationcube;
247 rtexture_t *r_texture_fogattenuation;
248 rtexture_t *r_texture_fogheighttexture;
249 rtexture_t *r_texture_gammaramps;
250 unsigned int r_texture_gammaramps_serial;
251 //rtexture_t *r_texture_fogintensity;
252 rtexture_t *r_texture_reflectcube;
253
254 // TODO: hash lookups?
255 typedef struct cubemapinfo_s
256 {
257         char basename[64];
258         rtexture_t *texture;
259 }
260 cubemapinfo_t;
261
262 int r_texture_numcubemaps;
263 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
264
265 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
266 unsigned int r_numqueries;
267 unsigned int r_maxqueries;
268
269 typedef struct r_qwskincache_s
270 {
271         char name[MAX_QPATH];
272         skinframe_t *skinframe;
273 }
274 r_qwskincache_t;
275
276 static r_qwskincache_t *r_qwskincache;
277 static int r_qwskincache_size;
278
279 /// vertex coordinates for a quad that covers the screen exactly
280 extern const float r_screenvertex3f[12];
281 extern const float r_d3dscreenvertex3f[12];
282 const float r_screenvertex3f[12] =
283 {
284         0, 0, 0,
285         1, 0, 0,
286         1, 1, 0,
287         0, 1, 0
288 };
289 const float r_d3dscreenvertex3f[12] =
290 {
291         0, 1, 0,
292         1, 1, 0,
293         1, 0, 0,
294         0, 0, 0
295 };
296
297 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
298 {
299         int i;
300         for (i = 0;i < verts;i++)
301         {
302                 out[0] = in[0] * r;
303                 out[1] = in[1] * g;
304                 out[2] = in[2] * b;
305                 out[3] = in[3];
306                 in += 4;
307                 out += 4;
308         }
309 }
310
311 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
312 {
313         int i;
314         for (i = 0;i < verts;i++)
315         {
316                 out[0] = r;
317                 out[1] = g;
318                 out[2] = b;
319                 out[3] = a;
320                 out += 4;
321         }
322 }
323
324 // FIXME: move this to client?
325 void FOG_clear(void)
326 {
327         if (gamemode == GAME_NEHAHRA)
328         {
329                 Cvar_Set("gl_fogenable", "0");
330                 Cvar_Set("gl_fogdensity", "0.2");
331                 Cvar_Set("gl_fogred", "0.3");
332                 Cvar_Set("gl_foggreen", "0.3");
333                 Cvar_Set("gl_fogblue", "0.3");
334         }
335         r_refdef.fog_density = 0;
336         r_refdef.fog_red = 0;
337         r_refdef.fog_green = 0;
338         r_refdef.fog_blue = 0;
339         r_refdef.fog_alpha = 1;
340         r_refdef.fog_start = 0;
341         r_refdef.fog_end = 16384;
342         r_refdef.fog_height = 1<<30;
343         r_refdef.fog_fadedepth = 128;
344         memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
345 }
346
347 static void R_BuildBlankTextures(void)
348 {
349         unsigned char data[4];
350         data[2] = 128; // normal X
351         data[1] = 128; // normal Y
352         data[0] = 255; // normal Z
353         data[3] = 128; // height
354         r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
355         data[0] = 255;
356         data[1] = 255;
357         data[2] = 255;
358         data[3] = 255;
359         r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
360         data[0] = 128;
361         data[1] = 128;
362         data[2] = 128;
363         data[3] = 255;
364         r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
365         data[0] = 0;
366         data[1] = 0;
367         data[2] = 0;
368         data[3] = 255;
369         r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
370 }
371
372 static void R_BuildNoTexture(void)
373 {
374         int x, y;
375         unsigned char pix[16][16][4];
376         // this makes a light grey/dark grey checkerboard texture
377         for (y = 0;y < 16;y++)
378         {
379                 for (x = 0;x < 16;x++)
380                 {
381                         if ((y < 8) ^ (x < 8))
382                         {
383                                 pix[y][x][0] = 128;
384                                 pix[y][x][1] = 128;
385                                 pix[y][x][2] = 128;
386                                 pix[y][x][3] = 255;
387                         }
388                         else
389                         {
390                                 pix[y][x][0] = 64;
391                                 pix[y][x][1] = 64;
392                                 pix[y][x][2] = 64;
393                                 pix[y][x][3] = 255;
394                         }
395                 }
396         }
397         r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
398 }
399
400 static void R_BuildWhiteCube(void)
401 {
402         unsigned char data[6*1*1*4];
403         memset(data, 255, sizeof(data));
404         r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
405 }
406
407 static void R_BuildNormalizationCube(void)
408 {
409         int x, y, side;
410         vec3_t v;
411         vec_t s, t, intensity;
412 #define NORMSIZE 64
413         unsigned char *data;
414         data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
415         for (side = 0;side < 6;side++)
416         {
417                 for (y = 0;y < NORMSIZE;y++)
418                 {
419                         for (x = 0;x < NORMSIZE;x++)
420                         {
421                                 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
422                                 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
423                                 switch(side)
424                                 {
425                                 default:
426                                 case 0:
427                                         v[0] = 1;
428                                         v[1] = -t;
429                                         v[2] = -s;
430                                         break;
431                                 case 1:
432                                         v[0] = -1;
433                                         v[1] = -t;
434                                         v[2] = s;
435                                         break;
436                                 case 2:
437                                         v[0] = s;
438                                         v[1] = 1;
439                                         v[2] = t;
440                                         break;
441                                 case 3:
442                                         v[0] = s;
443                                         v[1] = -1;
444                                         v[2] = -t;
445                                         break;
446                                 case 4:
447                                         v[0] = s;
448                                         v[1] = -t;
449                                         v[2] = 1;
450                                         break;
451                                 case 5:
452                                         v[0] = -s;
453                                         v[1] = -t;
454                                         v[2] = -1;
455                                         break;
456                                 }
457                                 intensity = 127.0f / sqrt(DotProduct(v, v));
458                                 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
459                                 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
460                                 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
461                                 data[((side*64+y)*64+x)*4+3] = 255;
462                         }
463                 }
464         }
465         r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
466         Mem_Free(data);
467 }
468
469 static void R_BuildFogTexture(void)
470 {
471         int x, b;
472 #define FOGWIDTH 256
473         unsigned char data1[FOGWIDTH][4];
474         //unsigned char data2[FOGWIDTH][4];
475         double d, r, alpha;
476
477         r_refdef.fogmasktable_start = r_refdef.fog_start;
478         r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
479         r_refdef.fogmasktable_range = r_refdef.fogrange;
480         r_refdef.fogmasktable_density = r_refdef.fog_density;
481
482         r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
483         for (x = 0;x < FOGMASKTABLEWIDTH;x++)
484         {
485                 d = (x * r - r_refdef.fogmasktable_start);
486                 if(developer_extra.integer)
487                         Con_DPrintf("%f ", d);
488                 d = max(0, d);
489                 if (r_fog_exp2.integer)
490                         alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
491                 else
492                         alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
493                 if(developer_extra.integer)
494                         Con_DPrintf(" : %f ", alpha);
495                 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
496                 if(developer_extra.integer)
497                         Con_DPrintf(" = %f\n", alpha);
498                 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
499         }
500
501         for (x = 0;x < FOGWIDTH;x++)
502         {
503                 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
504                 data1[x][0] = b;
505                 data1[x][1] = b;
506                 data1[x][2] = b;
507                 data1[x][3] = 255;
508                 //data2[x][0] = 255 - b;
509                 //data2[x][1] = 255 - b;
510                 //data2[x][2] = 255 - b;
511                 //data2[x][3] = 255;
512         }
513         if (r_texture_fogattenuation)
514         {
515                 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
516                 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
517         }
518         else
519         {
520                 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
521                 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
522         }
523 }
524
525 static void R_BuildFogHeightTexture(void)
526 {
527         unsigned char *inpixels;
528         int size;
529         int x;
530         int y;
531         int j;
532         float c[4];
533         float f;
534         inpixels = NULL;
535         strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
536         if (r_refdef.fogheighttexturename[0])
537                 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
538         if (!inpixels)
539         {
540                 r_refdef.fog_height_tablesize = 0;
541                 if (r_texture_fogheighttexture)
542                         R_FreeTexture(r_texture_fogheighttexture);
543                 r_texture_fogheighttexture = NULL;
544                 if (r_refdef.fog_height_table2d)
545                         Mem_Free(r_refdef.fog_height_table2d);
546                 r_refdef.fog_height_table2d = NULL;
547                 if (r_refdef.fog_height_table1d)
548                         Mem_Free(r_refdef.fog_height_table1d);
549                 r_refdef.fog_height_table1d = NULL;
550                 return;
551         }
552         size = image_width;
553         r_refdef.fog_height_tablesize = size;
554         r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
555         r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
556         memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
557         Mem_Free(inpixels);
558         // LordHavoc: now the magic - what is that table2d for?  it is a cooked
559         // average fog color table accounting for every fog layer between a point
560         // and the camera.  (Note: attenuation is handled separately!)
561         for (y = 0;y < size;y++)
562         {
563                 for (x = 0;x < size;x++)
564                 {
565                         Vector4Clear(c);
566                         f = 0;
567                         if (x < y)
568                         {
569                                 for (j = x;j <= y;j++)
570                                 {
571                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
572                                         f++;
573                                 }
574                         }
575                         else
576                         {
577                                 for (j = x;j >= y;j--)
578                                 {
579                                         Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
580                                         f++;
581                                 }
582                         }
583                         f = 1.0f / f;
584                         r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
585                         r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
586                         r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
587                         r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
588                 }
589         }
590         r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
591 }
592
593 //=======================================================================================================================================================
594
595 static const char *builtinshaderstring =
596 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
597 "// written by Forest 'LordHavoc' Hale\n"
598 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
599 "\n"
600 "// GL ES shaders use precision modifiers, standard GL does not\n"
601 "#ifndef GL_ES\n"
602 "#define lowp\n"
603 "#define mediump\n"
604 "#define highp\n"
605 "#endif\n"
606 "\n"
607 "#ifdef VERTEX_SHADER\n"
608 "attribute vec4 Attrib_Position;  // vertex\n"
609 "attribute vec4 Attrib_Color;     // color\n"
610 "attribute vec4 Attrib_TexCoord0; // material texcoords\n"
611 "attribute vec3 Attrib_TexCoord1; // svector\n"
612 "attribute vec3 Attrib_TexCoord2; // tvector\n"
613 "attribute vec3 Attrib_TexCoord3; // normal\n"
614 "attribute vec4 Attrib_TexCoord4; // lightmap texcoords\n"
615 "#endif\n"
616 "varying lowp vec4 VertexColor;\n"
617 "\n"
618 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
619 "# define USEFOG\n"
620 "#endif\n"
621 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
622 "#define USELIGHTMAP\n"
623 "#endif\n"
624 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
625 "#define USEEYEVECTOR\n"
626 "#endif\n"
627 "\n"
628 "#ifdef USESHADOWMAP2D\n"
629 "# ifdef GL_EXT_gpu_shader4\n"
630 "#   extension GL_EXT_gpu_shader4 : enable\n"
631 "# endif\n"
632 "# ifdef GL_ARB_texture_gather\n"
633 "#   extension GL_ARB_texture_gather : enable\n"
634 "# else\n"
635 "#   ifdef GL_AMD_texture_texture4\n"
636 "#     extension GL_AMD_texture_texture4 : enable\n"
637 "#   endif\n"
638 "# endif\n"
639 "#endif\n"
640 "\n"
641 "//#ifdef USESHADOWSAMPLER\n"
642 "//# extension GL_ARB_shadow : enable\n"
643 "//#endif\n"
644 "\n"
645 "//#ifdef __GLSL_CG_DATA_TYPES\n"
646 "//# define myhalf half\n"
647 "//# define myhalf2 half2\n"
648 "//# define myhalf3 half3\n"
649 "//# define myhalf4 half4\n"
650 "//#else\n"
651 "# define myhalf mediump float\n"
652 "# define myhalf2 mediump vec2\n"
653 "# define myhalf3 mediump vec3\n"
654 "# define myhalf4 mediump vec4\n"
655 "//#endif\n"
656 "\n"
657 "#ifdef VERTEX_SHADER\n"
658 "uniform highp mat4 ModelViewProjectionMatrix;\n"
659 "#endif\n"
660 "\n"
661 "#ifdef MODE_DEPTH_OR_SHADOW\n"
662 "#ifdef VERTEX_SHADER\n"
663 "void main(void)\n"
664 "{\n"
665 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
666 "}\n"
667 "#endif\n"
668 "#else // !MODE_DEPTH_ORSHADOW\n"
669 "\n"
670 "\n"
671 "\n"
672 "\n"
673 "#ifdef MODE_SHOWDEPTH\n"
674 "#ifdef VERTEX_SHADER\n"
675 "void main(void)\n"
676 "{\n"
677 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
678 "       VertexColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
679 "}\n"
680 "#endif\n"
681 "\n"
682 "#ifdef FRAGMENT_SHADER\n"
683 "void main(void)\n"
684 "{\n"
685 "       gl_FragColor = VertexColor;\n"
686 "}\n"
687 "#endif\n"
688 "#else // !MODE_SHOWDEPTH\n"
689 "\n"
690 "\n"
691 "\n"
692 "\n"
693 "#ifdef MODE_POSTPROCESS\n"
694 "varying mediump vec2 TexCoord1;\n"
695 "varying mediump vec2 TexCoord2;\n"
696 "\n"
697 "#ifdef VERTEX_SHADER\n"
698 "void main(void)\n"
699 "{\n"
700 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
701 "       TexCoord1 = Attrib_TexCoord0.xy;\n"
702 "#ifdef USEBLOOM\n"
703 "       TexCoord2 = Attrib_TexCoord4.xy;\n"
704 "#endif\n"
705 "}\n"
706 "#endif\n"
707 "\n"
708 "#ifdef FRAGMENT_SHADER\n"
709 "uniform sampler2D Texture_First;\n"
710 "#ifdef USEBLOOM\n"
711 "uniform sampler2D Texture_Second;\n"
712 "uniform lowp vec4 BloomColorSubtract;\n"
713 "#endif\n"
714 "#ifdef USEGAMMARAMPS\n"
715 "uniform sampler2D Texture_GammaRamps;\n"
716 "#endif\n"
717 "#ifdef USESATURATION\n"
718 "uniform lowp float Saturation;\n"
719 "#endif\n"
720 "#ifdef USEVIEWTINT\n"
721 "uniform lowp vec4 ViewTintColor;\n"
722 "#endif\n"
723 "//uncomment these if you want to use them:\n"
724 "uniform mediump vec4 UserVec1;\n"
725 "uniform mediump vec4 UserVec2;\n"
726 "// uniform mediump vec4 UserVec3;\n"
727 "// uniform mediump vec4 UserVec4;\n"
728 "// uniform highp float ClientTime;\n"
729 "uniform mediump vec2 PixelSize;\n"
730 "void main(void)\n"
731 "{\n"
732 "       gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
733 "#ifdef USEBLOOM\n"
734 "       gl_FragColor += max(vec4(0,0,0,0), texture2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
735 "#endif\n"
736 "#ifdef USEVIEWTINT\n"
737 "       gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
738 "#endif\n"
739 "\n"
740 "#ifdef USEPOSTPROCESSING\n"
741 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
742 "// 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"
743 "       float sobel = 1.0;\n"
744 "       // vec2 ts = textureSize(Texture_First, 0);\n"
745 "       // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
746 "       vec2 px = PixelSize;\n"
747 "       vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
748 "       vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,  0.0)).rgb;\n"
749 "       vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
750 "       vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
751 "       vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x,  0.0)).rgb;\n"
752 "       vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
753 "       vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
754 "       vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2(  0.0,-px.y)).rgb;\n"
755 "       vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
756 "       vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
757 "       vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2(  0.0, px.y)).rgb;\n"
758 "       vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
759 "       float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
760 "       float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
761 "       float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
762 "       float px4 =  1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
763 "       float px5 =  2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
764 "       float px6 =  1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
765 "       float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
766 "       float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
767 "       float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
768 "       float py4 =  1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
769 "       float py5 =  2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
770 "       float py6 =  1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
771 "       sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
772 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
773 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
774 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
775 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107,  0.707107)) * UserVec1.y;\n"
776 "       gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990,  0.891007)) * UserVec1.y;\n"
777 "       gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
778 "       gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
779 "#endif\n"
780 "\n"
781 "#ifdef USESATURATION\n"
782 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
783 "       float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
784 "       // 'vampire sight' effect, wheres red is compensated\n"
785 "       #ifdef SATURATION_REDCOMPENSATE\n"
786 "               float rboost = max(0.0, (gl_FragColor.r - max(gl_FragColor.g, gl_FragColor.b))*(1.0 - Saturation));\n"
787 "               gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
788 "               gl_FragColor.r += rboost;\n"
789 "       #else\n"
790 "               // normal desaturation\n"
791 "               //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
792 "               gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
793 "       #endif\n"
794 "#endif\n"
795 "\n"
796 "#ifdef USEGAMMARAMPS\n"
797 "       gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
798 "       gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
799 "       gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
800 "#endif\n"
801 "}\n"
802 "#endif\n"
803 "#else // !MODE_POSTPROCESS\n"
804 "\n"
805 "\n"
806 "\n"
807 "\n"
808 "#ifdef MODE_GENERIC\n"
809 "#ifdef USEDIFFUSE\n"
810 "varying mediump vec2 TexCoord1;\n"
811 "#endif\n"
812 "#ifdef USESPECULAR\n"
813 "varying mediump vec2 TexCoord2;\n"
814 "#endif\n"
815 "#ifdef VERTEX_SHADER\n"
816 "void main(void)\n"
817 "{\n"
818 "       VertexColor = Attrib_Color;\n"
819 "#ifdef USEDIFFUSE\n"
820 "       TexCoord1 = Attrib_TexCoord0.xy;\n"
821 "#endif\n"
822 "#ifdef USESPECULAR\n"
823 "       TexCoord2 = Attrib_TexCoord1.xy;\n"
824 "#endif\n"
825 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
826 "}\n"
827 "#endif\n"
828 "\n"
829 "#ifdef FRAGMENT_SHADER\n"
830 "#ifdef USEDIFFUSE\n"
831 "uniform sampler2D Texture_First;\n"
832 "#endif\n"
833 "#ifdef USESPECULAR\n"
834 "uniform sampler2D Texture_Second;\n"
835 "#endif\n"
836 "\n"
837 "void main(void)\n"
838 "{\n"
839 "#ifdef USEVIEWTINT\n"
840 "       gl_FragColor = VertexColor;\n"
841 "#else\n"
842 "       gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
843 "#endif\n"
844 "#ifdef USEDIFFUSE\n"
845 "       gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
846 "#endif\n"
847 "\n"
848 "#ifdef USESPECULAR\n"
849 "       vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
850 "# ifdef USECOLORMAPPING\n"
851 "       gl_FragColor *= tex2;\n"
852 "# endif\n"
853 "# ifdef USEGLOW\n"
854 "       gl_FragColor += tex2;\n"
855 "# endif\n"
856 "# ifdef USEVERTEXTEXTUREBLEND\n"
857 "       gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
858 "# endif\n"
859 "#endif\n"
860 "}\n"
861 "#endif\n"
862 "#else // !MODE_GENERIC\n"
863 "\n"
864 "\n"
865 "\n"
866 "\n"
867 "#ifdef MODE_BLOOMBLUR\n"
868 "varying mediump vec2 TexCoord;\n"
869 "#ifdef VERTEX_SHADER\n"
870 "void main(void)\n"
871 "{\n"
872 "       VertexColor = Attrib_Color;\n"
873 "       TexCoord = Attrib_TexCoord0.xy;\n"
874 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
875 "}\n"
876 "#endif\n"
877 "\n"
878 "#ifdef FRAGMENT_SHADER\n"
879 "uniform sampler2D Texture_First;\n"
880 "uniform mediump vec4 BloomBlur_Parameters;\n"
881 "\n"
882 "void main(void)\n"
883 "{\n"
884 "       int i;\n"
885 "       vec2 tc = TexCoord;\n"
886 "       vec3 color = texture2D(Texture_First, tc).rgb;\n"
887 "       tc += BloomBlur_Parameters.xy;\n"
888 "       for (i = 1;i < SAMPLES;i++)\n"
889 "       {\n"
890 "               color += texture2D(Texture_First, tc).rgb;\n"
891 "               tc += BloomBlur_Parameters.xy;\n"
892 "       }\n"
893 "       gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
894 "}\n"
895 "#endif\n"
896 "#else // !MODE_BLOOMBLUR\n"
897 "#ifdef MODE_REFRACTION\n"
898 "varying mediump vec2 TexCoord;\n"
899 "varying highp vec4 ModelViewProjectionPosition;\n"
900 "uniform highp mat4 TexMatrix;\n"
901 "#ifdef VERTEX_SHADER\n"
902 "\n"
903 "void main(void)\n"
904 "{\n"
905 "       TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
906 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
907 "       ModelViewProjectionPosition = gl_Position;\n"
908 "}\n"
909 "#endif\n"
910 "\n"
911 "#ifdef FRAGMENT_SHADER\n"
912 "uniform sampler2D Texture_Normal;\n"
913 "uniform sampler2D Texture_Refraction;\n"
914 "uniform sampler2D Texture_Reflection;\n"
915 "\n"
916 "uniform mediump vec4 DistortScaleRefractReflect;\n"
917 "uniform mediump vec4 ScreenScaleRefractReflect;\n"
918 "uniform mediump vec4 ScreenCenterRefractReflect;\n"
919 "uniform lowp vec4 RefractColor;\n"
920 "uniform lowp vec4 ReflectColor;\n"
921 "uniform mediump float ReflectFactor;\n"
922 "uniform mediump float ReflectOffset;\n"
923 "\n"
924 "void main(void)\n"
925 "{\n"
926 "       vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
927 "       //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
928 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
929 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
930 "       // FIXME temporary hack to detect the case that the reflection\n"
931 "       // gets blackened at edges due to leaving the area that contains actual\n"
932 "       // content.\n"
933 "       // Remove this 'ack once we have a better way to stop this thing from\n"
934 "       // 'appening.\n"
935 "       float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
936 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
937 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
938 "       f      *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
939 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
940 "       gl_FragColor = vec4(texture2D(Texture_Refraction, ScreenTexCoord).rgb, 1.0) * RefractColor;\n"
941 "}\n"
942 "#endif\n"
943 "#else // !MODE_REFRACTION\n"
944 "\n"
945 "\n"
946 "\n"
947 "\n"
948 "#ifdef MODE_WATER\n"
949 "varying mediump vec2 TexCoord;\n"
950 "varying highp vec3 EyeVector;\n"
951 "varying highp vec4 ModelViewProjectionPosition;\n"
952 "#ifdef VERTEX_SHADER\n"
953 "uniform highp vec3 EyePosition;\n"
954 "uniform highp mat4 TexMatrix;\n"
955 "\n"
956 "void main(void)\n"
957 "{\n"
958 "       TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
959 "       vec3 EyeVectorModelSpace = EyePosition - Attrib_Position.xyz;\n"
960 "       EyeVector.x = dot(EyeVectorModelSpace, Attrib_TexCoord1.xyz);\n"
961 "       EyeVector.y = dot(EyeVectorModelSpace, Attrib_TexCoord2.xyz);\n"
962 "       EyeVector.z = dot(EyeVectorModelSpace, Attrib_TexCoord3.xyz);\n"
963 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
964 "       ModelViewProjectionPosition = gl_Position;\n"
965 "}\n"
966 "#endif\n"
967 "\n"
968 "#ifdef FRAGMENT_SHADER\n"
969 "uniform sampler2D Texture_Normal;\n"
970 "uniform sampler2D Texture_Refraction;\n"
971 "uniform sampler2D Texture_Reflection;\n"
972 "\n"
973 "uniform mediump vec4 DistortScaleRefractReflect;\n"
974 "uniform mediump vec4 ScreenScaleRefractReflect;\n"
975 "uniform mediump vec4 ScreenCenterRefractReflect;\n"
976 "uniform lowp vec4 RefractColor;\n"
977 "uniform lowp vec4 ReflectColor;\n"
978 "uniform mediump float ReflectFactor;\n"
979 "uniform mediump float ReflectOffset;\n"
980 "uniform highp float ClientTime;\n"
981 "#ifdef USENORMALMAPSCROLLBLEND\n"
982 "uniform highp vec2 NormalmapScrollBlend;\n"
983 "#endif\n"
984 "\n"
985 "void main(void)\n"
986 "{\n"
987 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
988 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
989 "       vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
990 "       //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
991 "       // slight water animation via 2 layer scrolling (todo: tweak)\n"
992 "       #ifdef USENORMALMAPSCROLLBLEND\n"
993 "               vec3 normal = texture2D(Texture_Normal, (TexCoord + vec2(0.08, 0.08)*ClientTime*NormalmapScrollBlend.x*0.5)*NormalmapScrollBlend.y).rgb - vec3(1.0);\n"
994 "               normal += texture2D(Texture_Normal, (TexCoord + vec2(-0.06, -0.09)*ClientTime*NormalmapScrollBlend.x)*NormalmapScrollBlend.y*0.75).rgb;\n"
995 "               vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(normal) + vec3(0.15)).xyxy * DistortScaleRefractReflect;\n"
996 "       #else\n"
997 "               vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
998 "       #endif\n"
999 "       // FIXME temporary hack to detect the case that the reflection\n"
1000 "       // gets blackened at edges due to leaving the area that contains actual\n"
1001 "       // content.\n"
1002 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1003 "       // 'appening.\n"
1004 "       float f  = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.005, 0.01)).rgb) / 0.002);\n"
1005 "       f       *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.005, -0.01)).rgb) / 0.002);\n"
1006 "       f       *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.005, 0.01)).rgb) / 0.002);\n"
1007 "       f       *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.005, -0.01)).rgb) / 0.002);\n"
1008 "       ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
1009 "       f  = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.005, 0.005)).rgb) / 0.002);\n"
1010 "       f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.005, -0.005)).rgb) / 0.002);\n"
1011 "       f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.005, 0.005)).rgb) / 0.002);\n"
1012 "       f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.005, -0.005)).rgb) / 0.002);\n"
1013 "       ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
1014 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
1015 "       gl_FragColor = mix(vec4(texture2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, vec4(texture2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
1016 "}\n"
1017 "#endif\n"
1018 "#else // !MODE_WATER\n"
1019 "\n"
1020 "\n"
1021 "\n"
1022 "\n"
1023 "// common definitions between vertex shader and fragment shader:\n"
1024 "\n"
1025 "varying mediump vec2 TexCoord;\n"
1026 "#ifdef USEVERTEXTEXTUREBLEND\n"
1027 "varying mediump vec2 TexCoord2;\n"
1028 "#endif\n"
1029 "#ifdef USELIGHTMAP\n"
1030 "varying mediump vec2 TexCoordLightmap;\n"
1031 "#endif\n"
1032 "\n"
1033 "#ifdef MODE_LIGHTSOURCE\n"
1034 "varying mediump vec3 CubeVector;\n"
1035 "#endif\n"
1036 "\n"
1037 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
1038 "varying mediump vec3 LightVector;\n"
1039 "#endif\n"
1040 "\n"
1041 "#ifdef USEEYEVECTOR\n"
1042 "varying highp vec3 EyeVector;\n"
1043 "#endif\n"
1044 "#ifdef USEFOG\n"
1045 "varying highp vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
1046 "#endif\n"
1047 "\n"
1048 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
1049 "varying lowp vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
1050 "varying lowp vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
1051 "varying lowp vec3 VectorR; // direction of R texcoord (surface normal)\n"
1052 "#endif\n"
1053 "\n"
1054 "#ifdef USEREFLECTION\n"
1055 "varying highp vec4 ModelViewProjectionPosition;\n"
1056 "#endif\n"
1057 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1058 "uniform highp vec3 LightPosition;\n"
1059 "varying highp vec4 ModelViewPosition;\n"
1060 "#endif\n"
1061 "#ifdef MODE_DEFERREDBOUNCELIGHT\n"
1062 "varying highp vec4 ModelViewPosition;\n"
1063 "varying highp vec4 LightOriginInvRadius;\n"
1064 "varying mediump vec4 LightColor;\n"
1065 "#endif\n"
1066 "\n"
1067 "#ifdef MODE_LIGHTSOURCE\n"
1068 "uniform highp vec3 LightPosition;\n"
1069 "#endif\n"
1070 "uniform highp vec3 EyePosition;\n"
1071 "#ifdef MODE_LIGHTDIRECTION\n"
1072 "uniform highp vec3 LightDir;\n"
1073 "#endif\n"
1074 "uniform highp vec4 FogPlane;\n"
1075 "\n"
1076 "#ifdef USESHADOWMAPORTHO\n"
1077 "varying mediump vec3 ShadowMapTC;\n"
1078 "#endif\n"
1079 "\n"
1080 "#ifdef USEBOUNCEGRID\n"
1081 "varying mediump vec3 BounceGridTexCoord;\n"
1082 "#endif\n"
1083 "\n"
1084 "\n"
1085 "\n"
1086 "\n"
1087 "\n"
1088 "\n"
1089 "// 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"
1090 "\n"
1091 "// fragment shader specific:\n"
1092 "#ifdef FRAGMENT_SHADER\n"
1093 "\n"
1094 "uniform sampler2D Texture_Normal;\n"
1095 "uniform sampler2D Texture_Color;\n"
1096 "uniform sampler2D Texture_Gloss;\n"
1097 "#ifdef USEGLOW\n"
1098 "uniform sampler2D Texture_Glow;\n"
1099 "#endif\n"
1100 "#ifdef USEVERTEXTEXTUREBLEND\n"
1101 "uniform sampler2D Texture_SecondaryNormal;\n"
1102 "uniform sampler2D Texture_SecondaryColor;\n"
1103 "uniform sampler2D Texture_SecondaryGloss;\n"
1104 "#ifdef USEGLOW\n"
1105 "uniform sampler2D Texture_SecondaryGlow;\n"
1106 "#endif\n"
1107 "#endif\n"
1108 "#ifdef USECOLORMAPPING\n"
1109 "uniform sampler2D Texture_Pants;\n"
1110 "uniform sampler2D Texture_Shirt;\n"
1111 "#endif\n"
1112 "#ifdef USEFOG\n"
1113 "#ifdef USEFOGHEIGHTTEXTURE\n"
1114 "uniform sampler2D Texture_FogHeightTexture;\n"
1115 "#endif\n"
1116 "uniform sampler2D Texture_FogMask;\n"
1117 "#endif\n"
1118 "#ifdef USELIGHTMAP\n"
1119 "uniform sampler2D Texture_Lightmap;\n"
1120 "#endif\n"
1121 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1122 "uniform sampler2D Texture_Deluxemap;\n"
1123 "#endif\n"
1124 "#ifdef USEREFLECTION\n"
1125 "uniform sampler2D Texture_Reflection;\n"
1126 "#endif\n"
1127 "\n"
1128 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1129 "uniform sampler2D Texture_ScreenDepth;\n"
1130 "uniform sampler2D Texture_ScreenNormalMap;\n"
1131 "#endif\n"
1132 "#ifdef USEDEFERREDLIGHTMAP\n"
1133 "uniform sampler2D Texture_ScreenDiffuse;\n"
1134 "uniform sampler2D Texture_ScreenSpecular;\n"
1135 "#endif\n"
1136 "#ifdef MODE_DEFERREDBOUNCELIGHT\n"
1137 "uniform sampler2D Texture_ScreenDepth;\n"
1138 "#endif\n"
1139 "\n"
1140 "uniform lowp vec3 Color_Pants;\n"
1141 "uniform lowp vec3 Color_Shirt;\n"
1142 "uniform lowp vec3 FogColor;\n"
1143 "\n"
1144 "#ifdef USEFOG\n"
1145 "uniform highp float FogRangeRecip;\n"
1146 "uniform highp float FogPlaneViewDist;\n"
1147 "uniform highp float FogHeightFade;\n"
1148 "vec3 FogVertex(vec3 surfacecolor)\n"
1149 "{\n"
1150 "       vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1151 "       float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1152 "       float fogfrac;\n"
1153 "#ifdef USEFOGHEIGHTTEXTURE\n"
1154 "       vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1155 "       fogfrac = fogheightpixel.a;\n"
1156 "       return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1157 "#else\n"
1158 "# ifdef USEFOGOUTSIDE\n"
1159 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1160 "# else\n"
1161 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1162 "# endif\n"
1163 "       return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1164 "#endif\n"
1165 "}\n"
1166 "#endif\n"
1167 "\n"
1168 "#ifdef USEOFFSETMAPPING\n"
1169 "uniform mediump float OffsetMapping_Scale;\n"
1170 "vec2 OffsetMapping(vec2 TexCoord)\n"
1171 "{\n"
1172 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1173 "       // 14 sample relief mapping: linear search and then binary search\n"
1174 "       // this basically steps forward a small amount repeatedly until it finds\n"
1175 "       // itself inside solid, then jitters forward and back using decreasing\n"
1176 "       // amounts to find the impact\n"
1177 "       //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1178 "       //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1179 "       vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1180 "       vec3 RT = vec3(TexCoord, 1);\n"
1181 "       OffsetVector *= 0.1;\n"
1182 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1183 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1184 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1185 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1186 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1187 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1188 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1189 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1190 "       RT += OffsetVector *  step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1191 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
1192 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
1193 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
1194 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
1195 "       RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1196 "       return RT.xy;\n"
1197 "#else\n"
1198 "       // 2 sample offset mapping (only 2 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1199 "       // this basically moves forward the full distance, and then backs up based\n"
1200 "       // on height of samples\n"
1201 "       //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1202 "       //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1203 "       vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1204 "       TexCoord += OffsetVector;\n"
1205 "       OffsetVector *= 0.5;\n"
1206 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1207 "       TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1208 "       return TexCoord;\n"
1209 "#endif\n"
1210 "}\n"
1211 "#endif // USEOFFSETMAPPING\n"
1212 "\n"
1213 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1214 "uniform sampler2D Texture_Attenuation;\n"
1215 "uniform samplerCube Texture_Cube;\n"
1216 "#endif\n"
1217 "\n"
1218 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1219 "\n"
1220 "#ifdef USESHADOWMAP2D\n"
1221 "# ifdef USESHADOWSAMPLER\n"
1222 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1223 "# else\n"
1224 "uniform sampler2D Texture_ShadowMap2D;\n"
1225 "# endif\n"
1226 "#endif\n"
1227 "\n"
1228 "#ifdef USESHADOWMAPVSDCT\n"
1229 "uniform samplerCube Texture_CubeProjection;\n"
1230 "#endif\n"
1231 "\n"
1232 "#if defined(USESHADOWMAP2D)\n"
1233 "uniform mediump vec2 ShadowMap_TextureScale;\n"
1234 "uniform mediump vec4 ShadowMap_Parameters;\n"
1235 "#endif\n"
1236 "\n"
1237 "#if defined(USESHADOWMAP2D)\n"
1238 "# ifdef USESHADOWMAPORTHO\n"
1239 "#  define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1240 "# else\n"
1241 "#  ifdef USESHADOWMAPVSDCT\n"
1242 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1243 "{\n"
1244 "       vec3 adir = abs(dir);\n"
1245 "       vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1246 "       vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1247 "       return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1248 "}\n"
1249 "#  else\n"
1250 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1251 "{\n"
1252 "       vec3 adir = abs(dir);\n"
1253 "       float ma = adir.z;\n"
1254 "       vec4 proj = vec4(dir, 2.5);\n"
1255 "       if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1256 "       if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1257 "       vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1258 "       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"
1259 "}\n"
1260 "#  endif\n"
1261 "# endif\n"
1262 "#endif // defined(USESHADOWMAP2D)\n"
1263 "\n"
1264 "# ifdef USESHADOWMAP2D\n"
1265 "float ShadowMapCompare(vec3 dir)\n"
1266 "{\n"
1267 "       vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1268 "       float f;\n"
1269 "\n"
1270 "#  ifdef USESHADOWSAMPLER\n"
1271 "#    ifdef USESHADOWMAPPCF\n"
1272 "#      define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r  \n"
1273 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1274 "       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"
1275 "#    else\n"
1276 "       f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1277 "#    endif\n"
1278 "#  else\n"
1279 "#    ifdef USESHADOWMAPPCF\n"
1280 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1281 "#      ifdef GL_ARB_texture_gather\n"
1282 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1283 "#      else\n"
1284 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1285 "#      endif\n"
1286 "       vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1287 "#      if USESHADOWMAPPCF > 1\n"
1288 "   vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1289 "   vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1290 "   vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1291 "   vec4 group4 = step(shadowmaptc.z, texval(-2.0,  0.0));\n"
1292 "   vec4 group5 = step(shadowmaptc.z, texval( 0.0,  0.0));\n"
1293 "   vec4 group6 = step(shadowmaptc.z, texval( 2.0,  0.0));\n"
1294 "   vec4 group7 = step(shadowmaptc.z, texval(-2.0,  2.0));\n"
1295 "   vec4 group8 = step(shadowmaptc.z, texval( 0.0,  2.0));\n"
1296 "   vec4 group9 = step(shadowmaptc.z, texval( 2.0,  2.0));\n"
1297 "       vec4 locols = vec4(group1.ab, group3.ab);\n"
1298 "       vec4 hicols = vec4(group7.rg, group9.rg);\n"
1299 "       locols.yz += group2.ab;\n"
1300 "       hicols.yz += group8.rg;\n"
1301 "       vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1302 "                               vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1303 "                               mix(locols, hicols, offset.y);\n"
1304 "       vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1305 "       cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1306 "       f = dot(cols, vec4(1.0/25.0));\n"
1307 "#      else\n"
1308 "       vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1309 "       vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1310 "       vec4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
1311 "       vec4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
1312 "       vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1313 "                               mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1314 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1315 "#      endif\n"
1316 "#     else\n"
1317 "#      ifdef GL_EXT_gpu_shader4\n"
1318 "#        define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1319 "#      else\n"
1320 "#        define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r  \n"
1321 "#      endif\n"
1322 "#      if USESHADOWMAPPCF > 1\n"
1323 "       vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1324 "       center *= ShadowMap_TextureScale;\n"
1325 "       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"
1326 "       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"
1327 "       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"
1328 "       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"
1329 "       vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1330 "       f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1331 "#      else\n"
1332 "       vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1333 "       vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1334 "       vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
1335 "       vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
1336 "       vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1337 "       f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1338 "#      endif\n"
1339 "#     endif\n"
1340 "#    else\n"
1341 "       f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1342 "#    endif\n"
1343 "#  endif\n"
1344 "#  ifdef USESHADOWMAPORTHO\n"
1345 "       return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1346 "#  else\n"
1347 "       return f;\n"
1348 "#  endif\n"
1349 "}\n"
1350 "# endif\n"
1351 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1352 "#endif // FRAGMENT_SHADER\n"
1353 "\n"
1354 "\n"
1355 "\n"
1356 "\n"
1357 "#ifdef MODE_DEFERREDGEOMETRY\n"
1358 "#ifdef VERTEX_SHADER\n"
1359 "uniform highp mat4 TexMatrix;\n"
1360 "#ifdef USEVERTEXTEXTUREBLEND\n"
1361 "uniform highp mat4 BackgroundTexMatrix;\n"
1362 "#endif\n"
1363 "uniform highp mat4 ModelViewMatrix;\n"
1364 "void main(void)\n"
1365 "{\n"
1366 "       TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
1367 "#ifdef USEVERTEXTEXTUREBLEND\n"
1368 "       VertexColor = Attrib_Color;\n"
1369 "       TexCoord2 = vec2(BackgroundTexMatrix * Attrib_TexCoord0);\n"
1370 "#endif\n"
1371 "\n"
1372 "       // transform unnormalized eye direction into tangent space\n"
1373 "#ifdef USEOFFSETMAPPING\n"
1374 "       vec3 EyeVectorModelSpace = EyePosition - Attrib_Position.xyz;\n"
1375 "       EyeVector.x = dot(EyeVectorModelSpace, Attrib_TexCoord1.xyz);\n"
1376 "       EyeVector.y = dot(EyeVectorModelSpace, Attrib_TexCoord2.xyz);\n"
1377 "       EyeVector.z = dot(EyeVectorModelSpace, Attrib_TexCoord3.xyz);\n"
1378 "#endif\n"
1379 "\n"
1380 "       VectorS = (ModelViewMatrix * vec4(Attrib_TexCoord1.xyz, 0)).xyz;\n"
1381 "       VectorT = (ModelViewMatrix * vec4(Attrib_TexCoord2.xyz, 0)).xyz;\n"
1382 "       VectorR = (ModelViewMatrix * vec4(Attrib_TexCoord3.xyz, 0)).xyz;\n"
1383 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1384 "}\n"
1385 "#endif // VERTEX_SHADER\n"
1386 "\n"
1387 "#ifdef FRAGMENT_SHADER\n"
1388 "void main(void)\n"
1389 "{\n"
1390 "#ifdef USEOFFSETMAPPING\n"
1391 "       // apply offsetmapping\n"
1392 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1393 "#define TexCoord TexCoordOffset\n"
1394 "#endif\n"
1395 "\n"
1396 "#ifdef USEALPHAKILL\n"
1397 "       if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1398 "               discard;\n"
1399 "#endif\n"
1400 "\n"
1401 "#ifdef USEVERTEXTEXTUREBLEND\n"
1402 "       float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1403 "       float terrainblend = clamp(float(VertexColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1404 "       //float terrainblend = min(float(VertexColor.a) * alpha * 2.0, float(1.0));\n"
1405 "       //float terrainblend = float(VertexColor.a) * alpha > 0.5;\n"
1406 "#endif\n"
1407 "\n"
1408 "#ifdef USEVERTEXTEXTUREBLEND\n"
1409 "       vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1410 "       float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1411 "#else\n"
1412 "       vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1413 "       float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1414 "#endif\n"
1415 "\n"
1416 "       gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1417 "}\n"
1418 "#endif // FRAGMENT_SHADER\n"
1419 "#else // !MODE_DEFERREDGEOMETRY\n"
1420 "\n"
1421 "\n"
1422 "\n"
1423 "\n"
1424 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1425 "#ifdef VERTEX_SHADER\n"
1426 "uniform highp mat4 ModelViewMatrix;\n"
1427 "void main(void)\n"
1428 "{\n"
1429 "       ModelViewPosition = ModelViewMatrix * Attrib_Position;\n"
1430 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1431 "}\n"
1432 "#endif // VERTEX_SHADER\n"
1433 "\n"
1434 "#ifdef FRAGMENT_SHADER\n"
1435 "uniform highp mat4 ViewToLight;\n"
1436 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1437 "uniform highp vec2 ScreenToDepth;\n"
1438 "uniform myhalf3 DeferredColor_Ambient;\n"
1439 "uniform myhalf3 DeferredColor_Diffuse;\n"
1440 "#ifdef USESPECULAR\n"
1441 "uniform myhalf3 DeferredColor_Specular;\n"
1442 "uniform myhalf SpecularPower;\n"
1443 "#endif\n"
1444 "uniform myhalf2 PixelToScreenTexCoord;\n"
1445 "void main(void)\n"
1446 "{\n"
1447 "       // calculate viewspace pixel position\n"
1448 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1449 "       vec3 position;\n"
1450 "       position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1451 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1452 "       // decode viewspace pixel normal\n"
1453 "       myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1454 "       myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1455 "       // surfacenormal = pixel normal in viewspace\n"
1456 "       // LightVector = pixel to light in viewspace\n"
1457 "       // CubeVector = position in lightspace\n"
1458 "       // eyevector = pixel to view in viewspace\n"
1459 "       vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1460 "       myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1461 "#ifdef USEDIFFUSE\n"
1462 "       // calculate diffuse shading\n"
1463 "       myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1464 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1465 "#endif\n"
1466 "#ifdef USESPECULAR\n"
1467 "       // calculate directional shading\n"
1468 "       vec3 eyevector = position * -1.0;\n"
1469 "#  ifdef USEEXACTSPECULARMATH\n"
1470 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1471 "#  else\n"
1472 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1473 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1474 "#  endif\n"
1475 "#endif\n"
1476 "\n"
1477 "#if defined(USESHADOWMAP2D)\n"
1478 "       fade *= ShadowMapCompare(CubeVector);\n"
1479 "#endif\n"
1480 "\n"
1481 "#ifdef USEDIFFUSE\n"
1482 "       gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1483 "#else\n"
1484 "       gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1485 "#endif\n"
1486 "#ifdef USESPECULAR\n"
1487 "       gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1488 "#else\n"
1489 "       gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1490 "#endif\n"
1491 "\n"
1492 "# ifdef USECUBEFILTER\n"
1493 "       vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1494 "       gl_FragData[0].rgb *= cubecolor;\n"
1495 "       gl_FragData[1].rgb *= cubecolor;\n"
1496 "# endif\n"
1497 "}\n"
1498 "#endif // FRAGMENT_SHADER\n"
1499 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1500 "\n"
1501 "\n"
1502 "\n"
1503 "\n"
1504 "#ifdef MODE_DEFERREDBOUNCELIGHT\n"
1505 "#ifdef VERTEX_SHADER\n"
1506 "uniform highp mat4 ModelViewMatrix;\n"
1507 "void main(void)\n"
1508 "{\n"
1509 "       ModelViewPosition = ModelViewMatrix * Attrib_Position;\n"
1510 "       LightOriginInvRadius.xyz = (ModelViewMatrix * vec4(Attrib_TexCoord0.xyz, 1.0)).xyz;\n"
1511 "       LightOriginInvRadius.w = Attrib_TexCoord0.w;\n"
1512 "       LightColor = Attrib_Color;\n"
1513 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1514 "}\n"
1515 "#endif // VERTEX_SHADER\n"
1516 "\n"
1517 "#ifdef FRAGMENT_SHADER\n"
1518 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1519 "uniform highp vec2 ScreenToDepth;\n"
1520 "uniform myhalf2 PixelToScreenTexCoord;\n"
1521 "void main(void)\n"
1522 "{\n"
1523 "       // calculate viewspace pixel position\n"
1524 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1525 "       vec3 position;\n"
1526 "       position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1527 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1528 "       vec3 CubeVector = (position - LightOriginInvRadius.xyz) * LightOriginInvRadius.w;\n"
1529 "       gl_FragData[0] = vec4(LightColor.rgb * max(0.0, 1.0 - length(CubeVector)), 1.0);\n"
1530 "}\n"
1531 "#endif // FRAGMENT_SHADER\n"
1532 "#else // !MODE_DEFERREDBOUNCELIGHT\n"
1533 "\n"
1534 "\n"
1535 "\n"
1536 "\n"
1537 "#ifdef VERTEX_SHADER\n"
1538 "uniform highp mat4 TexMatrix;\n"
1539 "#ifdef USEVERTEXTEXTUREBLEND\n"
1540 "uniform highp mat4 BackgroundTexMatrix;\n"
1541 "#endif\n"
1542 "#ifdef MODE_LIGHTSOURCE\n"
1543 "uniform highp mat4 ModelToLight;\n"
1544 "#endif\n"
1545 "#ifdef USESHADOWMAPORTHO\n"
1546 "uniform highp mat4 ShadowMapMatrix;\n"
1547 "#endif\n"
1548 "#ifdef USEBOUNCEGRID\n"
1549 "uniform highp mat4 BounceGridMatrix;\n"
1550 "#endif\n"
1551 "void main(void)\n"
1552 "{\n"
1553 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1554 "       VertexColor = Attrib_Color;\n"
1555 "#endif\n"
1556 "       // copy the surface texcoord\n"
1557 "       TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
1558 "#ifdef USEVERTEXTEXTUREBLEND\n"
1559 "       TexCoord2 = vec2(BackgroundTexMatrix * Attrib_TexCoord0);\n"
1560 "#endif\n"
1561 "#ifdef USELIGHTMAP\n"
1562 "       TexCoordLightmap = vec2(Attrib_TexCoord4);\n"
1563 "#endif\n"
1564 "\n"
1565 "#ifdef USEBOUNCEGRID\n"
1566 "       BounceGridTexCoord = vec3(BounceGridMatrix * Attrib_Position);\n"
1567 "#endif\n"
1568 "\n"
1569 "#ifdef MODE_LIGHTSOURCE\n"
1570 "       // transform vertex position into light attenuation/cubemap space\n"
1571 "       // (-1 to +1 across the light box)\n"
1572 "       CubeVector = vec3(ModelToLight * Attrib_Position);\n"
1573 "\n"
1574 "# ifdef USEDIFFUSE\n"
1575 "       // transform unnormalized light direction into tangent space\n"
1576 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
1577 "       //  normalize it per pixel)\n"
1578 "       vec3 lightminusvertex = LightPosition - Attrib_Position.xyz;\n"
1579 "       LightVector.x = dot(lightminusvertex, Attrib_TexCoord1.xyz);\n"
1580 "       LightVector.y = dot(lightminusvertex, Attrib_TexCoord2.xyz);\n"
1581 "       LightVector.z = dot(lightminusvertex, Attrib_TexCoord3.xyz);\n"
1582 "# endif\n"
1583 "#endif\n"
1584 "\n"
1585 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1586 "       LightVector.x = dot(LightDir, Attrib_TexCoord1.xyz);\n"
1587 "       LightVector.y = dot(LightDir, Attrib_TexCoord2.xyz);\n"
1588 "       LightVector.z = dot(LightDir, Attrib_TexCoord3.xyz);\n"
1589 "#endif\n"
1590 "\n"
1591 "       // transform unnormalized eye direction into tangent space\n"
1592 "#ifdef USEEYEVECTOR\n"
1593 "       vec3 EyeVectorModelSpace = EyePosition - Attrib_Position.xyz;\n"
1594 "       EyeVector.x = dot(EyeVectorModelSpace, Attrib_TexCoord1.xyz);\n"
1595 "       EyeVector.y = dot(EyeVectorModelSpace, Attrib_TexCoord2.xyz);\n"
1596 "       EyeVector.z = dot(EyeVectorModelSpace, Attrib_TexCoord3.xyz);\n"
1597 "#endif\n"
1598 "\n"
1599 "#ifdef USEFOG\n"
1600 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - Attrib_Position.xyz;\n"
1601 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, Attrib_Position);\n"
1602 "#endif\n"
1603 "\n"
1604 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1605 "       VectorS = Attrib_TexCoord1.xyz;\n"
1606 "       VectorT = Attrib_TexCoord2.xyz;\n"
1607 "       VectorR = Attrib_TexCoord3.xyz;\n"
1608 "#endif\n"
1609 "\n"
1610 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1611 "       gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1612 "\n"
1613 "#ifdef USESHADOWMAPORTHO\n"
1614 "       ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1615 "#endif\n"
1616 "\n"
1617 "#ifdef USEREFLECTION\n"
1618 "       ModelViewProjectionPosition = gl_Position;\n"
1619 "#endif\n"
1620 "}\n"
1621 "#endif // VERTEX_SHADER\n"
1622 "\n"
1623 "\n"
1624 "\n"
1625 "\n"
1626 "#ifdef FRAGMENT_SHADER\n"
1627 "#ifdef USEDEFERREDLIGHTMAP\n"
1628 "uniform myhalf2 PixelToScreenTexCoord;\n"
1629 "uniform myhalf3 DeferredMod_Diffuse;\n"
1630 "uniform myhalf3 DeferredMod_Specular;\n"
1631 "#endif\n"
1632 "uniform myhalf3 Color_Ambient;\n"
1633 "uniform myhalf3 Color_Diffuse;\n"
1634 "uniform myhalf3 Color_Specular;\n"
1635 "uniform myhalf SpecularPower;\n"
1636 "#ifdef USEGLOW\n"
1637 "uniform myhalf3 Color_Glow;\n"
1638 "#endif\n"
1639 "uniform myhalf Alpha;\n"
1640 "#ifdef USEREFLECTION\n"
1641 "uniform mediump vec4 DistortScaleRefractReflect;\n"
1642 "uniform mediump vec4 ScreenScaleRefractReflect;\n"
1643 "uniform mediump vec4 ScreenCenterRefractReflect;\n"
1644 "uniform lowp vec4 ReflectColor;\n"
1645 "#endif\n"
1646 "#ifdef USEREFLECTCUBE\n"
1647 "uniform highp mat4 ModelToReflectCube;\n"
1648 "uniform sampler2D Texture_ReflectMask;\n"
1649 "uniform samplerCube Texture_ReflectCube;\n"
1650 "#endif\n"
1651 "#ifdef MODE_LIGHTDIRECTION\n"
1652 "uniform myhalf3 LightColor;\n"
1653 "#endif\n"
1654 "#ifdef MODE_LIGHTSOURCE\n"
1655 "uniform myhalf3 LightColor;\n"
1656 "#endif\n"
1657 "#ifdef USEBOUNCEGRID\n"
1658 "uniform sampler3D Texture_BounceGrid;\n"
1659 "uniform float BounceGridIntensity;\n"
1660 "#endif\n"
1661 "void main(void)\n"
1662 "{\n"
1663 "#ifdef USEOFFSETMAPPING\n"
1664 "       // apply offsetmapping\n"
1665 "       vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1666 "#define TexCoord TexCoordOffset\n"
1667 "#endif\n"
1668 "\n"
1669 "       // combine the diffuse textures (base, pants, shirt)\n"
1670 "       myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1671 "#ifdef USEALPHAKILL\n"
1672 "       if (color.a < 0.5)\n"
1673 "               discard;\n"
1674 "#endif\n"
1675 "       color.a *= Alpha;\n"
1676 "#ifdef USECOLORMAPPING\n"
1677 "       color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1678 "#endif\n"
1679 "#ifdef USEVERTEXTEXTUREBLEND\n"
1680 "       myhalf terrainblend = clamp(myhalf(VertexColor.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1681 "       //myhalf terrainblend = min(myhalf(VertexColor.a) * color.a * 2.0, myhalf(1.0));\n"
1682 "       //myhalf terrainblend = myhalf(VertexColor.a) * color.a > 0.5;\n"
1683 "       color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1684 "       color.a = 1.0;\n"
1685 "       //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1686 "#endif\n"
1687 "\n"
1688 "       // get the surface normal\n"
1689 "#ifdef USEVERTEXTEXTUREBLEND\n"
1690 "       myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1691 "#else\n"
1692 "       myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1693 "#endif\n"
1694 "\n"
1695 "       // get the material colors\n"
1696 "       myhalf3 diffusetex = color.rgb;\n"
1697 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1698 "# ifdef USEVERTEXTEXTUREBLEND\n"
1699 "       myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1700 "# else\n"
1701 "       myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1702 "# endif\n"
1703 "#endif\n"
1704 "\n"
1705 "#ifdef USEREFLECTCUBE\n"
1706 "       vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1707 "       vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1708 "       vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1709 "       diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1710 "#endif\n"
1711 "\n"
1712 "\n"
1713 "\n"
1714 "\n"
1715 "#ifdef MODE_LIGHTSOURCE\n"
1716 "       // light source\n"
1717 "#ifdef USEDIFFUSE\n"
1718 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1719 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1720 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1721 "#ifdef USESPECULAR\n"
1722 "#ifdef USEEXACTSPECULARMATH\n"
1723 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1724 "#else\n"
1725 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1726 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1727 "#endif\n"
1728 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1729 "#endif\n"
1730 "#else\n"
1731 "       color.rgb = diffusetex * Color_Ambient;\n"
1732 "#endif\n"
1733 "       color.rgb *= LightColor;\n"
1734 "       color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1735 "#if defined(USESHADOWMAP2D)\n"
1736 "       color.rgb *= ShadowMapCompare(CubeVector);\n"
1737 "#endif\n"
1738 "# ifdef USECUBEFILTER\n"
1739 "       color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1740 "# endif\n"
1741 "#endif // MODE_LIGHTSOURCE\n"
1742 "\n"
1743 "\n"
1744 "\n"
1745 "\n"
1746 "#ifdef MODE_LIGHTDIRECTION\n"
1747 "#define SHADING\n"
1748 "#ifdef USEDIFFUSE\n"
1749 "       myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1750 "#endif\n"
1751 "#define lightcolor LightColor\n"
1752 "#endif // MODE_LIGHTDIRECTION\n"
1753 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1754 "#define SHADING\n"
1755 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1756 "       myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1757 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1758 "       // convert modelspace light vector to tangentspace\n"
1759 "       myhalf3 lightnormal;\n"
1760 "       lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1761 "       lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1762 "       lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1763 "       lightnormal = normalize(lightnormal); // VectorS/T/R are not always perfectly normalized, and EXACTSPECULARMATH is very picky about this\n"
1764 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1765 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1766 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1767 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1768 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1769 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1770 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1771 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1772 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1773 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1774 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1775 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1776 "#define SHADING\n"
1777 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1778 "       myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1779 "       myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1780 "#endif\n"
1781 "\n"
1782 "\n"
1783 "\n"
1784 "\n"
1785 "#ifdef MODE_FAKELIGHT\n"
1786 "#define SHADING\n"
1787 "myhalf3 lightnormal = myhalf3(normalize(EyeVector));\n"
1788 "myhalf3 lightcolor = myhalf3(1.0);\n"
1789 "#endif // MODE_FAKELIGHT\n"
1790 "\n"
1791 "\n"
1792 "\n"
1793 "\n"
1794 "#ifdef MODE_LIGHTMAP\n"
1795 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1796 "#endif // MODE_LIGHTMAP\n"
1797 "#ifdef MODE_VERTEXCOLOR\n"
1798 "       color.rgb = diffusetex * (Color_Ambient + myhalf3(VertexColor.rgb) * Color_Diffuse);\n"
1799 "#endif // MODE_VERTEXCOLOR\n"
1800 "#ifdef MODE_FLATCOLOR\n"
1801 "       color.rgb = diffusetex * Color_Ambient;\n"
1802 "#endif // MODE_FLATCOLOR\n"
1803 "\n"
1804 "\n"
1805 "\n"
1806 "\n"
1807 "#ifdef SHADING\n"
1808 "# ifdef USEDIFFUSE\n"
1809 "       myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1810 "#  ifdef USESPECULAR\n"
1811 "#   ifdef USEEXACTSPECULARMATH\n"
1812 "       myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1813 "#   else\n"
1814 "       myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1815 "       myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1816 "#   endif\n"
1817 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1818 "#  else\n"
1819 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1820 "#  endif\n"
1821 "# else\n"
1822 "       color.rgb = diffusetex * Color_Ambient;\n"
1823 "# endif\n"
1824 "#endif\n"
1825 "\n"
1826 "#ifdef USESHADOWMAPORTHO\n"
1827 "       color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1828 "#endif\n"
1829 "\n"
1830 "#ifdef USEDEFERREDLIGHTMAP\n"
1831 "       vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1832 "       color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1833 "       color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1834 "#endif\n"
1835 "\n"
1836 "#ifdef USEBOUNCEGRID\n"
1837 "       color.rgb += diffusetex * myhalf3(texture3D(Texture_BounceGrid, BounceGridTexCoord)) * BounceGridIntensity;\n"
1838 "#endif\n"
1839 "\n"
1840 "#ifdef USEGLOW\n"
1841 "#ifdef USEVERTEXTEXTUREBLEND\n"
1842 "       color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1843 "#else\n"
1844 "       color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1845 "#endif\n"
1846 "#endif\n"
1847 "\n"
1848 "#ifdef USEFOG\n"
1849 "       color.rgb = FogVertex(color.rgb);\n"
1850 "#endif\n"
1851 "\n"
1852 "       // 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"
1853 "#ifdef USEREFLECTION\n"
1854 "       vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1855 "       //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1856 "       vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1857 "       vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1858 "       // FIXME temporary hack to detect the case that the reflection\n"
1859 "       // gets blackened at edges due to leaving the area that contains actual\n"
1860 "       // content.\n"
1861 "       // Remove this 'ack once we have a better way to stop this thing from\n"
1862 "       // 'appening.\n"
1863 "       float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1864 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1865 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1866 "       f      *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1867 "       ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1868 "       color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1869 "#endif\n"
1870 "\n"
1871 "       gl_FragColor = vec4(color);\n"
1872 "}\n"
1873 "#endif // FRAGMENT_SHADER\n"
1874 "\n"
1875 "#endif // !MODE_DEFERREDBOUNCELIGHT\n"
1876 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1877 "#endif // !MODE_DEFERREDGEOMETRY\n"
1878 "#endif // !MODE_WATER\n"
1879 "#endif // !MODE_REFRACTION\n"
1880 "#endif // !MODE_BLOOMBLUR\n"
1881 "#endif // !MODE_GENERIC\n"
1882 "#endif // !MODE_POSTPROCESS\n"
1883 "#endif // !MODE_SHOWDEPTH\n"
1884 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1885 ;
1886
1887 /*
1888 =========================================================================================================================================================
1889
1890
1891
1892 =========================================================================================================================================================
1893
1894
1895
1896 =========================================================================================================================================================
1897
1898
1899
1900 =========================================================================================================================================================
1901
1902
1903
1904 =========================================================================================================================================================
1905
1906
1907
1908 =========================================================================================================================================================
1909
1910
1911
1912 =========================================================================================================================================================
1913 */
1914
1915 const char *builtinhlslshaderstring =
1916 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1917 "// written by Forest 'LordHavoc' Hale\n"
1918 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1919 "\n"
1920 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1921 "#if defined(USEREFLECTION)\n"
1922 "#undef USESHADOWMAPORTHO\n"
1923 "#endif\n"
1924 "\n"
1925 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1926 "# define USEFOG\n"
1927 "#endif\n"
1928 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1929 "#define USELIGHTMAP\n"
1930 "#endif\n"
1931 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
1932 "#define USEEYEVECTOR\n"
1933 "#endif\n"
1934 "\n"
1935 "#ifdef FRAGMENT_SHADER\n"
1936 "#ifdef HLSL\n"
1937 "//#undef USESHADOWMAPPCF\n"
1938 "//#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1939 "#define texDepth2D(tex,texcoord) dot(tex2D(tex,texcoord).rgb, float3(1.0, 255.0/65536.0, 255.0/16777216.0))\n"
1940 "#else\n"
1941 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1942 "#endif\n"
1943 "#endif\n"
1944 "\n"
1945 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1946 "#ifdef VERTEX_SHADER\n"
1947 "void main\n"
1948 "(\n"
1949 "float4 gl_Vertex : POSITION,\n"
1950 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1951 "out float4 gl_Position : POSITION,\n"
1952 "out float Depth : TEXCOORD0\n"
1953 ")\n"
1954 "{\n"
1955 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1956 "       Depth = gl_Position.z;\n"
1957 "}\n"
1958 "#endif\n"
1959 "\n"
1960 "#ifdef FRAGMENT_SHADER\n"
1961 "void main\n"
1962 "(\n"
1963 "float Depth : TEXCOORD0,\n"
1964 "out float4 gl_FragColor : COLOR\n"
1965 ")\n"
1966 "{\n"
1967 "//     float4 temp = float4(Depth,Depth*(65536.0/255.0),Depth*(16777216.0/255.0),0.0);\n"
1968 "       float4 temp = float4(Depth,Depth*256.0,Depth*65536.0,0.0);\n"
1969 "       temp.yz -= floor(temp.yz);\n"
1970 "       gl_FragColor = temp;\n"
1971 "//     gl_FragColor = float4(Depth,0,0,0);\n"
1972 "}\n"
1973 "#endif\n"
1974 "#else // !MODE_DEPTH_ORSHADOW\n"
1975 "\n"
1976 "\n"
1977 "\n"
1978 "\n"
1979 "#ifdef MODE_SHOWDEPTH\n"
1980 "#ifdef VERTEX_SHADER\n"
1981 "void main\n"
1982 "(\n"
1983 "float4 gl_Vertex : POSITION,\n"
1984 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1985 "out float4 gl_Position : POSITION,\n"
1986 "out float4 gl_FrontColor : COLOR0\n"
1987 ")\n"
1988 "{\n"
1989 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1990 "       gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1991 "}\n"
1992 "#endif\n"
1993 "\n"
1994 "#ifdef FRAGMENT_SHADER\n"
1995 "void main\n"
1996 "(\n"
1997 "float4 gl_FrontColor : COLOR0,\n"
1998 "out float4 gl_FragColor : COLOR\n"
1999 ")\n"
2000 "{\n"
2001 "       gl_FragColor = gl_FrontColor;\n"
2002 "}\n"
2003 "#endif\n"
2004 "#else // !MODE_SHOWDEPTH\n"
2005 "\n"
2006 "\n"
2007 "\n"
2008 "\n"
2009 "#ifdef MODE_POSTPROCESS\n"
2010 "\n"
2011 "#ifdef VERTEX_SHADER\n"
2012 "void main\n"
2013 "(\n"
2014 "float4 gl_Vertex : POSITION,\n"
2015 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2016 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2017 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2018 "out float4 gl_Position : POSITION,\n"
2019 "out float2 TexCoord1 : TEXCOORD0,\n"
2020 "out float2 TexCoord2 : TEXCOORD1\n"
2021 ")\n"
2022 "{\n"
2023 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2024 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
2025 "#ifdef USEBLOOM\n"
2026 "       TexCoord2 = gl_MultiTexCoord4.xy;\n"
2027 "#endif\n"
2028 "}\n"
2029 "#endif\n"
2030 "\n"
2031 "#ifdef FRAGMENT_SHADER\n"
2032 "void main\n"
2033 "(\n"
2034 "float2 TexCoord1 : TEXCOORD0,\n"
2035 "float2 TexCoord2 : TEXCOORD1,\n"
2036 "uniform sampler Texture_First : register(s0),\n"
2037 "#ifdef USEBLOOM\n"
2038 "uniform sampler Texture_Second : register(s1),\n"
2039 "#endif\n"
2040 "#ifdef USEGAMMARAMPS\n"
2041 "uniform sampler Texture_GammaRamps : register(s2),\n"
2042 "#endif\n"
2043 "#ifdef USESATURATION\n"
2044 "uniform float Saturation : register(c30),\n"
2045 "#endif\n"
2046 "#ifdef USEVIEWTINT\n"
2047 "uniform float4 ViewTintColor : register(c41),\n"
2048 "#endif\n"
2049 "uniform float4 UserVec1 : register(c37),\n"
2050 "uniform float4 UserVec2 : register(c38),\n"
2051 "uniform float4 UserVec3 : register(c39),\n"
2052 "uniform float4 UserVec4 : register(c40),\n"
2053 "uniform float ClientTime : register(c2),\n"
2054 "uniform float2 PixelSize : register(c25),\n"
2055 "uniform float4 BloomColorSubtract : register(c43),\n"
2056 "out float4 gl_FragColor : COLOR\n"
2057 ")\n"
2058 "{\n"
2059 "       gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
2060 "#ifdef USEBLOOM\n"
2061 "       gl_FragColor += max(float4(0,0,0,0), tex2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
2062 "#endif\n"
2063 "#ifdef USEVIEWTINT\n"
2064 "       gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
2065 "#endif\n"
2066 "\n"
2067 "#ifdef USEPOSTPROCESSING\n"
2068 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
2069 "// 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"
2070 "       float sobel = 1.0;\n"
2071 "       // float2 ts = textureSize(Texture_First, 0);\n"
2072 "       // float2 px = float2(1/ts.x, 1/ts.y);\n"
2073 "       float2 px = PixelSize;\n"
2074 "       float3 x1 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
2075 "       float3 x2 = tex2D(Texture_First, TexCoord1 + float2(-px.x,  0.0)).rgb;\n"
2076 "       float3 x3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
2077 "       float3 x4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
2078 "       float3 x5 = tex2D(Texture_First, TexCoord1 + float2( px.x,  0.0)).rgb;\n"
2079 "       float3 x6 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
2080 "       float3 y1 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
2081 "       float3 y2 = tex2D(Texture_First, TexCoord1 + float2(  0.0,-px.y)).rgb;\n"
2082 "       float3 y3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
2083 "       float3 y4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
2084 "       float3 y5 = tex2D(Texture_First, TexCoord1 + float2(  0.0, px.y)).rgb;\n"
2085 "       float3 y6 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
2086 "       float px1 = -1.0 * dot(float3(0.3, 0.59, 0.11), x1);\n"
2087 "       float px2 = -2.0 * dot(float3(0.3, 0.59, 0.11), x2);\n"
2088 "       float px3 = -1.0 * dot(float3(0.3, 0.59, 0.11), x3);\n"
2089 "       float px4 =  1.0 * dot(float3(0.3, 0.59, 0.11), x4);\n"
2090 "       float px5 =  2.0 * dot(float3(0.3, 0.59, 0.11), x5);\n"
2091 "       float px6 =  1.0 * dot(float3(0.3, 0.59, 0.11), x6);\n"
2092 "       float py1 = -1.0 * dot(float3(0.3, 0.59, 0.11), y1);\n"
2093 "       float py2 = -2.0 * dot(float3(0.3, 0.59, 0.11), y2);\n"
2094 "       float py3 = -1.0 * dot(float3(0.3, 0.59, 0.11), y3);\n"
2095 "       float py4 =  1.0 * dot(float3(0.3, 0.59, 0.11), y4);\n"
2096 "       float py5 =  2.0 * dot(float3(0.3, 0.59, 0.11), y5);\n"
2097 "       float py6 =  1.0 * dot(float3(0.3, 0.59, 0.11), y6);\n"
2098 "       sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
2099 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
2100 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
2101 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
2102 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107,  0.707107)) * UserVec1.y;\n"
2103 "       gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990,  0.891007)) * UserVec1.y;\n"
2104 "       gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
2105 "       gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + float3(1,1,1)*max(0.0, sobel - UserVec2.z)*UserVec2.y;\n"
2106 "#endif\n"
2107 "\n"
2108 "#ifdef USESATURATION\n"
2109 "       //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2110 "       float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2111 "       // 'vampire sight' effect, wheres red is compensated\n"
2112 "       #ifdef SATURATION_REDCOMPENSATE\n"
2113 "               float rboost = max(0.0, (gl_FragColor.r - max(gl_FragColor.g, gl_FragColor.b))*(1.0 - Saturation));\n"
2114 "               gl_FragColor.rgb = lerp(float3(y,y,y), gl_FragColor.rgb, Saturation);\n"
2115 "               gl_FragColor.r += r;\n"
2116 "       #else\n"
2117 "               // normal desaturation\n"
2118 "               //gl_FragColor = float3(y,y,y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2119 "               gl_FragColor.rgb = lerp(float3(y,y,y), gl_FragColor.rgb, Saturation);\n"
2120 "       #endif\n"
2121 "#endif\n"
2122 "\n"
2123 "#ifdef USEGAMMARAMPS\n"
2124 "       gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2125 "       gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2126 "       gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2127 "#endif\n"
2128 "}\n"
2129 "#endif\n"
2130 "#else // !MODE_POSTPROCESS\n"
2131 "\n"
2132 "\n"
2133 "\n"
2134 "\n"
2135 "#ifdef MODE_GENERIC\n"
2136 "#ifdef VERTEX_SHADER\n"
2137 "void main\n"
2138 "(\n"
2139 "float4 gl_Vertex : POSITION,\n"
2140 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2141 "float4 gl_Color : COLOR0,\n"
2142 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2143 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2144 "out float4 gl_Position : POSITION,\n"
2145 "#ifdef USEDIFFUSE\n"
2146 "out float2 TexCoord1 : TEXCOORD0,\n"
2147 "#endif\n"
2148 "#ifdef USESPECULAR\n"
2149 "out float2 TexCoord2 : TEXCOORD1,\n"
2150 "#endif\n"
2151 "out float4 gl_FrontColor : COLOR\n"
2152 ")\n"
2153 "{\n"
2154 "#ifdef HLSL\n"
2155 "       gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2156 "#else\n"
2157 "       gl_FrontColor = gl_Color; // Cg is forward\n"
2158 "#endif\n"
2159 "#ifdef USEDIFFUSE\n"
2160 "       TexCoord1 = gl_MultiTexCoord0.xy;\n"
2161 "#endif\n"
2162 "#ifdef USESPECULAR\n"
2163 "       TexCoord2 = gl_MultiTexCoord1.xy;\n"
2164 "#endif\n"
2165 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2166 "}\n"
2167 "#endif\n"
2168 "\n"
2169 "#ifdef FRAGMENT_SHADER\n"
2170 "\n"
2171 "void main\n"
2172 "(\n"
2173 "float4 gl_FrontColor : COLOR0,\n"
2174 "float2 TexCoord1 : TEXCOORD0,\n"
2175 "float2 TexCoord2 : TEXCOORD1,\n"
2176 "#ifdef USEDIFFUSE\n"
2177 "uniform sampler Texture_First : register(s0),\n"
2178 "#endif\n"
2179 "#ifdef USESPECULAR\n"
2180 "uniform sampler Texture_Second : register(s1),\n"
2181 "#endif\n"
2182 "out float4 gl_FragColor : COLOR\n"
2183 ")\n"
2184 "{\n"
2185 "#ifdef USEVIEWTINT\n"
2186 "       gl_FragColor = gl_FrontColor;\n"
2187 "#else\n"
2188 "       gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
2189 "#endif\n"
2190 "#ifdef USEDIFFUSE\n"
2191 "       gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2192 "#endif\n"
2193 "\n"
2194 "#ifdef USESPECULAR\n"
2195 "       float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2196 "# ifdef USECOLORMAPPING\n"
2197 "       gl_FragColor *= tex2;\n"
2198 "# endif\n"
2199 "# ifdef USEGLOW\n"
2200 "       gl_FragColor += tex2;\n"
2201 "# endif\n"
2202 "# ifdef USEVERTEXTEXTUREBLEND\n"
2203 "       gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2204 "# endif\n"
2205 "#endif\n"
2206 "}\n"
2207 "#endif\n"
2208 "#else // !MODE_GENERIC\n"
2209 "\n"
2210 "\n"
2211 "\n"
2212 "\n"
2213 "#ifdef MODE_BLOOMBLUR\n"
2214 "#ifdef VERTEX_SHADER\n"
2215 "void main\n"
2216 "(\n"
2217 "float4 gl_Vertex : POSITION,\n"
2218 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2219 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2220 "out float4 gl_Position : POSITION,\n"
2221 "out float2 TexCoord : TEXCOORD0\n"
2222 ")\n"
2223 "{\n"
2224 "       TexCoord = gl_MultiTexCoord0.xy;\n"
2225 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2226 "}\n"
2227 "#endif\n"
2228 "\n"
2229 "#ifdef FRAGMENT_SHADER\n"
2230 "\n"
2231 "void main\n"
2232 "(\n"
2233 "float2 TexCoord : TEXCOORD0,\n"
2234 "uniform sampler Texture_First : register(s0),\n"
2235 "uniform float4 BloomBlur_Parameters : register(c1),\n"
2236 "out float4 gl_FragColor : COLOR\n"
2237 ")\n"
2238 "{\n"
2239 "       int i;\n"
2240 "       float2 tc = TexCoord;\n"
2241 "       float3 color = tex2D(Texture_First, tc).rgb;\n"
2242 "       tc += BloomBlur_Parameters.xy;\n"
2243 "       for (i = 1;i < SAMPLES;i++)\n"
2244 "       {\n"
2245 "               color += tex2D(Texture_First, tc).rgb;\n"
2246 "               tc += BloomBlur_Parameters.xy;\n"
2247 "       }\n"
2248 "       gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2249 "}\n"
2250 "#endif\n"
2251 "#else // !MODE_BLOOMBLUR\n"
2252 "#ifdef MODE_REFRACTION\n"
2253 "#ifdef VERTEX_SHADER\n"
2254 "void main\n"
2255 "(\n"
2256 "float4 gl_Vertex : POSITION,\n"
2257 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2258 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2259 "uniform float4x4 TexMatrix : register(c0),\n"
2260 "uniform float3 EyePosition : register(c24),\n"
2261 "out float4 gl_Position : POSITION,\n"
2262 "out float2 TexCoord : TEXCOORD0,\n"
2263 "out float3 EyeVector : TEXCOORD1,\n"
2264 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2265 ")\n"
2266 "{\n"
2267 "       TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2268 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2269 "       ModelViewProjectionPosition = gl_Position;\n"
2270 "}\n"
2271 "#endif\n"
2272 "\n"
2273 "#ifdef FRAGMENT_SHADER\n"
2274 "void main\n"
2275 "(\n"
2276 "float2 TexCoord : TEXCOORD0,\n"
2277 "float3 EyeVector : TEXCOORD1,\n"
2278 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2279 "uniform sampler Texture_Normal : register(s0),\n"
2280 "uniform sampler Texture_Refraction : register(s3),\n"
2281 "uniform sampler Texture_Reflection : register(s7),\n"
2282 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2283 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2284 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2285 "uniform float4 RefractColor : register(c29),\n"
2286 "out float4 gl_FragColor : COLOR\n"
2287 ")\n"
2288 "{\n"
2289 "       float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2290 "       //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2291 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2292 "       float2 ScreenTexCoord = SafeScreenTexCoord + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy * DistortScaleRefractReflect.xy;\n"
2293 "       // FIXME temporary hack to detect the case that the reflection\n"
2294 "       // gets blackened at edges due to leaving the area that contains actual\n"
2295 "       // content.\n"
2296 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2297 "       // 'appening.\n"
2298 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2299 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2300 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2301 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2302 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2303 "       gl_FragColor = float4(tex2D(Texture_Refraction, ScreenTexCoord).rgb, 1) * RefractColor;\n"
2304 "}\n"
2305 "#endif\n"
2306 "#else // !MODE_REFRACTION\n"
2307 "\n"
2308 "\n"
2309 "\n"
2310 "\n"
2311 "#ifdef MODE_WATER\n"
2312 "#ifdef VERTEX_SHADER\n"
2313 "\n"
2314 "void main\n"
2315 "(\n"
2316 "float4 gl_Vertex : POSITION,\n"
2317 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2318 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2319 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2320 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2321 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2322 "uniform float4x4 TexMatrix : register(c0),\n"
2323 "uniform float3 EyePosition : register(c24),\n"
2324 "out float4 gl_Position : POSITION,\n"
2325 "out float2 TexCoord : TEXCOORD0,\n"
2326 "out float3 EyeVector : TEXCOORD1,\n"
2327 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2328 ")\n"
2329 "{\n"
2330 "       TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2331 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2332 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2333 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2334 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2335 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2336 "       ModelViewProjectionPosition = gl_Position;\n"
2337 "}\n"
2338 "#endif\n"
2339 "\n"
2340 "#ifdef FRAGMENT_SHADER\n"
2341 "void main\n"
2342 "(\n"
2343 "float2 TexCoord : TEXCOORD0,\n"
2344 "float3 EyeVector : TEXCOORD1,\n"
2345 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2346 "uniform sampler Texture_Normal : register(s0),\n"
2347 "uniform sampler Texture_Refraction : register(s3),\n"
2348 "uniform sampler Texture_Reflection : register(s7),\n"
2349 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2350 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2351 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2352 "uniform float4 RefractColor : register(c29),\n"
2353 "uniform float4 ReflectColor : register(c26),\n"
2354 "uniform float ReflectFactor : register(c27),\n"
2355 "uniform float ReflectOffset : register(c28),\n"
2356 "out float4 gl_FragColor : COLOR\n"
2357 ")\n"
2358 "{\n"
2359 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2360 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2361 "       float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2362 "       //SafeScreenTexCoord = gl_FragCoord.xyxy * float4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
2363 "       float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy).xyxy * DistortScaleRefractReflect;\n"
2364 "       // FIXME temporary hack to detect the case that the reflection\n"
2365 "       // gets blackened at edges due to leaving the area that contains actual\n"
2366 "       // content.\n"
2367 "       // Remove this 'ack once we have a better way to stop this thing from\n"
2368 "       // 'appening.\n"
2369 "       float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2370 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2371 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2372 "       f      *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2373 "       ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2374 "       f  = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2375 "       f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2376 "       f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2377 "       f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2378 "       ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2379 "       float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2380 "       gl_FragColor = lerp(float4(tex2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, float4(tex2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
2381 "}\n"
2382 "#endif\n"
2383 "#else // !MODE_WATER\n"
2384 "\n"
2385 "\n"
2386 "\n"
2387 "\n"
2388 "// 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"
2389 "\n"
2390 "// fragment shader specific:\n"
2391 "#ifdef FRAGMENT_SHADER\n"
2392 "\n"
2393 "#ifdef USEFOG\n"
2394 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler Texture_FogMask, sampler Texture_FogHeightTexture)\n"
2395 "{\n"
2396 "       float fogfrac;\n"
2397 "#ifdef USEFOGHEIGHTTEXTURE\n"
2398 "       float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2399 "       fogfrac = fogheightpixel.a;\n"
2400 "       return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2401 "#else\n"
2402 "# ifdef USEFOGOUTSIDE\n"
2403 "       fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2404 "# else\n"
2405 "       fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2406 "# endif\n"
2407 "       return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2408 "#endif\n"
2409 "}\n"
2410 "#endif\n"
2411 "\n"
2412 "#ifdef USEOFFSETMAPPING\n"
2413 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler Texture_Normal)\n"
2414 "{\n"
2415 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2416 "       // 14 sample relief mapping: linear search and then binary search\n"
2417 "       // this basically steps forward a small amount repeatedly until it finds\n"
2418 "       // itself inside solid, then jitters forward and back using decreasing\n"
2419 "       // amounts to find the impact\n"
2420 "       //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2421 "       //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2422 "       float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2423 "       float3 RT = float3(TexCoord, 1);\n"
2424 "       OffsetVector *= 0.1;\n"
2425 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2426 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2427 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2428 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2429 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2430 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2431 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2432 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2433 "       RT += OffsetVector *  step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2434 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z)          - 0.5);\n"
2435 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5    - 0.25);\n"
2436 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25   - 0.125);\n"
2437 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125  - 0.0625);\n"
2438 "       RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2439 "       return RT.xy;\n"
2440 "#else\n"
2441 "       // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2442 "       // this basically moves forward the full distance, and then backs up based\n"
2443 "       // on height of samples\n"
2444 "       //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2445 "       //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2446 "       float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2447 "       TexCoord += OffsetVector;\n"
2448 "       OffsetVector *= 0.333;\n"
2449 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2450 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2451 "       TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2452 "       return TexCoord;\n"
2453 "#endif\n"
2454 "}\n"
2455 "#endif // USEOFFSETMAPPING\n"
2456 "\n"
2457 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2458 "#if defined(USESHADOWMAP2D)\n"
2459 "# ifdef USESHADOWMAPORTHO\n"
2460 "#  define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2461 "# else\n"
2462 "#  ifdef USESHADOWMAPVSDCT\n"
2463 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2464 "{\n"
2465 "       float3 adir = abs(dir);\n"
2466 "       float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2467 "       float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2468 "       return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2469 "}\n"
2470 "#  else\n"
2471 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2472 "{\n"
2473 "       float3 adir = abs(dir);\n"
2474 "       float ma = adir.z;\n"
2475 "       float4 proj = float4(dir, 2.5);\n"
2476 "       if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2477 "       if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2478 "#ifdef HLSL\n"
2479 "       return float3(proj.xy * ShadowMap_Parameters.x / ma + float2(0.5,0.5) + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, ma + 64 * ShadowMap_Parameters.w);\n"
2480 "#else\n"
2481 "       float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2482 "       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"
2483 "#endif\n"
2484 "}\n"
2485 "#  endif\n"
2486 "# endif\n"
2487 "#endif // defined(USESHADOWMAP2D)\n"
2488 "\n"
2489 "# ifdef USESHADOWMAP2D\n"
2490 "#ifdef USESHADOWMAPVSDCT\n"
2491 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2492 "#else\n"
2493 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2494 "#endif\n"
2495 "{\n"
2496 "#ifdef USESHADOWMAPVSDCT\n"
2497 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2498 "#else\n"
2499 "       float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2500 "#endif\n"
2501 "       float f;\n"
2502 "\n"
2503 "#  ifdef USESHADOWSAMPLER\n"
2504 "#    ifdef USESHADOWMAPPCF\n"
2505 "#      define texval(x, y) tex2Dproj(Texture_ShadowMap2D, float4(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r  \n"
2506 "       float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2507 "       f = dot(float4(0.25,0.25,0.25,0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2508 "#    else\n"
2509 "       f = tex2Dproj(Texture_ShadowMap2D, float4(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r;\n"
2510 "#    endif\n"
2511 "#  else\n"
2512 "#    ifdef USESHADOWMAPPCF\n"
2513 "#     if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2514 "#      ifdef GL_ARB_texture_gather\n"
2515 "#        define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, int2(x, y))\n"
2516 "#      else\n"
2517 "#        define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale)\n"
2518 "#      endif\n"
2519 "       float2 offset = frac(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
2520 "#      if USESHADOWMAPPCF > 1\n"
2521 "       float4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
2522 "       float4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
2523 "       float4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
2524 "       float4 group4 = step(shadowmaptc.z, texval(-2.0,  0.0));\n"
2525 "       float4 group5 = step(shadowmaptc.z, texval( 0.0,  0.0));\n"
2526 "       float4 group6 = step(shadowmaptc.z, texval( 2.0,  0.0));\n"
2527 "       float4 group7 = step(shadowmaptc.z, texval(-2.0,  2.0));\n"
2528 "       float4 group8 = step(shadowmaptc.z, texval( 0.0,  2.0));\n"
2529 "       float4 group9 = step(shadowmaptc.z, texval( 2.0,  2.0));\n"
2530 "       float4 locols = float4(group1.ab, group3.ab);\n"
2531 "       float4 hicols = float4(group7.rg, group9.rg);\n"
2532 "       locols.yz += group2.ab;\n"
2533 "       hicols.yz += group8.rg;\n"
2534 "       float4 midcols = float4(group1.rg, group3.rg) + float4(group7.ab, group9.ab) +\n"
2535 "                               float4(group4.rg, group6.rg) + float4(group4.ab, group6.ab) +\n"
2536 "                               lerp(locols, hicols, offset.y);\n"
2537 "       float4 cols = group5 + float4(group2.rg, group8.ab);\n"
2538 "       cols.xyz += lerp(midcols.xyz, midcols.yzw, offset.x);\n"
2539 "       f = dot(cols, float4(1.0/25.0));\n"
2540 "#      else\n"
2541 "       float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2542 "       float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2543 "       float4 group3 = step(shadowmaptc.z, texval(-1.0,  1.0));\n"
2544 "       float4 group4 = step(shadowmaptc.z, texval( 1.0,  1.0));\n"
2545 "       float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2546 "                               lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2547 "       f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2548 "#      endif\n"
2549 "#     else\n"
2550 "#      ifdef GL_EXT_gpu_shader4\n"
2551 "#        define texval(x, y) tex2DOffset(Texture_ShadowMap2D, center, int2(x, y)).r\n"
2552 "#      else\n"
2553 "#        define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale).r  \n"
2554 "#      endif\n"
2555 "#      if USESHADOWMAPPCF > 1\n"
2556 "       float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2557 "       center *= ShadowMap_TextureScale;\n"
2558 "       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"
2559 "       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"
2560 "       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"
2561 "       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"
2562 "       float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2563 "       f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2564 "#      else\n"
2565 "       float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2566 "       float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2567 "       float3 row2 = step(shadowmaptc.z, float3(texval(-1.0,  0.0), texval( 0.0,  0.0), texval( 1.0,  0.0)));\n"
2568 "       float3 row3 = step(shadowmaptc.z, float3(texval(-1.0,  1.0), texval( 0.0,  1.0), texval( 1.0,  1.0)));\n"
2569 "       float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2570 "       f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25,0.25));\n"
2571 "#      endif\n"
2572 "#     endif\n"
2573 "#    else\n"
2574 "       f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2575 "#    endif\n"
2576 "#  endif\n"
2577 "#  ifdef USESHADOWMAPORTHO\n"
2578 "       return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2579 "#  else\n"
2580 "       return f;\n"
2581 "#  endif\n"
2582 "}\n"
2583 "# endif\n"
2584 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
2585 "#endif // FRAGMENT_SHADER\n"
2586 "\n"
2587 "\n"
2588 "\n"
2589 "\n"
2590 "#ifdef MODE_DEFERREDGEOMETRY\n"
2591 "#ifdef VERTEX_SHADER\n"
2592 "void main\n"
2593 "(\n"
2594 "float4 gl_Vertex : POSITION,\n"
2595 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2596 "#ifdef USEVERTEXTEXTUREBLEND\n"
2597 "float4 gl_Color : COLOR0,\n"
2598 "#endif\n"
2599 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2600 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2601 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2602 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2603 "uniform float4x4 TexMatrix : register(c0),\n"
2604 "#ifdef USEVERTEXTEXTUREBLEND\n"
2605 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2606 "#endif\n"
2607 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2608 "#ifdef USEOFFSETMAPPING\n"
2609 "uniform float3 EyePosition : register(c24),\n"
2610 "#endif\n"
2611 "out float4 gl_Position : POSITION,\n"
2612 "#ifdef USEVERTEXTEXTUREBLEND\n"
2613 "out float4 gl_FrontColor : COLOR,\n"
2614 "#endif\n"
2615 "out float4 TexCoordBoth : TEXCOORD0,\n"
2616 "#ifdef USEOFFSETMAPPING\n"
2617 "out float3 EyeVector : TEXCOORD2,\n"
2618 "#endif\n"
2619 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2620 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2621 "out float4 VectorR : TEXCOORD7 // direction of R texcoord (surface normal), Depth value\n"
2622 ")\n"
2623 "{\n"
2624 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2625 "#ifdef USEVERTEXTEXTUREBLEND\n"
2626 "#ifdef HLSL\n"
2627 "       gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2628 "#else\n"
2629 "       gl_FrontColor = gl_Color; // Cg is forward\n"
2630 "#endif\n"
2631 "       TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2632 "#endif\n"
2633 "\n"
2634 "       // transform unnormalized eye direction into tangent space\n"
2635 "#ifdef USEOFFSETMAPPING\n"
2636 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2637 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2638 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2639 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2640 "#endif\n"
2641 "\n"
2642 "       VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2643 "       VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2644 "       VectorR.xyz = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2645 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2646 "       VectorR.w = gl_Position.z;\n"
2647 "}\n"
2648 "#endif // VERTEX_SHADER\n"
2649 "\n"
2650 "#ifdef FRAGMENT_SHADER\n"
2651 "void main\n"
2652 "(\n"
2653 "float4 TexCoordBoth : TEXCOORD0,\n"
2654 "float3 EyeVector : TEXCOORD2,\n"
2655 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2656 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2657 "float4 VectorR : TEXCOORD7, // direction of R texcoord (surface normal), Depth value\n"
2658 "uniform sampler Texture_Normal : register(s0),\n"
2659 "#ifdef USEALPHAKILL\n"
2660 "uniform sampler Texture_Color : register(s1),\n"
2661 "#endif\n"
2662 "uniform sampler Texture_Gloss : register(s2),\n"
2663 "#ifdef USEVERTEXTEXTUREBLEND\n"
2664 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
2665 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
2666 "#endif\n"
2667 "#ifdef USEOFFSETMAPPING\n"
2668 "uniform float OffsetMapping_Scale : register(c24),\n"
2669 "#endif\n"
2670 "uniform half SpecularPower : register(c36),\n"
2671 "#ifdef HLSL\n"
2672 "out float4 gl_FragData0 : COLOR0,\n"
2673 "out float4 gl_FragData1 : COLOR1\n"
2674 "#else\n"
2675 "out float4 gl_FragColor : COLOR\n"
2676 "#endif\n"
2677 ")\n"
2678 "{\n"
2679 "       float2 TexCoord = TexCoordBoth.xy;\n"
2680 "#ifdef USEOFFSETMAPPING\n"
2681 "       // apply offsetmapping\n"
2682 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2683 "#define TexCoord TexCoordOffset\n"
2684 "#endif\n"
2685 "\n"
2686 "#ifdef USEALPHAKILL\n"
2687 "       if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2688 "               discard;\n"
2689 "#endif\n"
2690 "\n"
2691 "#ifdef USEVERTEXTEXTUREBLEND\n"
2692 "       float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2693 "       float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2694 "       //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2695 "       //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2696 "#endif\n"
2697 "\n"
2698 "#ifdef USEVERTEXTEXTUREBLEND\n"
2699 "       float3 surfacenormal = lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend) - float3(0.5, 0.5, 0.5);\n"
2700 "       float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2).a, tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2701 "#else\n"
2702 "       float3 surfacenormal = tex2D(Texture_Normal, TexCoord).rgb - float3(0.5, 0.5, 0.5);\n"
2703 "       float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2704 "#endif\n"
2705 "\n"
2706 "#ifdef HLSL\n"
2707 "       gl_FragData0 = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR.xyz) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2708 "       float Depth = VectorR.w / 256.0;\n"
2709 "       float4 depthcolor = float4(Depth,Depth*65536.0/255.0,Depth*16777216.0/255.0,0.0);\n"
2710 "//     float4 depthcolor = float4(Depth,Depth*256.0,Depth*65536.0,0.0);\n"
2711 "       depthcolor.yz -= floor(depthcolor.yz);\n"
2712 "       gl_FragData1 = depthcolor;\n"
2713 "#else\n"
2714 "       gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2715 "#endif\n"
2716 "}\n"
2717 "#endif // FRAGMENT_SHADER\n"
2718 "#else // !MODE_DEFERREDGEOMETRY\n"
2719 "\n"
2720 "\n"
2721 "\n"
2722 "\n"
2723 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2724 "#ifdef VERTEX_SHADER\n"
2725 "void main\n"
2726 "(\n"
2727 "float4 gl_Vertex : POSITION,\n"
2728 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2729 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2730 "out float4 gl_Position : POSITION,\n"
2731 "out float4 ModelViewPosition : TEXCOORD0\n"
2732 ")\n"
2733 "{\n"
2734 "       ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2735 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2736 "}\n"
2737 "#endif // VERTEX_SHADER\n"
2738 "\n"
2739 "#ifdef FRAGMENT_SHADER\n"
2740 "void main\n"
2741 "(\n"
2742 "#ifdef HLSL\n"
2743 "float2 Pixel : VPOS,\n"
2744 "#else\n"
2745 "float2 Pixel : WPOS,\n"
2746 "#endif\n"
2747 "float4 ModelViewPosition : TEXCOORD0,\n"
2748 "uniform float4x4 ViewToLight : register(c44),\n"
2749 "uniform float2 ScreenToDepth : register(c33), // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2750 "uniform float3 LightPosition : register(c23),\n"
2751 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
2752 "uniform half3 DeferredColor_Ambient : register(c9),\n"
2753 "uniform half3 DeferredColor_Diffuse : register(c10),\n"
2754 "#ifdef USESPECULAR\n"
2755 "uniform half3 DeferredColor_Specular : register(c11),\n"
2756 "uniform half SpecularPower : register(c36),\n"
2757 "#endif\n"
2758 "uniform sampler Texture_Attenuation : register(s9),\n"
2759 "uniform sampler Texture_ScreenDepth : register(s13),\n"
2760 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
2761 "\n"
2762 "#ifdef USECUBEFILTER\n"
2763 "uniform samplerCUBE Texture_Cube : register(s10),\n"
2764 "#endif\n"
2765 "\n"
2766 "#ifdef USESHADOWMAP2D\n"
2767 "# ifdef USESHADOWSAMPLER\n"
2768 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
2769 "# else\n"
2770 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
2771 "# endif\n"
2772 "#endif\n"
2773 "\n"
2774 "#ifdef USESHADOWMAPVSDCT\n"
2775 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
2776 "#endif\n"
2777 "\n"
2778 "#if defined(USESHADOWMAP2D)\n"
2779 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
2780 "uniform float4 ShadowMap_Parameters : register(c34),\n"
2781 "#endif\n"
2782 "\n"
2783 "out float4 gl_FragData0 : COLOR0,\n"
2784 "out float4 gl_FragData1 : COLOR1\n"
2785 ")\n"
2786 "{\n"
2787 "       // calculate viewspace pixel position\n"
2788 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2789 "       //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2790 "       float3 position;\n"
2791 "#ifdef HLSL\n"
2792 "       position.z = texDepth2D(Texture_ScreenDepth, ScreenTexCoord) * 256.0;\n"
2793 "#else\n"
2794 "       position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2795 "#endif\n"
2796 "       position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2797 "       // decode viewspace pixel normal\n"
2798 "       half4 normalmap = half4(tex2D(Texture_ScreenNormalMap, ScreenTexCoord));\n"
2799 "       half3 surfacenormal = half3(normalize(normalmap.rgb - half3(0.5,0.5,0.5)));\n"
2800 "       // surfacenormal = pixel normal in viewspace\n"
2801 "       // LightVector = pixel to light in viewspace\n"
2802 "       // CubeVector = position in lightspace\n"
2803 "       // eyevector = pixel to view in viewspace\n"
2804 "       float3 CubeVector = mul(ViewToLight, float4(position,1)).xyz;\n"
2805 "       half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
2806 "#ifdef USEDIFFUSE\n"
2807 "       // calculate diffuse shading\n"
2808 "       half3 lightnormal = half3(normalize(LightPosition - position));\n"
2809 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2810 "#endif\n"
2811 "#ifdef USESPECULAR\n"
2812 "       // calculate directional shading\n"
2813 "       float3 eyevector = position * -1.0;\n"
2814 "#  ifdef USEEXACTSPECULARMATH\n"
2815 "       half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a));\n"
2816 "#  else\n"
2817 "       half3 specularnormal = half3(normalize(lightnormal + half3(normalize(eyevector))));\n"
2818 "       half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a));\n"
2819 "#  endif\n"
2820 "#endif\n"
2821 "\n"
2822 "#if defined(USESHADOWMAP2D)\n"
2823 "       fade *= half(ShadowMapCompare(CubeVector, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2824 "#ifdef USESHADOWMAPVSDCT\n"
2825 ", Texture_CubeProjection\n"
2826 "#endif\n"
2827 "       ));\n"
2828 "#endif\n"
2829 "\n"
2830 "#ifdef USEDIFFUSE\n"
2831 "       gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2832 "#else\n"
2833 "       gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2834 "#endif\n"
2835 "#ifdef USESPECULAR\n"
2836 "       gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2837 "#else\n"
2838 "       gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2839 "#endif\n"
2840 "\n"
2841 "# ifdef USECUBEFILTER\n"
2842 "       float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2843 "       gl_FragData0.rgb *= cubecolor;\n"
2844 "       gl_FragData1.rgb *= cubecolor;\n"
2845 "# endif\n"
2846 "}\n"
2847 "#endif // FRAGMENT_SHADER\n"
2848 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2849 "\n"
2850 "\n"
2851 "\n"
2852 "\n"
2853 "#ifdef VERTEX_SHADER\n"
2854 "void main\n"
2855 "(\n"
2856 "float4 gl_Vertex : POSITION,\n"
2857 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2858 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2859 "float4 gl_Color : COLOR0,\n"
2860 "#endif\n"
2861 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2862 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2863 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2864 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2865 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2866 "\n"
2867 "uniform float3 EyePosition : register(c24),\n"
2868 "uniform float4x4 TexMatrix : register(c0),\n"
2869 "#ifdef USEVERTEXTEXTUREBLEND\n"
2870 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2871 "#endif\n"
2872 "#ifdef MODE_LIGHTSOURCE\n"
2873 "uniform float4x4 ModelToLight : register(c20),\n"
2874 "#endif\n"
2875 "#ifdef MODE_LIGHTSOURCE\n"
2876 "uniform float3 LightPosition : register(c27),\n"
2877 "#endif\n"
2878 "#ifdef MODE_LIGHTDIRECTION\n"
2879 "uniform float3 LightDir : register(c26),\n"
2880 "#endif\n"
2881 "uniform float4 FogPlane : register(c25),\n"
2882 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2883 "uniform float3 LightPosition : register(c27),\n"
2884 "#endif\n"
2885 "#ifdef USESHADOWMAPORTHO\n"
2886 "uniform float4x4 ShadowMapMatrix : register(c16),\n"
2887 "#endif\n"
2888 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2889 "out float4 gl_FrontColor : COLOR,\n"
2890 "#endif\n"
2891 "out float4 TexCoordBoth : TEXCOORD0,\n"
2892 "#ifdef USELIGHTMAP\n"
2893 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2894 "#endif\n"
2895 "#ifdef USEEYEVECTOR\n"
2896 "out float3 EyeVector : TEXCOORD2,\n"
2897 "#endif\n"
2898 "#ifdef USEREFLECTION\n"
2899 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2900 "#endif\n"
2901 "#ifdef USEFOG\n"
2902 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2903 "#endif\n"
2904 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE) || defined(USEDIFFUSE)\n"
2905 "out float3 LightVector : TEXCOORD1,\n"
2906 "#endif\n"
2907 "#ifdef MODE_LIGHTSOURCE\n"
2908 "out float3 CubeVector : TEXCOORD3,\n"
2909 "#endif\n"
2910 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2911 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2912 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2913 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2914 "#endif\n"
2915 "#ifdef USESHADOWMAPORTHO\n"
2916 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2917 "#endif\n"
2918 "out float4 gl_Position : POSITION\n"
2919 ")\n"
2920 "{\n"
2921 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2922 "#ifdef HLSL\n"
2923 "       gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2924 "#else\n"
2925 "       gl_FrontColor = gl_Color; // Cg is forward\n"
2926 "#endif\n"
2927 "#endif\n"
2928 "       // copy the surface texcoord\n"
2929 "       TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2930 "#ifdef USEVERTEXTEXTUREBLEND\n"
2931 "       TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2932 "#endif\n"
2933 "#ifdef USELIGHTMAP\n"
2934 "       TexCoordLightmap = gl_MultiTexCoord4.xy;\n"
2935 "#endif\n"
2936 "\n"
2937 "#ifdef MODE_LIGHTSOURCE\n"
2938 "       // transform vertex position into light attenuation/cubemap space\n"
2939 "       // (-1 to +1 across the light box)\n"
2940 "       CubeVector = mul(ModelToLight, gl_Vertex).xyz;\n"
2941 "\n"
2942 "# ifdef USEDIFFUSE\n"
2943 "       // transform unnormalized light direction into tangent space\n"
2944 "       // (we use unnormalized to ensure that it interpolates correctly and then\n"
2945 "       //  normalize it per pixel)\n"
2946 "       float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2947 "       LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2948 "       LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2949 "       LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2950 "# endif\n"
2951 "#endif\n"
2952 "\n"
2953 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2954 "       LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2955 "       LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2956 "       LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2957 "#endif\n"
2958 "\n"
2959 "       // transform unnormalized eye direction into tangent space\n"
2960 "#ifdef USEEYEVECTOR\n"
2961 "       float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2962 "       EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2963 "       EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2964 "       EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2965 "#endif\n"
2966 "\n"
2967 "#ifdef USEFOG\n"
2968 "       EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2969 "       EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2970 "#endif\n"
2971 "\n"
2972 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2973 "       VectorS = gl_MultiTexCoord1.xyz;\n"
2974 "       VectorT = gl_MultiTexCoord2.xyz;\n"
2975 "       VectorR = gl_MultiTexCoord3.xyz;\n"
2976 "#endif\n"
2977 "\n"
2978 "       // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2979 "       gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2980 "\n"
2981 "#ifdef USESHADOWMAPORTHO\n"
2982 "       ShadowMapTC = mul(ShadowMapMatrix, gl_Position).xyz;\n"
2983 "#endif\n"
2984 "\n"
2985 "#ifdef USEREFLECTION\n"
2986 "       ModelViewProjectionPosition = gl_Position;\n"
2987 "#endif\n"
2988 "}\n"
2989 "#endif // VERTEX_SHADER\n"
2990 "\n"
2991 "\n"
2992 "\n"
2993 "\n"
2994 "#ifdef FRAGMENT_SHADER\n"
2995 "void main\n"
2996 "(\n"
2997 "#ifdef USEDEFERREDLIGHTMAP\n"
2998 "#ifdef HLSL\n"
2999 "float2 Pixel : VPOS,\n"
3000 "#else\n"
3001 "float2 Pixel : WPOS,\n"
3002 "#endif\n"
3003 "#endif\n"
3004 "float4 gl_FrontColor : COLOR,\n"
3005 "float4 TexCoordBoth : TEXCOORD0,\n"
3006 "#ifdef USELIGHTMAP\n"
3007 "float2 TexCoordLightmap : TEXCOORD1,\n"
3008 "#endif\n"
3009 "#ifdef USEEYEVECTOR\n"
3010 "float3 EyeVector : TEXCOORD2,\n"
3011 "#endif\n"
3012 "#ifdef USEREFLECTION\n"
3013 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
3014 "#endif\n"
3015 "#ifdef USEFOG\n"
3016 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
3017 "#endif\n"
3018 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
3019 "float3 LightVector : TEXCOORD1,\n"
3020 "#endif\n"
3021 "#ifdef MODE_LIGHTSOURCE\n"
3022 "float3 CubeVector : TEXCOORD3,\n"
3023 "#endif\n"
3024 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
3025 "float4 ModelViewPosition : TEXCOORD0,\n"
3026 "#endif\n"
3027 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
3028 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
3029 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
3030 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
3031 "#endif\n"
3032 "#ifdef USESHADOWMAPORTHO\n"
3033 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
3034 "#endif\n"
3035 "\n"
3036 "uniform sampler Texture_Normal : register(s0),\n"
3037 "uniform sampler Texture_Color : register(s1),\n"
3038 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3039 "uniform sampler Texture_Gloss : register(s2),\n"
3040 "#endif\n"
3041 "#ifdef USEGLOW\n"
3042 "uniform sampler Texture_Glow : register(s3),\n"
3043 "#endif\n"
3044 "#ifdef USEVERTEXTEXTUREBLEND\n"
3045 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
3046 "uniform sampler Texture_SecondaryColor : register(s5),\n"
3047 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3048 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
3049 "#endif\n"
3050 "#ifdef USEGLOW\n"
3051 "uniform sampler Texture_SecondaryGlow : register(s7),\n"
3052 "#endif\n"
3053 "#endif\n"
3054 "#ifdef USECOLORMAPPING\n"
3055 "uniform sampler Texture_Pants : register(s4),\n"
3056 "uniform sampler Texture_Shirt : register(s7),\n"
3057 "#endif\n"
3058 "#ifdef USEFOG\n"
3059 "uniform sampler Texture_FogHeightTexture : register(s14),\n"
3060 "uniform sampler Texture_FogMask : register(s8),\n"
3061 "#endif\n"
3062 "#ifdef USELIGHTMAP\n"
3063 "uniform sampler Texture_Lightmap : register(s9),\n"
3064 "#endif\n"
3065 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
3066 "uniform sampler Texture_Deluxemap : register(s10),\n"
3067 "#endif\n"
3068 "#ifdef USEREFLECTION\n"
3069 "uniform sampler Texture_Reflection : register(s7),\n"
3070 "#endif\n"
3071 "\n"
3072 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
3073 "uniform sampler Texture_ScreenDepth : register(s13),\n"
3074 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
3075 "#endif\n"
3076 "#ifdef USEDEFERREDLIGHTMAP\n"
3077 "uniform sampler Texture_ScreenDepth : register(s13),\n"
3078 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
3079 "uniform sampler Texture_ScreenDiffuse : register(s11),\n"
3080 "uniform sampler Texture_ScreenSpecular : register(s12),\n"
3081 "#endif\n"
3082 "\n"
3083 "#ifdef USECOLORMAPPING\n"
3084 "uniform half3 Color_Pants : register(c7),\n"
3085 "uniform half3 Color_Shirt : register(c8),\n"
3086 "#endif\n"
3087 "#ifdef USEFOG\n"
3088 "uniform float3 FogColor : register(c16),\n"
3089 "uniform float FogRangeRecip : register(c20),\n"
3090 "uniform float FogPlaneViewDist : register(c19),\n"
3091 "uniform float FogHeightFade : register(c17),\n"
3092 "#endif\n"
3093 "\n"
3094 "#ifdef USEOFFSETMAPPING\n"
3095 "uniform float OffsetMapping_Scale : register(c24),\n"
3096 "#endif\n"
3097 "\n"
3098 "#ifdef USEDEFERREDLIGHTMAP\n"
3099 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
3100 "uniform half3 DeferredMod_Diffuse : register(c12),\n"
3101 "uniform half3 DeferredMod_Specular : register(c13),\n"
3102 "#endif\n"
3103 "uniform half3 Color_Ambient : register(c3),\n"
3104 "uniform half3 Color_Diffuse : register(c4),\n"
3105 "uniform half3 Color_Specular : register(c5),\n"
3106 "uniform half SpecularPower : register(c36),\n"
3107 "#ifdef USEGLOW\n"
3108 "uniform half3 Color_Glow : register(c6),\n"
3109 "#endif\n"
3110 "uniform half Alpha : register(c0),\n"
3111 "#ifdef USEREFLECTION\n"
3112 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
3113 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
3114 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
3115 "uniform half4 ReflectColor : register(c26),\n"
3116 "#endif\n"
3117 "#ifdef USEREFLECTCUBE\n"
3118 "uniform float4x4 ModelToReflectCube : register(c48),\n"
3119 "uniform sampler Texture_ReflectMask : register(s5),\n"
3120 "uniform samplerCUBE Texture_ReflectCube : register(s6),\n"
3121 "#endif\n"
3122 "#ifdef MODE_LIGHTDIRECTION\n"
3123 "uniform half3 LightColor : register(c21),\n"
3124 "#endif\n"
3125 "#ifdef MODE_LIGHTSOURCE\n"
3126 "uniform half3 LightColor : register(c21),\n"
3127 "#endif\n"
3128 "\n"
3129 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3130 "uniform sampler Texture_Attenuation : register(s9),\n"
3131 "uniform samplerCUBE Texture_Cube : register(s10),\n"
3132 "#endif\n"
3133 "\n"
3134 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3135 "\n"
3136 "#ifdef USESHADOWMAP2D\n"
3137 "# ifdef USESHADOWSAMPLER\n"
3138 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
3139 "# else\n"
3140 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
3141 "# endif\n"
3142 "#endif\n"
3143 "\n"
3144 "#ifdef USESHADOWMAPVSDCT\n"
3145 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
3146 "#endif\n"
3147 "\n"
3148 "#if defined(USESHADOWMAP2D)\n"
3149 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
3150 "uniform float4 ShadowMap_Parameters : register(c34),\n"
3151 "#endif\n"
3152 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3153 "\n"
3154 "out float4 gl_FragColor : COLOR\n"
3155 ")\n"
3156 "{\n"
3157 "       float2 TexCoord = TexCoordBoth.xy;\n"
3158 "#ifdef USEVERTEXTEXTUREBLEND\n"
3159 "       float2 TexCoord2 = TexCoordBoth.zw;\n"
3160 "#endif\n"
3161 "#ifdef USEOFFSETMAPPING\n"
3162 "       // apply offsetmapping\n"
3163 "       float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3164 "#define TexCoord TexCoordOffset\n"
3165 "#endif\n"
3166 "\n"
3167 "       // combine the diffuse textures (base, pants, shirt)\n"
3168 "       half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3169 "#ifdef USEALPHAKILL\n"
3170 "       if (color.a < 0.5)\n"
3171 "               discard;\n"
3172 "#endif\n"
3173 "       color.a *= Alpha;\n"
3174 "#ifdef USECOLORMAPPING\n"
3175 "       color.rgb += half3(tex2D(Texture_Pants, TexCoord).rgb) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord).rgb) * Color_Shirt;\n"
3176 "#endif\n"
3177 "#ifdef USEVERTEXTEXTUREBLEND\n"
3178 "       half terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3179 "       //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3180 "       //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3181 "       color.rgb = half3(lerp(tex2D(Texture_SecondaryColor, TexCoord2).rgb, float3(color.rgb), terrainblend));\n"
3182 "       color.a = 1.0;\n"
3183 "       //color = half4(lerp(float4(1, 0, 0, 1), color, terrainblend));\n"
3184 "#endif\n"
3185 "\n"
3186 "       // get the surface normal\n"
3187 "#ifdef USEVERTEXTEXTUREBLEND\n"
3188 "       half3 surfacenormal = normalize(half3(lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3189 "#else\n"
3190 "       half3 surfacenormal = half3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5, 0.5, 0.5)));\n"
3191 "#endif\n"
3192 "\n"
3193 "       // get the material colors\n"
3194 "       half3 diffusetex = color.rgb;\n"
3195 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3196 "# ifdef USEVERTEXTEXTUREBLEND\n"
3197 "       half4 glosstex = half4(lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord), terrainblend));\n"
3198 "# else\n"
3199 "       half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3200 "# endif\n"
3201 "#endif\n"
3202 "\n"
3203 "#ifdef USEREFLECTCUBE\n"
3204 "       float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3205 "       float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3206 "       float3 ReflectCubeTexCoord = mul(ModelToReflectCube, float4(ModelReflectVector, 0)).xyz;\n"
3207 "       diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord).rgb) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord).rgb);\n"
3208 "#endif\n"
3209 "\n"
3210 "\n"
3211 "\n"
3212 "\n"
3213 "#ifdef MODE_LIGHTSOURCE\n"
3214 "       // light source\n"
3215 "#ifdef USEDIFFUSE\n"
3216 "       half3 lightnormal = half3(normalize(LightVector));\n"
3217 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3218 "       color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3219 "#ifdef USESPECULAR\n"
3220 "#ifdef USEEXACTSPECULARMATH\n"
3221 "       half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3222 "#else\n"
3223 "       half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3224 "       half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3225 "#endif\n"
3226 "       color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3227 "#endif\n"
3228 "#else\n"
3229 "       color.rgb = diffusetex * Color_Ambient;\n"
3230 "#endif\n"
3231 "       color.rgb *= LightColor;\n"
3232 "       color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
3233 "#if defined(USESHADOWMAP2D)\n"
3234 "       color.rgb *= half(ShadowMapCompare(CubeVector, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3235 "#ifdef USESHADOWMAPVSDCT\n"
3236 ", Texture_CubeProjection\n"
3237 "#endif\n"
3238 "       ));\n"
3239 "\n"
3240 "#endif\n"
3241 "# ifdef USECUBEFILTER\n"
3242 "       color.rgb *= half3(texCUBE(Texture_Cube, CubeVector).rgb);\n"
3243 "# endif\n"
3244 "\n"
3245 "#ifdef USESHADOWMAP2D\n"
3246 "#ifdef USESHADOWMAPVSDCT\n"
3247 "//     float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters, Texture_CubeProjection);\n"
3248 "#else\n"
3249 "//     float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters);\n"
3250 "#endif\n"
3251 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3252 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale).rgb);\n"
3253 "//     color.rgb = half3(shadowmaptc.xyz * float3(ShadowMap_TextureScale,1.0));\n"
3254 "//     color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3255 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3256 "//     color.rgb = half3(tex2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale).rgb);\n"
3257 "//     color.rgb = half3(shadowmaptc.xyz * float3(ShadowMap_TextureScale,1.0));\n"
3258 "//     color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3259 "//     color.r = half(shadowmaptc.z - texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3260 "//     color.r = half(shadowmaptc.z);\n"
3261 "//     color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3262 "//     color.r = half(shadowmaptc.z);\n"
3263 "//     color.r = 1;\n"
3264 "//     color.rgb = abs(CubeVector);\n"
3265 "#endif\n"
3266 "//     color.rgb = half3(1,1,1);\n"
3267 "#endif // MODE_LIGHTSOURCE\n"
3268 "\n"
3269 "\n"
3270 "\n"
3271 "\n"
3272 "#ifdef MODE_LIGHTDIRECTION\n"
3273 "#define SHADING\n"
3274 "#ifdef USEDIFFUSE\n"
3275 "       half3 lightnormal = half3(normalize(LightVector));\n"
3276 "#endif\n"
3277 "#define lightcolor LightColor\n"
3278 "#endif // MODE_LIGHTDIRECTION\n"
3279 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3280 "#define SHADING\n"
3281 "       // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3282 "       half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3283 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3284 "       // convert modelspace light vector to tangentspace\n"
3285 "       half3 lightnormal;\n"
3286 "       lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3287 "       lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3288 "       lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3289 "       // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3290 "       // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3291 "       // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3292 "       // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3293 "       // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3294 "       // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3295 "       // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3296 "       // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3297 "       // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3298 "       lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3299 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3300 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3301 "#define SHADING\n"
3302 "       // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3303 "       half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3304 "       half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3305 "#endif\n"
3306 "\n"
3307 "\n"
3308 "\n"
3309 "\n"
3310 "#ifdef MODE_FAKELIGHT\n"
3311 "#define SHADING\n"
3312 "half3 lightnormal = half3(normalize(EyeVector));\n"
3313 "half3 lightcolor = half3(1.0,1.0,1.0);\n"
3314 "#endif // MODE_FAKELIGHT\n"
3315 "\n"
3316 "\n"
3317 "\n"
3318 "\n"
3319 "#ifdef MODE_LIGHTMAP\n"
3320 "       color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb) * Color_Diffuse);\n"
3321 "#endif // MODE_LIGHTMAP\n"
3322 "#ifdef MODE_VERTEXCOLOR\n"
3323 "       color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3324 "#endif // MODE_VERTEXCOLOR\n"
3325 "#ifdef MODE_FLATCOLOR\n"
3326 "       color.rgb = diffusetex * Color_Ambient;\n"
3327 "#endif // MODE_FLATCOLOR\n"
3328 "\n"
3329 "\n"
3330 "\n"
3331 "\n"
3332 "#ifdef SHADING\n"
3333 "# ifdef USEDIFFUSE\n"
3334 "       half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3335 "#  ifdef USESPECULAR\n"
3336 "#   ifdef USEEXACTSPECULARMATH\n"
3337 "       half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3338 "#   else\n"
3339 "       half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3340 "       half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3341 "#   endif\n"
3342 "       color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3343 "#  else\n"
3344 "       color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3345 "#  endif\n"
3346 "# else\n"
3347 "       color.rgb = diffusetex * Color_Ambient;\n"
3348 "# endif\n"
3349 "#endif\n"
3350 "\n"
3351 "#ifdef USESHADOWMAPORTHO\n"
3352 "       color.rgb *= half(ShadowMapCompare(ShadowMapTC, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale));\n"
3353 "#endif\n"
3354 "\n"
3355 "#ifdef USEDEFERREDLIGHTMAP\n"
3356 "       float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3357 "       color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord).rgb) * DeferredMod_Diffuse;\n"
3358 "       color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord).rgb) * DeferredMod_Specular;\n"
3359 "//     color.rgb = half3(tex2D(Texture_ScreenDepth, ScreenTexCoord).rgb);\n"
3360 "//     color.r = half(texDepth2D(Texture_ScreenDepth, ScreenTexCoord)) * 1.0;\n"
3361 "#endif\n"
3362 "\n"
3363 "#ifdef USEGLOW\n"
3364 "#ifdef USEVERTEXTEXTUREBLEND\n"
3365 "       color.rgb += half3(lerp(tex2D(Texture_SecondaryGlow, TexCoord2).rgb, tex2D(Texture_Glow, TexCoord).rgb, terrainblend)) * Color_Glow;\n"
3366 "#else\n"
3367 "       color.rgb += half3(tex2D(Texture_Glow, TexCoord).rgb) * Color_Glow;\n"
3368 "#endif\n"
3369 "#endif\n"
3370 "\n"
3371 "#ifdef USEFOG\n"
3372 "       color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3373 "#endif\n"
3374 "\n"
3375 "       // 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"
3376 "#ifdef USEREFLECTION\n"
3377 "       float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3378 "       //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3379 "       float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3380 "       float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5))).xy * DistortScaleRefractReflect.zw;\n"
3381 "       // FIXME temporary hack to detect the case that the reflection\n"
3382 "       // gets blackened at edges due to leaving the area that contains actual\n"
3383 "       // content.\n"
3384 "       // Remove this 'ack once we have a better way to stop this thing from\n"
3385 "       // 'appening.\n"
3386 "       float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3387 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3388 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3389 "       f      *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3390 "       ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3391 "       color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord).rgb) * ReflectColor.rgb, ReflectColor.a);\n"
3392 "#endif\n"
3393 "\n"
3394 "       gl_FragColor = float4(color);\n"
3395 "}\n"
3396 "#endif // FRAGMENT_SHADER\n"
3397 "\n"
3398 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3399 "#endif // !MODE_DEFERREDGEOMETRY\n"
3400 "#endif // !MODE_WATER\n"
3401 "#endif // !MODE_REFRACTION\n"
3402 "#endif // !MODE_BLOOMBLUR\n"
3403 "#endif // !MODE_GENERIC\n"
3404 "#endif // !MODE_POSTPROCESS\n"
3405 "#endif // !MODE_SHOWDEPTH\n"
3406 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3407 ;
3408
3409 char *glslshaderstring = NULL;
3410 char *hlslshaderstring = NULL;
3411
3412 //=======================================================================================================================================================
3413
3414 typedef struct shaderpermutationinfo_s
3415 {
3416         const char *pretext;
3417         const char *name;
3418 }
3419 shaderpermutationinfo_t;
3420
3421 typedef struct shadermodeinfo_s
3422 {
3423         const char *vertexfilename;
3424         const char *geometryfilename;
3425         const char *fragmentfilename;
3426         const char *pretext;
3427         const char *name;
3428 }
3429 shadermodeinfo_t;
3430
3431 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3432 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3433 {
3434         {"#define USEDIFFUSE\n", " diffuse"},
3435         {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3436         {"#define USEVIEWTINT\n", " viewtint"},
3437         {"#define USECOLORMAPPING\n", " colormapping"},
3438         {"#define USESATURATION\n", " saturation"},
3439         {"#define USEFOGINSIDE\n", " foginside"},
3440         {"#define USEFOGOUTSIDE\n", " fogoutside"},
3441         {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3442         {"#define USEGAMMARAMPS\n", " gammaramps"},
3443         {"#define USECUBEFILTER\n", " cubefilter"},
3444         {"#define USEGLOW\n", " glow"},
3445         {"#define USEBLOOM\n", " bloom"},
3446         {"#define USESPECULAR\n", " specular"},
3447         {"#define USEPOSTPROCESSING\n", " postprocessing"},
3448         {"#define USEREFLECTION\n", " reflection"},
3449         {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3450         {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3451         {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3452         {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3453         {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3454         {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3455         {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3456         {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3457         {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3458         {"#define USEALPHAKILL\n", " alphakill"},
3459         {"#define USEREFLECTCUBE\n", " reflectcube"},
3460         {"#define USENORMALMAPSCROLLBLEND\n", " normalmapscrollblend"},
3461         {"#define USEBOUNCEGRID\n", " bouncegrid"},
3462 };
3463
3464 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3465 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3466 {
3467         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3468         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3469         {"glsl/default.glsl", NULL, NULL               , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3470         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3471         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3472         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3473         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FAKELIGHT\n", " fakelight"},
3474         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3475         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3476         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3477         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3478         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3479         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3480         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3481         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3482         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3483         {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDBOUNCELIGHT\n", " deferredbouncelight"},
3484 };
3485
3486 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
3487 {
3488         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
3489         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3490         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3491         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3492         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3493         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3494         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FAKELIGHT\n", " fakelight"},
3495         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3496         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3497         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3498         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3499         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
3500         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
3501         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3502         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3503         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3504         {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDBOUNCELIGHT\n", " deferredbouncelight"},
3505 };
3506
3507 struct r_glsl_permutation_s;
3508 typedef struct r_glsl_permutation_s
3509 {
3510         /// hash lookup data
3511         struct r_glsl_permutation_s *hashnext;
3512         unsigned int mode;
3513         unsigned int permutation;
3514
3515         /// indicates if we have tried compiling this permutation already
3516         qboolean compiled;
3517         /// 0 if compilation failed
3518         int program;
3519         // texture units assigned to each detected uniform
3520         int tex_Texture_First;
3521         int tex_Texture_Second;
3522         int tex_Texture_GammaRamps;
3523         int tex_Texture_Normal;
3524         int tex_Texture_Color;
3525         int tex_Texture_Gloss;
3526         int tex_Texture_Glow;
3527         int tex_Texture_SecondaryNormal;
3528         int tex_Texture_SecondaryColor;
3529         int tex_Texture_SecondaryGloss;
3530         int tex_Texture_SecondaryGlow;
3531         int tex_Texture_Pants;
3532         int tex_Texture_Shirt;
3533         int tex_Texture_FogHeightTexture;
3534         int tex_Texture_FogMask;
3535         int tex_Texture_Lightmap;
3536         int tex_Texture_Deluxemap;
3537         int tex_Texture_Attenuation;
3538         int tex_Texture_Cube;
3539         int tex_Texture_Refraction;
3540         int tex_Texture_Reflection;
3541         int tex_Texture_ShadowMap2D;
3542         int tex_Texture_CubeProjection;
3543         int tex_Texture_ScreenDepth;
3544         int tex_Texture_ScreenNormalMap;
3545         int tex_Texture_ScreenDiffuse;
3546         int tex_Texture_ScreenSpecular;
3547         int tex_Texture_ReflectMask;
3548         int tex_Texture_ReflectCube;
3549         int tex_Texture_BounceGrid;
3550         /// locations of detected uniforms in program object, or -1 if not found
3551         int loc_Texture_First;
3552         int loc_Texture_Second;
3553         int loc_Texture_GammaRamps;
3554         int loc_Texture_Normal;
3555         int loc_Texture_Color;
3556         int loc_Texture_Gloss;
3557         int loc_Texture_Glow;
3558         int loc_Texture_SecondaryNormal;
3559         int loc_Texture_SecondaryColor;
3560         int loc_Texture_SecondaryGloss;
3561         int loc_Texture_SecondaryGlow;
3562         int loc_Texture_Pants;
3563         int loc_Texture_Shirt;
3564         int loc_Texture_FogHeightTexture;
3565         int loc_Texture_FogMask;
3566         int loc_Texture_Lightmap;
3567         int loc_Texture_Deluxemap;
3568         int loc_Texture_Attenuation;
3569         int loc_Texture_Cube;
3570         int loc_Texture_Refraction;
3571         int loc_Texture_Reflection;
3572         int loc_Texture_ShadowMap2D;
3573         int loc_Texture_CubeProjection;
3574         int loc_Texture_ScreenDepth;
3575         int loc_Texture_ScreenNormalMap;
3576         int loc_Texture_ScreenDiffuse;
3577         int loc_Texture_ScreenSpecular;
3578         int loc_Texture_ReflectMask;
3579         int loc_Texture_ReflectCube;
3580         int loc_Texture_BounceGrid;
3581         int loc_Alpha;
3582         int loc_BloomBlur_Parameters;
3583         int loc_ClientTime;
3584         int loc_Color_Ambient;
3585         int loc_Color_Diffuse;
3586         int loc_Color_Specular;
3587         int loc_Color_Glow;
3588         int loc_Color_Pants;
3589         int loc_Color_Shirt;
3590         int loc_DeferredColor_Ambient;
3591         int loc_DeferredColor_Diffuse;
3592         int loc_DeferredColor_Specular;
3593         int loc_DeferredMod_Diffuse;
3594         int loc_DeferredMod_Specular;
3595         int loc_DistortScaleRefractReflect;
3596         int loc_EyePosition;
3597         int loc_FogColor;
3598         int loc_FogHeightFade;
3599         int loc_FogPlane;
3600         int loc_FogPlaneViewDist;
3601         int loc_FogRangeRecip;
3602         int loc_LightColor;
3603         int loc_LightDir;
3604         int loc_LightPosition;
3605         int loc_OffsetMapping_Scale;
3606         int loc_PixelSize;
3607         int loc_ReflectColor;
3608         int loc_ReflectFactor;
3609         int loc_ReflectOffset;
3610         int loc_RefractColor;
3611         int loc_Saturation;
3612         int loc_ScreenCenterRefractReflect;
3613         int loc_ScreenScaleRefractReflect;
3614         int loc_ScreenToDepth;
3615         int loc_ShadowMap_Parameters;
3616         int loc_ShadowMap_TextureScale;
3617         int loc_SpecularPower;
3618         int loc_UserVec1;
3619         int loc_UserVec2;
3620         int loc_UserVec3;
3621         int loc_UserVec4;
3622         int loc_ViewTintColor;
3623         int loc_ViewToLight;
3624         int loc_ModelToLight;
3625         int loc_TexMatrix;
3626         int loc_BackgroundTexMatrix;
3627         int loc_ModelViewProjectionMatrix;
3628         int loc_ModelViewMatrix;
3629         int loc_PixelToScreenTexCoord;
3630         int loc_ModelToReflectCube;
3631         int loc_ShadowMapMatrix;
3632         int loc_BloomColorSubtract;
3633         int loc_NormalmapScrollBlend;
3634         int loc_BounceGridMatrix;
3635         int loc_BounceGridIntensity;
3636 }
3637 r_glsl_permutation_t;
3638
3639 #define SHADERPERMUTATION_HASHSIZE 256
3640
3641
3642 // non-degradable "lightweight" shader parameters to keep the permutations simpler
3643 // these can NOT degrade! only use for simple stuff
3644 enum
3645 {
3646         SHADERSTATICPARM_SATURATION_REDCOMPENSATE = 0, ///< red compensation filter for saturation
3647         SHADERSTATICPARM_EXACTSPECULARMATH = 1, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3648         SHADERSTATICPARM_POSTPROCESS_USERVEC1 = 2, ///< postprocess uservec1 is enabled
3649         SHADERSTATICPARM_POSTPROCESS_USERVEC2 = 3, ///< postprocess uservec2 is enabled
3650         SHADERSTATICPARM_POSTPROCESS_USERVEC3 = 4, ///< postprocess uservec3 is enabled
3651         SHADERSTATICPARM_POSTPROCESS_USERVEC4 = 5  ///< postprocess uservec4 is enabled
3652 };
3653 #define SHADERSTATICPARMS_COUNT 6
3654
3655 static const char *shaderstaticparmstrings_list[SHADERSTATICPARMS_COUNT];
3656 static int shaderstaticparms_count = 0;
3657
3658 static unsigned int r_compileshader_staticparms[(SHADERSTATICPARMS_COUNT + 0x1F) >> 5] = {0};
3659 #define R_COMPILESHADER_STATICPARM_ENABLE(p) r_compileshader_staticparms[(p) >> 5] |= (1 << ((p) & 0x1F))
3660 qboolean R_CompileShader_CheckStaticParms(void)
3661 {
3662         static int r_compileshader_staticparms_save[1];
3663         memcpy(r_compileshader_staticparms_save, r_compileshader_staticparms, sizeof(r_compileshader_staticparms));
3664         memset(r_compileshader_staticparms, 0, sizeof(r_compileshader_staticparms));
3665
3666         // detect all
3667         if (r_glsl_saturation_redcompensate.integer)
3668                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_SATURATION_REDCOMPENSATE);
3669         if (r_shadow_glossexact.integer)
3670                 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_EXACTSPECULARMATH);
3671         if (r_glsl_postprocess.integer)
3672         {
3673                 if (r_glsl_postprocess_uservec1_enable.integer)
3674                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC1);
3675                 if (r_glsl_postprocess_uservec2_enable.integer)
3676                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC2);
3677                 if (r_glsl_postprocess_uservec3_enable.integer)
3678                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC3);
3679                 if (r_glsl_postprocess_uservec4_enable.integer)
3680                         R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC4);
3681         }
3682         return memcmp(r_compileshader_staticparms, r_compileshader_staticparms_save, sizeof(r_compileshader_staticparms)) != 0;
3683 }
3684
3685 #define R_COMPILESHADER_STATICPARM_EMIT(p, n) \
3686         if(r_compileshader_staticparms[(p) >> 5] & (1 << ((p) & 0x1F))) \
3687                 shaderstaticparmstrings_list[shaderstaticparms_count++] = "#define " n "\n"; \
3688         else \
3689                 shaderstaticparmstrings_list[shaderstaticparms_count++] = "\n"
3690 void R_CompileShader_AddStaticParms(unsigned int mode, unsigned int permutation)
3691 {
3692         shaderstaticparms_count = 0;
3693
3694         // emit all
3695         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_SATURATION_REDCOMPENSATE, "SATURATION_REDCOMPENSATE");
3696         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_EXACTSPECULARMATH, "USEEXACTSPECULARMATH");
3697         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC1, "USERVEC1");
3698         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC2, "USERVEC2");
3699         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC3, "USERVEC3");
3700         R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC4, "USERVEC4");
3701 }
3702
3703 /// information about each possible shader permutation
3704 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3705 /// currently selected permutation
3706 r_glsl_permutation_t *r_glsl_permutation;
3707 /// storage for permutations linked in the hash table
3708 memexpandablearray_t r_glsl_permutationarray;
3709
3710 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3711 {
3712         //unsigned int hashdepth = 0;
3713         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3714         r_glsl_permutation_t *p;
3715         for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3716         {
3717                 if (p->mode == mode && p->permutation == permutation)
3718                 {
3719                         //if (hashdepth > 10)
3720                         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3721                         return p;
3722                 }
3723                 //hashdepth++;
3724         }
3725         p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3726         p->mode = mode;
3727         p->permutation = permutation;
3728         p->hashnext = r_glsl_permutationhash[mode][hashindex];
3729         r_glsl_permutationhash[mode][hashindex] = p;
3730         //if (hashdepth > 10)
3731         //      Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3732         return p;
3733 }
3734
3735 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3736 {
3737         char *shaderstring;
3738         if (!filename || !filename[0])
3739                 return NULL;
3740         if (!strcmp(filename, "glsl/default.glsl"))
3741         {
3742                 if (!glslshaderstring)
3743                 {
3744                         glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3745                         if (glslshaderstring)
3746                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
3747                         else
3748                                 glslshaderstring = (char *)builtinshaderstring;
3749                 }
3750                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3751                 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3752                 return shaderstring;
3753         }
3754         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3755         if (shaderstring)
3756         {
3757                 if (printfromdisknotice)
3758                         Con_DPrintf("from disk %s... ", filename);
3759                 return shaderstring;
3760         }
3761         return shaderstring;
3762 }
3763
3764 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3765 {
3766         int i;
3767         int sampler;
3768         shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3769         char *vertexstring, *geometrystring, *fragmentstring;
3770         char permutationname[256];
3771         int vertstrings_count = 0;
3772         int geomstrings_count = 0;
3773         int fragstrings_count = 0;
3774         const char *vertstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
3775         const char *geomstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
3776         const char *fragstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
3777
3778         if (p->compiled)
3779                 return;
3780         p->compiled = true;
3781         p->program = 0;
3782
3783         permutationname[0] = 0;
3784         vertexstring   = R_GLSL_GetText(modeinfo->vertexfilename, true);
3785         geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3786         fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3787
3788         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3789
3790         // the first pretext is which type of shader to compile as
3791         // (later these will all be bound together as a program object)
3792         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3793         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3794         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3795
3796         // the second pretext is the mode (for example a light source)
3797         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3798         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3799         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3800         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3801
3802         // now add all the permutation pretexts
3803         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3804         {
3805                 if (permutation & (1<<i))
3806                 {
3807                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3808                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3809                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3810                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3811                 }
3812                 else
3813                 {
3814                         // keep line numbers correct
3815                         vertstrings_list[vertstrings_count++] = "\n";
3816                         geomstrings_list[geomstrings_count++] = "\n";
3817                         fragstrings_list[fragstrings_count++] = "\n";
3818                 }
3819         }
3820
3821         // add static parms
3822         R_CompileShader_AddStaticParms(mode, permutation);
3823         memcpy((char *)(vertstrings_list + vertstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
3824         vertstrings_count += shaderstaticparms_count;
3825         memcpy((char *)(geomstrings_list + geomstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
3826         geomstrings_count += shaderstaticparms_count;
3827         memcpy((char *)(fragstrings_list + fragstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
3828         fragstrings_count += shaderstaticparms_count;
3829
3830         // now append the shader text itself
3831         vertstrings_list[vertstrings_count++] = vertexstring;
3832         geomstrings_list[geomstrings_count++] = geometrystring;
3833         fragstrings_list[fragstrings_count++] = fragmentstring;
3834
3835         // if any sources were NULL, clear the respective list
3836         if (!vertexstring)
3837                 vertstrings_count = 0;
3838         if (!geometrystring)
3839                 geomstrings_count = 0;
3840         if (!fragmentstring)
3841                 fragstrings_count = 0;
3842
3843         // compile the shader program
3844         if (vertstrings_count + geomstrings_count + fragstrings_count)
3845                 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3846         if (p->program)
3847         {
3848                 CHECKGLERROR
3849                 qglUseProgram(p->program);CHECKGLERROR
3850                 // look up all the uniform variable names we care about, so we don't
3851                 // have to look them up every time we set them
3852
3853                 p->loc_Texture_First              = qglGetUniformLocation(p->program, "Texture_First");
3854                 p->loc_Texture_Second             = qglGetUniformLocation(p->program, "Texture_Second");
3855                 p->loc_Texture_GammaRamps         = qglGetUniformLocation(p->program, "Texture_GammaRamps");
3856                 p->loc_Texture_Normal             = qglGetUniformLocation(p->program, "Texture_Normal");
3857                 p->loc_Texture_Color              = qglGetUniformLocation(p->program, "Texture_Color");
3858                 p->loc_Texture_Gloss              = qglGetUniformLocation(p->program, "Texture_Gloss");
3859                 p->loc_Texture_Glow               = qglGetUniformLocation(p->program, "Texture_Glow");
3860                 p->loc_Texture_SecondaryNormal    = qglGetUniformLocation(p->program, "Texture_SecondaryNormal");
3861                 p->loc_Texture_SecondaryColor     = qglGetUniformLocation(p->program, "Texture_SecondaryColor");
3862                 p->loc_Texture_SecondaryGloss     = qglGetUniformLocation(p->program, "Texture_SecondaryGloss");
3863                 p->loc_Texture_SecondaryGlow      = qglGetUniformLocation(p->program, "Texture_SecondaryGlow");
3864                 p->loc_Texture_Pants              = qglGetUniformLocation(p->program, "Texture_Pants");
3865                 p->loc_Texture_Shirt              = qglGetUniformLocation(p->program, "Texture_Shirt");
3866                 p->loc_Texture_FogHeightTexture   = qglGetUniformLocation(p->program, "Texture_FogHeightTexture");
3867                 p->loc_Texture_FogMask            = qglGetUniformLocation(p->program, "Texture_FogMask");
3868                 p->loc_Texture_Lightmap           = qglGetUniformLocation(p->program, "Texture_Lightmap");
3869                 p->loc_Texture_Deluxemap          = qglGetUniformLocation(p->program, "Texture_Deluxemap");
3870                 p->loc_Texture_Attenuation        = qglGetUniformLocation(p->program, "Texture_Attenuation");
3871                 p->loc_Texture_Cube               = qglGetUniformLocation(p->program, "Texture_Cube");
3872                 p->loc_Texture_Refraction         = qglGetUniformLocation(p->program, "Texture_Refraction");
3873                 p->loc_Texture_Reflection         = qglGetUniformLocation(p->program, "Texture_Reflection");
3874                 p->loc_Texture_ShadowMap2D        = qglGetUniformLocation(p->program, "Texture_ShadowMap2D");
3875                 p->loc_Texture_CubeProjection     = qglGetUniformLocation(p->program, "Texture_CubeProjection");
3876                 p->loc_Texture_ScreenDepth        = qglGetUniformLocation(p->program, "Texture_ScreenDepth");
3877                 p->loc_Texture_ScreenNormalMap    = qglGetUniformLocation(p->program, "Texture_ScreenNormalMap");
3878                 p->loc_Texture_ScreenDiffuse      = qglGetUniformLocation(p->program, "Texture_ScreenDiffuse");
3879                 p->loc_Texture_ScreenSpecular     = qglGetUniformLocation(p->program, "Texture_ScreenSpecular");
3880                 p->loc_Texture_ReflectMask        = qglGetUniformLocation(p->program, "Texture_ReflectMask");
3881                 p->loc_Texture_ReflectCube        = qglGetUniformLocation(p->program, "Texture_ReflectCube");
3882                 p->loc_Texture_BounceGrid         = qglGetUniformLocation(p->program, "Texture_BounceGrid");
3883                 p->loc_Alpha                      = qglGetUniformLocation(p->program, "Alpha");
3884                 p->loc_BloomBlur_Parameters       = qglGetUniformLocation(p->program, "BloomBlur_Parameters");
3885                 p->loc_ClientTime                 = qglGetUniformLocation(p->program, "ClientTime");
3886                 p->loc_Color_Ambient              = qglGetUniformLocation(p->program, "Color_Ambient");
3887                 p->loc_Color_Diffuse              = qglGetUniformLocation(p->program, "Color_Diffuse");
3888                 p->loc_Color_Specular             = qglGetUniformLocation(p->program, "Color_Specular");
3889                 p->loc_Color_Glow                 = qglGetUniformLocation(p->program, "Color_Glow");
3890                 p->loc_Color_Pants                = qglGetUniformLocation(p->program, "Color_Pants");
3891                 p->loc_Color_Shirt                = qglGetUniformLocation(p->program, "Color_Shirt");
3892                 p->loc_DeferredColor_Ambient      = qglGetUniformLocation(p->program, "DeferredColor_Ambient");
3893                 p->loc_DeferredColor_Diffuse      = qglGetUniformLocation(p->program, "DeferredColor_Diffuse");
3894                 p->loc_DeferredColor_Specular     = qglGetUniformLocation(p->program, "DeferredColor_Specular");
3895                 p->loc_DeferredMod_Diffuse        = qglGetUniformLocation(p->program, "DeferredMod_Diffuse");
3896                 p->loc_DeferredMod_Specular       = qglGetUniformLocation(p->program, "DeferredMod_Specular");
3897                 p->loc_DistortScaleRefractReflect = qglGetUniformLocation(p->program, "DistortScaleRefractReflect");
3898                 p->loc_EyePosition                = qglGetUniformLocation(p->program, "EyePosition");
3899                 p->loc_FogColor                   = qglGetUniformLocation(p->program, "FogColor");
3900                 p->loc_FogHeightFade              = qglGetUniformLocation(p->program, "FogHeightFade");
3901                 p->loc_FogPlane                   = qglGetUniformLocation(p->program, "FogPlane");
3902                 p->loc_FogPlaneViewDist           = qglGetUniformLocation(p->program, "FogPlaneViewDist");
3903                 p->loc_FogRangeRecip              = qglGetUniformLocation(p->program, "FogRangeRecip");
3904                 p->loc_LightColor                 = qglGetUniformLocation(p->program, "LightColor");
3905                 p->loc_LightDir                   = qglGetUniformLocation(p->program, "LightDir");
3906                 p->loc_LightPosition              = qglGetUniformLocation(p->program, "LightPosition");
3907                 p->loc_OffsetMapping_Scale        = qglGetUniformLocation(p->program, "OffsetMapping_Scale");
3908                 p->loc_PixelSize                  = qglGetUniformLocation(p->program, "PixelSize");
3909                 p->loc_ReflectColor               = qglGetUniformLocation(p->program, "ReflectColor");
3910                 p->loc_ReflectFactor              = qglGetUniformLocation(p->program, "ReflectFactor");
3911                 p->loc_ReflectOffset              = qglGetUniformLocation(p->program, "ReflectOffset");
3912                 p->loc_RefractColor               = qglGetUniformLocation(p->program, "RefractColor");
3913                 p->loc_Saturation                 = qglGetUniformLocation(p->program, "Saturation");
3914                 p->loc_ScreenCenterRefractReflect = qglGetUniformLocation(p->program, "ScreenCenterRefractReflect");
3915                 p->loc_ScreenScaleRefractReflect  = qglGetUniformLocation(p->program, "ScreenScaleRefractReflect");
3916                 p->loc_ScreenToDepth              = qglGetUniformLocation(p->program, "ScreenToDepth");
3917                 p->loc_ShadowMap_Parameters       = qglGetUniformLocation(p->program, "ShadowMap_Parameters");
3918                 p->loc_ShadowMap_TextureScale     = qglGetUniformLocation(p->program, "ShadowMap_TextureScale");
3919                 p->loc_SpecularPower              = qglGetUniformLocation(p->program, "SpecularPower");
3920                 p->loc_UserVec1                   = qglGetUniformLocation(p->program, "UserVec1");
3921                 p->loc_UserVec2                   = qglGetUniformLocation(p->program, "UserVec2");
3922                 p->loc_UserVec3                   = qglGetUniformLocation(p->program, "UserVec3");
3923                 p->loc_UserVec4                   = qglGetUniformLocation(p->program, "UserVec4");
3924                 p->loc_ViewTintColor              = qglGetUniformLocation(p->program, "ViewTintColor");
3925                 p->loc_ViewToLight                = qglGetUniformLocation(p->program, "ViewToLight");
3926                 p->loc_ModelToLight               = qglGetUniformLocation(p->program, "ModelToLight");
3927                 p->loc_TexMatrix                  = qglGetUniformLocation(p->program, "TexMatrix");
3928                 p->loc_BackgroundTexMatrix        = qglGetUniformLocation(p->program, "BackgroundTexMatrix");
3929                 p->loc_ModelViewMatrix            = qglGetUniformLocation(p->program, "ModelViewMatrix");
3930                 p->loc_ModelViewProjectionMatrix  = qglGetUniformLocation(p->program, "ModelViewProjectionMatrix");
3931                 p->loc_PixelToScreenTexCoord      = qglGetUniformLocation(p->program, "PixelToScreenTexCoord");
3932                 p->loc_ModelToReflectCube         = qglGetUniformLocation(p->program, "ModelToReflectCube");
3933                 p->loc_ShadowMapMatrix            = qglGetUniformLocation(p->program, "ShadowMapMatrix");
3934                 p->loc_BloomColorSubtract         = qglGetUniformLocation(p->program, "BloomColorSubtract");
3935                 p->loc_NormalmapScrollBlend       = qglGetUniformLocation(p->program, "NormalmapScrollBlend");
3936                 p->loc_BounceGridMatrix           = qglGetUniformLocation(p->program, "BounceGridMatrix");
3937                 p->loc_BounceGridIntensity        = qglGetUniformLocation(p->program, "BounceGridIntensity");
3938                 // initialize the samplers to refer to the texture units we use
3939                 p->tex_Texture_First = -1;
3940                 p->tex_Texture_Second = -1;
3941                 p->tex_Texture_GammaRamps = -1;
3942                 p->tex_Texture_Normal = -1;
3943                 p->tex_Texture_Color = -1;
3944                 p->tex_Texture_Gloss = -1;
3945                 p->tex_Texture_Glow = -1;
3946                 p->tex_Texture_SecondaryNormal = -1;
3947                 p->tex_Texture_SecondaryColor = -1;
3948                 p->tex_Texture_SecondaryGloss = -1;
3949                 p->tex_Texture_SecondaryGlow = -1;
3950                 p->tex_Texture_Pants = -1;
3951                 p->tex_Texture_Shirt = -1;
3952                 p->tex_Texture_FogHeightTexture = -1;
3953                 p->tex_Texture_FogMask = -1;
3954                 p->tex_Texture_Lightmap = -1;
3955                 p->tex_Texture_Deluxemap = -1;
3956                 p->tex_Texture_Attenuation = -1;
3957                 p->tex_Texture_Cube = -1;
3958                 p->tex_Texture_Refraction = -1;
3959                 p->tex_Texture_Reflection = -1;
3960                 p->tex_Texture_ShadowMap2D = -1;
3961                 p->tex_Texture_CubeProjection = -1;
3962                 p->tex_Texture_ScreenDepth = -1;
3963                 p->tex_Texture_ScreenNormalMap = -1;
3964                 p->tex_Texture_ScreenDiffuse = -1;
3965                 p->tex_Texture_ScreenSpecular = -1;
3966                 p->tex_Texture_ReflectMask = -1;
3967                 p->tex_Texture_ReflectCube = -1;
3968                 p->tex_Texture_BounceGrid = -1;
3969                 sampler = 0;
3970                 if (p->loc_Texture_First           >= 0) {p->tex_Texture_First            = sampler;qglUniform1i(p->loc_Texture_First           , sampler);sampler++;}
3971                 if (p->loc_Texture_Second          >= 0) {p->tex_Texture_Second           = sampler;qglUniform1i(p->loc_Texture_Second          , sampler);sampler++;}
3972                 if (p->loc_Texture_GammaRamps      >= 0) {p->tex_Texture_GammaRamps       = sampler;qglUniform1i(p->loc_Texture_GammaRamps      , sampler);sampler++;}
3973                 if (p->loc_Texture_Normal          >= 0) {p->tex_Texture_Normal           = sampler;qglUniform1i(p->loc_Texture_Normal          , sampler);sampler++;}
3974                 if (p->loc_Texture_Color           >= 0) {p->tex_Texture_Color            = sampler;qglUniform1i(p->loc_Texture_Color           , sampler);sampler++;}
3975                 if (p->loc_Texture_Gloss           >= 0) {p->tex_Texture_Gloss            = sampler;qglUniform1i(p->loc_Texture_Gloss           , sampler);sampler++;}
3976                 if (p->loc_Texture_Glow            >= 0) {p->tex_Texture_Glow             = sampler;qglUniform1i(p->loc_Texture_Glow            , sampler);sampler++;}
3977                 if (p->loc_Texture_SecondaryNormal >= 0) {p->tex_Texture_SecondaryNormal  = sampler;qglUniform1i(p->loc_Texture_SecondaryNormal , sampler);sampler++;}
3978                 if (p->loc_Texture_SecondaryColor  >= 0) {p->tex_Texture_SecondaryColor   = sampler;qglUniform1i(p->loc_Texture_SecondaryColor  , sampler);sampler++;}
3979                 if (p->loc_Texture_SecondaryGloss  >= 0) {p->tex_Texture_SecondaryGloss   = sampler;qglUniform1i(p->loc_Texture_SecondaryGloss  , sampler);sampler++;}
3980                 if (p->loc_Texture_SecondaryGlow   >= 0) {p->tex_Texture_SecondaryGlow    = sampler;qglUniform1i(p->loc_Texture_SecondaryGlow   , sampler);sampler++;}
3981                 if (p->loc_Texture_Pants           >= 0) {p->tex_Texture_Pants            = sampler;qglUniform1i(p->loc_Texture_Pants           , sampler);sampler++;}
3982                 if (p->loc_Texture_Shirt           >= 0) {p->tex_Texture_Shirt            = sampler;qglUniform1i(p->loc_Texture_Shirt           , sampler);sampler++;}
3983                 if (p->loc_Texture_FogHeightTexture>= 0) {p->tex_Texture_FogHeightTexture = sampler;qglUniform1i(p->loc_Texture_FogHeightTexture, sampler);sampler++;}
3984                 if (p->loc_Texture_FogMask         >= 0) {p->tex_Texture_FogMask          = sampler;qglUniform1i(p->loc_Texture_FogMask         , sampler);sampler++;}
3985                 if (p->loc_Texture_Lightmap        >= 0) {p->tex_Texture_Lightmap         = sampler;qglUniform1i(p->loc_Texture_Lightmap        , sampler);sampler++;}
3986                 if (p->loc_Texture_Deluxemap       >= 0) {p->tex_Texture_Deluxemap        = sampler;qglUniform1i(p->loc_Texture_Deluxemap       , sampler);sampler++;}
3987                 if (p->loc_Texture_Attenuation     >= 0) {p->tex_Texture_Attenuation      = sampler;qglUniform1i(p->loc_Texture_Attenuation     , sampler);sampler++;}
3988                 if (p->loc_Texture_Cube            >= 0) {p->tex_Texture_Cube             = sampler;qglUniform1i(p->loc_Texture_Cube            , sampler);sampler++;}
3989                 if (p->loc_Texture_Refraction      >= 0) {p->tex_Texture_Refraction       = sampler;qglUniform1i(p->loc_Texture_Refraction      , sampler);sampler++;}
3990                 if (p->loc_Texture_Reflection      >= 0) {p->tex_Texture_Reflection       = sampler;qglUniform1i(p->loc_Texture_Reflection      , sampler);sampler++;}
3991                 if (p->loc_Texture_ShadowMap2D     >= 0) {p->tex_Texture_ShadowMap2D      = sampler;qglUniform1i(p->loc_Texture_ShadowMap2D     , sampler);sampler++;}
3992                 if (p->loc_Texture_CubeProjection  >= 0) {p->tex_Texture_CubeProjection   = sampler;qglUniform1i(p->loc_Texture_CubeProjection  , sampler);sampler++;}
3993                 if (p->loc_Texture_ScreenDepth     >= 0) {p->tex_Texture_ScreenDepth      = sampler;qglUniform1i(p->loc_Texture_ScreenDepth     , sampler);sampler++;}
3994                 if (p->loc_Texture_ScreenNormalMap >= 0) {p->tex_Texture_ScreenNormalMap  = sampler;qglUniform1i(p->loc_Texture_ScreenNormalMap , sampler);sampler++;}
3995                 if (p->loc_Texture_ScreenDiffuse   >= 0) {p->tex_Texture_ScreenDiffuse    = sampler;qglUniform1i(p->loc_Texture_ScreenDiffuse   , sampler);sampler++;}
3996                 if (p->loc_Texture_ScreenSpecular  >= 0) {p->tex_Texture_ScreenSpecular   = sampler;qglUniform1i(p->loc_Texture_ScreenSpecular  , sampler);sampler++;}
3997                 if (p->loc_Texture_ReflectMask     >= 0) {p->tex_Texture_ReflectMask      = sampler;qglUniform1i(p->loc_Texture_ReflectMask     , sampler);sampler++;}
3998                 if (p->loc_Texture_ReflectCube     >= 0) {p->tex_Texture_ReflectCube      = sampler;qglUniform1i(p->loc_Texture_ReflectCube     , sampler);sampler++;}
3999                 if (p->loc_Texture_BounceGrid      >= 0) {p->tex_Texture_BounceGrid       = sampler;qglUniform1i(p->loc_Texture_BounceGrid      , sampler);sampler++;}
4000                 CHECKGLERROR
4001                 Con_DPrintf("^5GLSL shader %s compiled (%i textures).\n", permutationname, sampler);
4002         }
4003         else
4004                 Con_Printf("^1GLSL shader %s failed!  some features may not work properly.\n", permutationname);
4005
4006         // free the strings
4007         if (vertexstring)
4008                 Mem_Free(vertexstring);
4009         if (geometrystring)
4010                 Mem_Free(geometrystring);
4011         if (fragmentstring)
4012                 Mem_Free(fragmentstring);
4013 }
4014
4015 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
4016 {
4017         r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
4018         if (r_glsl_permutation != perm)
4019         {
4020                 r_glsl_permutation = perm;
4021                 if (!r_glsl_permutation->program)
4022                 {
4023                         if (!r_glsl_permutation->compiled)
4024                                 R_GLSL_CompilePermutation(perm, mode, permutation);
4025                         if (!r_glsl_permutation->program)
4026                         {
4027                                 // remove features until we find a valid permutation
4028                                 int i;
4029                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4030                                 {
4031                                         // reduce i more quickly whenever it would not remove any bits
4032                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4033                                         if (!(permutation & j))
4034                                                 continue;
4035                                         permutation -= j;
4036                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
4037                                         if (!r_glsl_permutation->compiled)
4038                                                 R_GLSL_CompilePermutation(perm, mode, permutation);
4039                                         if (r_glsl_permutation->program)
4040                                                 break;
4041                                 }
4042                                 if (i >= SHADERPERMUTATION_COUNT)
4043                                 {
4044                                         //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4045                                         r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
4046                                         qglUseProgram(0);CHECKGLERROR
4047                                         return; // no bit left to clear, entire mode is broken
4048                                 }
4049                         }
4050                 }
4051                 CHECKGLERROR
4052                 qglUseProgram(r_glsl_permutation->program);CHECKGLERROR
4053         }
4054         if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
4055         if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
4056         if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1f(r_glsl_permutation->loc_ClientTime, cl.time);
4057 }
4058
4059 #ifdef SUPPORTD3D
4060
4061 #ifdef SUPPORTD3D
4062 #include <d3d9.h>
4063 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
4064 extern D3DCAPS9 vid_d3d9caps;
4065 #endif
4066
4067 struct r_hlsl_permutation_s;
4068 typedef struct r_hlsl_permutation_s
4069 {
4070         /// hash lookup data
4071         struct r_hlsl_permutation_s *hashnext;
4072         unsigned int mode;
4073         unsigned int permutation;
4074
4075         /// indicates if we have tried compiling this permutation already
4076         qboolean compiled;
4077         /// NULL if compilation failed
4078         IDirect3DVertexShader9 *vertexshader;
4079         IDirect3DPixelShader9 *pixelshader;
4080 }
4081 r_hlsl_permutation_t;
4082
4083 typedef enum D3DVSREGISTER_e
4084 {
4085         D3DVSREGISTER_TexMatrix = 0, // float4x4
4086         D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
4087         D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
4088         D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
4089         D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
4090         D3DVSREGISTER_ModelToLight = 20, // float4x4
4091         D3DVSREGISTER_EyePosition = 24,
4092         D3DVSREGISTER_FogPlane = 25,
4093         D3DVSREGISTER_LightDir = 26,
4094         D3DVSREGISTER_LightPosition = 27,
4095 }
4096 D3DVSREGISTER_t;
4097
4098 typedef enum D3DPSREGISTER_e
4099 {
4100         D3DPSREGISTER_Alpha = 0,
4101         D3DPSREGISTER_BloomBlur_Parameters = 1,
4102         D3DPSREGISTER_ClientTime = 2,
4103         D3DPSREGISTER_Color_Ambient = 3,
4104         D3DPSREGISTER_Color_Diffuse = 4,
4105         D3DPSREGISTER_Color_Specular = 5,
4106         D3DPSREGISTER_Color_Glow = 6,
4107         D3DPSREGISTER_Color_Pants = 7,
4108         D3DPSREGISTER_Color_Shirt = 8,
4109         D3DPSREGISTER_DeferredColor_Ambient = 9,
4110         D3DPSREGISTER_DeferredColor_Diffuse = 10,
4111         D3DPSREGISTER_DeferredColor_Specular = 11,
4112         D3DPSREGISTER_DeferredMod_Diffuse = 12,
4113         D3DPSREGISTER_DeferredMod_Specular = 13,
4114         D3DPSREGISTER_DistortScaleRefractReflect = 14,
4115         D3DPSREGISTER_EyePosition = 15, // unused
4116         D3DPSREGISTER_FogColor = 16,
4117         D3DPSREGISTER_FogHeightFade = 17,
4118         D3DPSREGISTER_FogPlane = 18,
4119         D3DPSREGISTER_FogPlaneViewDist = 19,
4120         D3DPSREGISTER_FogRangeRecip = 20,
4121         D3DPSREGISTER_LightColor = 21,
4122         D3DPSREGISTER_LightDir = 22, // unused
4123         D3DPSREGISTER_LightPosition = 23,
4124         D3DPSREGISTER_OffsetMapping_Scale = 24,
4125         D3DPSREGISTER_PixelSize = 25,
4126         D3DPSREGISTER_ReflectColor = 26,
4127         D3DPSREGISTER_ReflectFactor = 27,
4128         D3DPSREGISTER_ReflectOffset = 28,
4129         D3DPSREGISTER_RefractColor = 29,
4130         D3DPSREGISTER_Saturation = 30,
4131         D3DPSREGISTER_ScreenCenterRefractReflect = 31,
4132         D3DPSREGISTER_ScreenScaleRefractReflect = 32,
4133         D3DPSREGISTER_ScreenToDepth = 33,
4134         D3DPSREGISTER_ShadowMap_Parameters = 34,
4135         D3DPSREGISTER_ShadowMap_TextureScale = 35,
4136         D3DPSREGISTER_SpecularPower = 36,
4137         D3DPSREGISTER_UserVec1 = 37,
4138         D3DPSREGISTER_UserVec2 = 38,
4139         D3DPSREGISTER_UserVec3 = 39,
4140         D3DPSREGISTER_UserVec4 = 40,
4141         D3DPSREGISTER_ViewTintColor = 41,
4142         D3DPSREGISTER_PixelToScreenTexCoord = 42,
4143         D3DPSREGISTER_BloomColorSubtract = 43,
4144         D3DPSREGISTER_ViewToLight = 44, // float4x4
4145         D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
4146         D3DPSREGISTER_NormalmapScrollBlend = 52,
4147         // next at 53
4148 }
4149 D3DPSREGISTER_t;
4150
4151 /// information about each possible shader permutation
4152 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4153 /// currently selected permutation
4154 r_hlsl_permutation_t *r_hlsl_permutation;
4155 /// storage for permutations linked in the hash table
4156 memexpandablearray_t r_hlsl_permutationarray;
4157
4158 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
4159 {
4160         //unsigned int hashdepth = 0;
4161         unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4162         r_hlsl_permutation_t *p;
4163         for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
4164         {
4165                 if (p->mode == mode && p->permutation == permutation)
4166                 {
4167                         //if (hashdepth > 10)
4168                         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4169                         return p;
4170                 }
4171                 //hashdepth++;
4172         }
4173         p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
4174         p->mode = mode;
4175         p->permutation = permutation;
4176         p->hashnext = r_hlsl_permutationhash[mode][hashindex];
4177         r_hlsl_permutationhash[mode][hashindex] = p;
4178         //if (hashdepth > 10)
4179         //      Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4180         return p;
4181 }
4182
4183 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
4184 {
4185         char *shaderstring;
4186         if (!filename || !filename[0])
4187                 return NULL;
4188         if (!strcmp(filename, "hlsl/default.hlsl"))
4189         {
4190                 if (!hlslshaderstring)
4191                 {
4192                         hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4193                         if (hlslshaderstring)
4194                                 Con_DPrintf("Loading shaders from file %s...\n", filename);
4195                         else
4196                                 hlslshaderstring = (char *)builtinhlslshaderstring;
4197                 }
4198                 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
4199                 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
4200                 return shaderstring;
4201         }
4202         shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4203         if (shaderstring)
4204         {
4205                 if (printfromdisknotice)
4206                         Con_DPrintf("from disk %s... ", filename);
4207                 return shaderstring;
4208         }
4209         return shaderstring;
4210 }
4211
4212 #include <d3dx9.h>
4213 //#include <d3dx9shader.h>
4214 //#include <d3dx9mesh.h>
4215
4216 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4217 {
4218         DWORD *vsbin = NULL;
4219         DWORD *psbin = NULL;
4220         fs_offset_t vsbinsize;
4221         fs_offset_t psbinsize;
4222 //      IDirect3DVertexShader9 *vs = NULL;
4223 //      IDirect3DPixelShader9 *ps = NULL;
4224         ID3DXBuffer *vslog = NULL;
4225         ID3DXBuffer *vsbuffer = NULL;
4226         ID3DXConstantTable *vsconstanttable = NULL;
4227         ID3DXBuffer *pslog = NULL;
4228         ID3DXBuffer *psbuffer = NULL;
4229         ID3DXConstantTable *psconstanttable = NULL;
4230         int vsresult = 0;
4231         int psresult = 0;
4232         char temp[MAX_INPUTLINE];
4233         const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
4234         qboolean debugshader = gl_paranoid.integer != 0;
4235         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4236         if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4237         if (!debugshader)
4238         {
4239                 vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
4240                 psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
4241         }
4242         if ((!vsbin && vertstring) || (!psbin && fragstring))
4243         {
4244                 const char* dllnames_d3dx9 [] =
4245                 {
4246                         "d3dx9_43.dll",
4247                         "d3dx9_42.dll",
4248                         "d3dx9_41.dll",
4249                         "d3dx9_40.dll",
4250                         "d3dx9_39.dll",
4251                         "d3dx9_38.dll",
4252                         "d3dx9_37.dll",
4253                         "d3dx9_36.dll",
4254                         "d3dx9_35.dll",
4255                         "d3dx9_34.dll",
4256                         "d3dx9_33.dll",
4257                         "d3dx9_32.dll",
4258                         "d3dx9_31.dll",
4259                         "d3dx9_30.dll",
4260                         "d3dx9_29.dll",
4261                         "d3dx9_28.dll",
4262                         "d3dx9_27.dll",
4263                         "d3dx9_26.dll",
4264                         "d3dx9_25.dll",
4265                         "d3dx9_24.dll",
4266                         NULL
4267                 };
4268                 dllhandle_t d3dx9_dll = NULL;
4269                 HRESULT (WINAPI *qD3DXCompileShaderFromFileA)(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
4270                 HRESULT (WINAPI *qD3DXPreprocessShader)(LPCSTR pSrcData, UINT SrcDataSize, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPD3DXBUFFER* ppShaderText, LPD3DXBUFFER* ppErrorMsgs);
4271                 HRESULT (WINAPI *qD3DXCompileShader)(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
4272                 dllfunction_t d3dx9_dllfuncs[] =
4273                 {
4274                         {"D3DXCompileShaderFromFileA",  (void **) &qD3DXCompileShaderFromFileA},
4275                         {"D3DXPreprocessShader",                (void **) &qD3DXPreprocessShader},
4276                         {"D3DXCompileShader",                   (void **) &qD3DXCompileShader},
4277                         {NULL, NULL}
4278                 };
4279                 if (Sys_LoadLibrary(dllnames_d3dx9, &d3dx9_dll, d3dx9_dllfuncs))
4280                 {
4281                         DWORD shaderflags = 0;
4282                         if (debugshader)
4283                                 shaderflags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION;
4284                         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4285                         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4286                         if (vertstring && vertstring[0])
4287                         {
4288                                 if (debugshader)
4289                                 {
4290 //                                      vsresult = qD3DXPreprocessShader(vertstring, strlen(vertstring), NULL, NULL, &vsbuffer, &vslog);
4291 //                                      FS_WriteFile(va("%s_vs.fx", cachename), vsbuffer->GetBufferPointer(), vsbuffer->GetBufferSize());
4292                                         FS_WriteFile(va("%s_vs.fx", cachename), vertstring, strlen(vertstring));
4293                                         vsresult = qD3DXCompileShaderFromFileA(va("%s/%s_vs.fx", fs_gamedir, cachename), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
4294                                 }
4295                                 else
4296                                         vsresult = qD3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
4297                                 if (vsbuffer)
4298                                 {
4299                                         vsbinsize = vsbuffer->GetBufferSize();
4300                                         vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
4301                                         memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
4302                                         vsbuffer->Release();
4303                                 }
4304                                 if (vslog)
4305                                 {
4306                                         strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
4307                                         Con_Printf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
4308                                         vslog->Release();
4309                                 }
4310                         }
4311                         if (fragstring && fragstring[0])
4312                         {
4313                                 if (debugshader)
4314                                 {
4315 //                                      psresult = qD3DXPreprocessShader(fragstring, strlen(fragstring), NULL, NULL, &psbuffer, &pslog);
4316 //                                      FS_WriteFile(va("%s_ps.fx", cachename), psbuffer->GetBufferPointer(), psbuffer->GetBufferSize());
4317                                         FS_WriteFile(va("%s_ps.fx", cachename), fragstring, strlen(fragstring));
4318                                         psresult = qD3DXCompileShaderFromFileA(va("%s/%s_ps.fx", fs_gamedir, cachename), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
4319                                 }
4320                                 else
4321                                         psresult = qD3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
4322                                 if (psbuffer)
4323                                 {
4324                                         psbinsize = psbuffer->GetBufferSize();
4325                                         psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
4326                                         memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
4327                                         psbuffer->Release();
4328                                 }
4329                                 if (pslog)
4330                                 {
4331                                         strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
4332                                         Con_Printf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
4333                                         pslog->Release();
4334                                 }
4335                         }
4336                         Sys_UnloadLibrary(&d3dx9_dll);
4337                 }
4338                 else
4339                         Con_Printf("Unable to compile shader - D3DXCompileShader function not found\n");
4340         }
4341         if (vsbin && psbin)
4342         {
4343                 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
4344                 if (FAILED(vsresult))
4345                         Con_Printf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
4346                 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
4347                 if (FAILED(psresult))
4348                         Con_Printf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
4349         }
4350         // free the shader data
4351         vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4352         psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4353 }
4354
4355 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
4356 {
4357         int i;
4358         shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
4359         int vertstring_length = 0;
4360         int geomstring_length = 0;
4361         int fragstring_length = 0;
4362         char *t;
4363         char *vertexstring, *geometrystring, *fragmentstring;
4364         char *vertstring, *geomstring, *fragstring;
4365         char permutationname[256];
4366         char cachename[256];
4367         int vertstrings_count = 0;
4368         int geomstrings_count = 0;
4369         int fragstrings_count = 0;
4370         const char *vertstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
4371         const char *geomstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
4372         const char *fragstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
4373
4374         if (p->compiled)
4375                 return;
4376         p->compiled = true;
4377         p->vertexshader = NULL;
4378         p->pixelshader = NULL;
4379
4380         permutationname[0] = 0;
4381         cachename[0] = 0;
4382         vertexstring   = R_HLSL_GetText(modeinfo->vertexfilename, true);
4383         geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
4384         fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
4385
4386         strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4387         strlcat(cachename, "hlsl/", sizeof(cachename));
4388
4389         // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
4390         vertstrings_count = 0;
4391         geomstrings_count = 0;
4392         fragstrings_count = 0;
4393         vertstrings_list[vertstrings_count++] = "#define HLSL\n";
4394         geomstrings_list[geomstrings_count++] = "#define HLSL\n";
4395         fragstrings_list[fragstrings_count++] = "#define HLSL\n";
4396
4397         // the first pretext is which type of shader to compile as
4398         // (later these will all be bound together as a program object)
4399         vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4400         geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4401         fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4402
4403         // the second pretext is the mode (for example a light source)
4404         vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4405         geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4406         fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4407         strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4408         strlcat(cachename, modeinfo->name, sizeof(cachename));
4409
4410         // now add all the permutation pretexts
4411         for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4412         {
4413                 if (permutation & (1<<i))
4414                 {
4415                         vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4416                         geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4417                         fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4418                         strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4419                         strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4420                 }
4421                 else
4422                 {
4423                         // keep line numbers correct
4424                         vertstrings_list[vertstrings_count++] = "\n";
4425                         geomstrings_list[geomstrings_count++] = "\n";
4426                         fragstrings_list[fragstrings_count++] = "\n";
4427                 }
4428         }
4429
4430         // add static parms
4431         R_CompileShader_AddStaticParms(mode, permutation);
4432         memcpy(vertstrings_list + vertstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
4433         vertstrings_count += shaderstaticparms_count;
4434         memcpy(geomstrings_list + geomstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
4435         geomstrings_count += shaderstaticparms_count;
4436         memcpy(fragstrings_list + fragstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
4437         fragstrings_count += shaderstaticparms_count;
4438
4439         // replace spaces in the cachename with _ characters
4440         for (i = 0;cachename[i];i++)
4441                 if (cachename[i] == ' ')
4442                         cachename[i] = '_';
4443
4444         // now append the shader text itself
4445         vertstrings_list[vertstrings_count++] = vertexstring;
4446         geomstrings_list[geomstrings_count++] = geometrystring;
4447         fragstrings_list[fragstrings_count++] = fragmentstring;
4448
4449         // if any sources were NULL, clear the respective list
4450         if (!vertexstring)
4451                 vertstrings_count = 0;
4452         if (!geometrystring)
4453                 geomstrings_count = 0;
4454         if (!fragmentstring)
4455                 fragstrings_count = 0;
4456
4457         vertstring_length = 0;
4458         for (i = 0;i < vertstrings_count;i++)
4459                 vertstring_length += strlen(vertstrings_list[i]);
4460         vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
4461         for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4462                 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4463
4464         geomstring_length = 0;
4465         for (i = 0;i < geomstrings_count;i++)
4466                 geomstring_length += strlen(geomstrings_list[i]);
4467         geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
4468         for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4469                 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4470
4471         fragstring_length = 0;
4472         for (i = 0;i < fragstrings_count;i++)
4473                 fragstring_length += strlen(fragstrings_list[i]);
4474         fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
4475         for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4476                 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4477
4478         // try to load the cached shader, or generate one
4479         R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
4480
4481         if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
4482                 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
4483         else
4484                 Con_Printf("^1HLSL shader %s failed!  some features may not work properly.\n", permutationname);
4485
4486         // free the strings
4487         if (vertstring)
4488                 Mem_Free(vertstring);
4489         if (geomstring)
4490                 Mem_Free(geomstring);
4491         if (fragstring)
4492                 Mem_Free(fragstring);
4493         if (vertexstring)
4494                 Mem_Free(vertexstring);
4495         if (geometrystring)
4496                 Mem_Free(geometrystring);
4497         if (fragmentstring)
4498                 Mem_Free(fragmentstring);
4499 }
4500
4501 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
4502 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
4503 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4504 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4505 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4506 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4507
4508 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
4509 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
4510 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4511 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4512 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4513 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4514
4515 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
4516 {
4517         r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
4518         if (r_hlsl_permutation != perm)
4519         {
4520                 r_hlsl_permutation = perm;
4521                 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4522                 {
4523                         if (!r_hlsl_permutation->compiled)
4524                                 R_HLSL_CompilePermutation(perm, mode, permutation);
4525                         if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4526                         {
4527                                 // remove features until we find a valid permutation
4528                                 int i;
4529                                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4530                                 {
4531                                         // reduce i more quickly whenever it would not remove any bits
4532                                         int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4533                                         if (!(permutation & j))
4534                                                 continue;
4535                                         permutation -= j;
4536                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4537                                         if (!r_hlsl_permutation->compiled)
4538                                                 R_HLSL_CompilePermutation(perm, mode, permutation);
4539                                         if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
4540                                                 break;
4541                                 }
4542                                 if (i >= SHADERPERMUTATION_COUNT)
4543                                 {
4544                                         //Con_Printf("Could not find a working HLSL shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4545                                         r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4546                                         return; // no bit left to clear, entire mode is broken
4547                                 }
4548                         }
4549                 }
4550                 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
4551                 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
4552         }
4553         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
4554         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
4555         hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
4556 }
4557 #endif
4558
4559 void R_SetupShader_SetPermutationSoft(unsigned int mode, unsigned int permutation)
4560 {
4561         DPSOFTRAST_SetShader(mode, permutation);
4562         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
4563         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
4564         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ClientTime, cl.time);
4565 }
4566
4567 void R_GLSL_Restart_f(void)
4568 {
4569         unsigned int i, limit;
4570         if (glslshaderstring && glslshaderstring != builtinshaderstring)
4571                 Mem_Free(glslshaderstring);
4572         glslshaderstring = NULL;
4573         if (hlslshaderstring && hlslshaderstring != builtinhlslshaderstring)
4574                 Mem_Free(hlslshaderstring);
4575         hlslshaderstring = NULL;
4576         switch(vid.renderpath)
4577         {
4578         case RENDERPATH_D3D9:
4579 #ifdef SUPPORTD3D
4580                 {
4581                         r_hlsl_permutation_t *p;
4582                         r_hlsl_permutation = NULL;
4583                         limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
4584                         for (i = 0;i < limit;i++)
4585                         {
4586                                 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
4587                                 {
4588                                         if (p->vertexshader)
4589                                                 IDirect3DVertexShader9_Release(p->vertexshader);
4590                                         if (p->pixelshader)
4591                                                 IDirect3DPixelShader9_Release(p->pixelshader);
4592                                         Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
4593                                 }
4594                         }
4595                         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
4596                 }
4597 #endif
4598                 break;
4599         case RENDERPATH_D3D10:
4600                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4601                 break;
4602         case RENDERPATH_D3D11:
4603                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4604                 break;
4605         case RENDERPATH_GL20:
4606         case RENDERPATH_GLES2:
4607                 {
4608                         r_glsl_permutation_t *p;
4609                         r_glsl_permutation = NULL;
4610                         limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4611                         for (i = 0;i < limit;i++)
4612                         {
4613                                 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4614                                 {
4615                                         GL_Backend_FreeProgram(p->program);
4616                                         Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4617                                 }
4618                         }
4619                         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4620                 }
4621                 break;
4622         case RENDERPATH_GL13:
4623         case RENDERPATH_GL11:
4624                 break;
4625         case RENDERPATH_SOFT:
4626                 break;
4627         }
4628 }
4629
4630 void R_GLSL_DumpShader_f(void)
4631 {
4632         int i;
4633         qfile_t *file;
4634
4635         file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4636         if (file)
4637         {
4638                 FS_Print(file, "/* The engine may define the following macros:\n");
4639                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4640                 for (i = 0;i < SHADERMODE_COUNT;i++)
4641                         FS_Print(file, glslshadermodeinfo[i].pretext);
4642                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4643                         FS_Print(file, shaderpermutationinfo[i].pretext);
4644                 FS_Print(file, "*/\n");
4645                 FS_Print(file, builtinshaderstring);
4646                 FS_Close(file);
4647                 Con_Printf("glsl/default.glsl written\n");
4648         }
4649         else
4650                 Con_Printf("failed to write to glsl/default.glsl\n");
4651
4652         file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
4653         if (file)
4654         {
4655                 FS_Print(file, "/* The engine may define the following macros:\n");
4656                 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4657                 for (i = 0;i < SHADERMODE_COUNT;i++)
4658                         FS_Print(file, hlslshadermodeinfo[i].pretext);
4659                 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4660                         FS_Print(file, shaderpermutationinfo[i].pretext);
4661                 FS_Print(file, "*/\n");
4662                 FS_Print(file, builtinhlslshaderstring);
4663                 FS_Close(file);
4664                 Con_Printf("hlsl/default.hlsl written\n");
4665         }
4666         else
4667                 Con_Printf("failed to write to hlsl/default.hlsl\n");
4668 }
4669
4670 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4671 {
4672         if (!second)
4673                 texturemode = GL_MODULATE;
4674         switch (vid.renderpath)
4675         {
4676         case RENDERPATH_D3D9:
4677 #ifdef SUPPORTD3D
4678                 R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, SHADERPERMUTATION_VIEWTINT | (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4679                 R_Mesh_TexBind(GL20TU_FIRST , first );
4680                 R_Mesh_TexBind(GL20TU_SECOND, second);
4681 #endif
4682                 break;
4683         case RENDERPATH_D3D10:
4684                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4685                 break;
4686         case RENDERPATH_D3D11:
4687                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4688                 break;
4689         case RENDERPATH_GL20:
4690         case RENDERPATH_GLES2:
4691                 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, SHADERPERMUTATION_VIEWTINT | (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4692                 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , first );
4693                 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second, second);
4694                 break;
4695         case RENDERPATH_GL13:
4696                 R_Mesh_TexBind(0, first );
4697                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4698                 R_Mesh_TexBind(1, second);
4699                 if (second)
4700                         R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4701                 break;
4702         case RENDERPATH_GL11:
4703                 R_Mesh_TexBind(0, first );
4704                 break;
4705         case RENDERPATH_SOFT:
4706                 R_SetupShader_SetPermutationSoft(SHADERMODE_GENERIC, SHADERPERMUTATION_VIEWTINT | (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4707                 R_Mesh_TexBind(GL20TU_FIRST , first );
4708                 R_Mesh_TexBind(GL20TU_SECOND, second);
4709                 break;
4710         }
4711 }
4712
4713 void R_SetupShader_DepthOrShadow(void)
4714 {
4715         switch (vid.renderpath)
4716         {
4717         case RENDERPATH_D3D9:
4718 #ifdef SUPPORTD3D
4719                 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4720 #endif
4721                 break;
4722         case RENDERPATH_D3D10:
4723                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4724                 break;
4725         case RENDERPATH_D3D11:
4726                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4727                 break;
4728         case RENDERPATH_GL20:
4729         case RENDERPATH_GLES2:
4730                 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4731                 break;
4732         case RENDERPATH_GL13:
4733                 R_Mesh_TexBind(0, 0);
4734                 R_Mesh_TexBind(1, 0);
4735                 break;
4736         case RENDERPATH_GL11:
4737                 R_Mesh_TexBind(0, 0);
4738                 break;
4739         case RENDERPATH_SOFT:
4740                 R_SetupShader_SetPermutationSoft(SHADERMODE_DEPTH_OR_SHADOW, 0);
4741                 break;
4742         }
4743 }
4744
4745 void R_SetupShader_ShowDepth(void)
4746 {
4747         switch (vid.renderpath)
4748         {
4749         case RENDERPATH_D3D9:
4750 #ifdef SUPPORTHLSL
4751                 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, 0);
4752 #endif
4753                 break;
4754         case RENDERPATH_D3D10:
4755                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4756                 break;
4757         case RENDERPATH_D3D11:
4758                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4759                 break;
4760         case RENDERPATH_GL20:
4761         case RENDERPATH_GLES2:
4762                 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4763                 break;
4764         case RENDERPATH_GL13:
4765                 break;
4766         case RENDERPATH_GL11:
4767                 break;
4768         case RENDERPATH_SOFT:
4769                 R_SetupShader_SetPermutationSoft(SHADERMODE_SHOWDEPTH, 0);
4770                 break;
4771         }
4772 }
4773
4774 extern qboolean r_shadow_usingdeferredprepass;
4775 extern cvar_t r_shadow_deferred_8bitrange;
4776 extern rtexture_t *r_shadow_attenuationgradienttexture;
4777 extern rtexture_t *r_shadow_attenuation2dtexture;
4778 extern rtexture_t *r_shadow_attenuation3dtexture;
4779 extern qboolean r_shadow_usingshadowmap2d;
4780 extern qboolean r_shadow_usingshadowmaportho;
4781 extern float r_shadow_shadowmap_texturescale[2];
4782 extern float r_shadow_shadowmap_parameters[4];
4783 extern qboolean r_shadow_shadowmapvsdct;
4784 extern qboolean r_shadow_shadowmapsampler;
4785 extern int r_shadow_shadowmappcf;
4786 extern rtexture_t *r_shadow_shadowmap2dtexture;
4787 extern rtexture_t *r_shadow_shadowmap2dcolortexture;
4788 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4789 extern matrix4x4_t r_shadow_shadowmapmatrix;
4790 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4791 extern int r_shadow_prepass_width;
4792 extern int r_shadow_prepass_height;
4793 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4794 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4795 extern rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
4796 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4797 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4798 static qboolean R_BlendFuncAllowsColormod(int src, int dst)
4799 {
4800         // a blendfunc allows colormod if:
4801         // a) it can never keep the destination pixel invariant, or
4802         // b) it can keep the destination pixel invariant, and still can do so if colormodded
4803         // this is to prevent unintended side effects from colormod
4804
4805         // in formulas:
4806         // IF there is a (s, sa) for which for all (d, da),
4807         //   s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4808         // THEN, for this (s, sa) and all (colormod, d, da):
4809         //   s*colormod * src(s*colormod, d, sa, da) + d * dst(s*colormod, d, sa, da) == d
4810         // OBVIOUSLY, this means that
4811         //   s*colormod * src(s*colormod, d, sa, da) = 0
4812         //   dst(s*colormod, d, sa, da)              = 1
4813
4814         // note: not caring about GL_SRC_ALPHA_SATURATE and following here, these are unused in DP code
4815
4816         // main condition to leave dst color invariant:
4817         //   s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4818         //   src == GL_ZERO:
4819         //     s * 0 + d * dst(s, d, sa, da) == d
4820         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4821         //       => colormod is a problem for GL_SRC_COLOR only
4822         //   src == GL_ONE:
4823         //     s + d * dst(s, d, sa, da) == d
4824         //       => s == 0
4825         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4826         //       => colormod is never problematic for these
4827         //   src == GL_SRC_COLOR:
4828         //     s*s + d * dst(s, d, sa, da) == d
4829         //       => s == 0
4830         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4831         //       => colormod is never problematic for these
4832         //   src == GL_ONE_MINUS_SRC_COLOR:
4833         //     s*(1-s) + d * dst(s, d, sa, da) == d
4834         //       => s == 0 or s == 1
4835         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4836         //       => colormod is a problem for GL_SRC_COLOR only
4837         //   src == GL_DST_COLOR
4838         //     s*d + d * dst(s, d, sa, da) == d
4839         //       => s == 1
4840         //       => dst == GL_ZERO/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4841         //       => colormod is always a problem
4842         //     or
4843         //       => s == 0
4844         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4845         //       => colormod is never problematic for these
4846         //       => BUT, we do not know s! We must assume it is problematic
4847         //       then... except in GL_ONE case, where we know all invariant
4848         //       cases are fine
4849         //   src == GL_ONE_MINUS_DST_COLOR
4850         //     s*(1-d) + d * dst(s, d, sa, da) == d
4851         //       => s == 0 (1-d is impossible to handle for our desired result)
4852         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4853         //       => colormod is never problematic for these
4854         //   src == GL_SRC_ALPHA
4855         //     s*sa + d * dst(s, d, sa, da) == d
4856         //       => s == 0, or sa == 0
4857         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4858         //       => colormod breaks in the case GL_SRC_COLOR only
4859         //   src == GL_ONE_MINUS_SRC_ALPHA
4860         //     s*(1-sa) + d * dst(s, d, sa, da) == d
4861         //       => s == 0, or sa == 1
4862         //       => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4863         //       => colormod breaks in the case GL_SRC_COLOR only
4864         //   src == GL_DST_ALPHA
4865         //     s*da + d * dst(s, d, sa, da) == d
4866         //       => s == 0
4867         //       => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4868         //       => colormod is never problematic for these
4869
4870         switch(src)
4871         {
4872                 case GL_ZERO:
4873                 case GL_ONE_MINUS_SRC_COLOR:
4874                 case GL_SRC_ALPHA:
4875                 case GL_ONE_MINUS_SRC_ALPHA:
4876                         if(dst == GL_SRC_COLOR)
4877                                 return false;
4878                         return true;
4879                 case GL_ONE:
4880                 case GL_SRC_COLOR:
4881                 case GL_ONE_MINUS_DST_COLOR:
4882                 case GL_DST_ALPHA:
4883                 case GL_ONE_MINUS_DST_ALPHA:
4884                         return true;
4885                 case GL_DST_COLOR:
4886                         if(dst == GL_ONE)
4887                                 return true;
4888                         return false;
4889                 default:
4890                         return false;
4891         }
4892 }
4893 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane)
4894 {
4895         // select a permutation of the lighting shader appropriate to this
4896         // combination of texture, entity, light source, and fogging, only use the
4897         // minimum features necessary to avoid wasting rendering time in the
4898         // fragment shader on features that are not being used
4899         unsigned int permutation = 0;
4900         unsigned int mode = 0;
4901         qboolean allow_colormod;
4902         static float dummy_colormod[3] = {1, 1, 1};
4903         float *colormod = rsurface.colormod;
4904         float m16f[16];
4905         matrix4x4_t tempmatrix;
4906         r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
4907         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4908                 permutation |= SHADERPERMUTATION_ALPHAKILL;
4909         if (rsurfacepass == RSURFPASS_BACKGROUND)
4910         {
4911                 // distorted background
4912                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4913                 {
4914                         mode = SHADERMODE_WATER;
4915                         if (rsurface.texture->r_water_waterscroll[0] && rsurface.texture->r_water_waterscroll[1])
4916                                 permutation |= SHADERPERMUTATION_NORMALMAPSCROLLBLEND;
4917                         if((r_wateralpha.value < 1) && (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA))
4918                         {
4919                                 // this is the right thing to do for wateralpha
4920                                 GL_BlendFunc(GL_ONE, GL_ZERO);
4921                                 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4922                         }
4923                         else
4924                         {
4925                                 // this is the right thing to do for entity alpha
4926                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4927                                 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4928                         }
4929                 }
4930                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4931                 {
4932                         mode = SHADERMODE_REFRACTION;
4933                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4934                         allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4935                 }
4936                 else
4937                 {
4938                         mode = SHADERMODE_GENERIC;
4939                         permutation |= SHADERPERMUTATION_DIFFUSE;
4940                         GL_BlendFunc(GL_ONE, GL_ZERO);
4941                         allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4942                 }
4943         }
4944         else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4945         {
4946                 if (r_glsl_offsetmapping.integer)
4947                 {
4948                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4949                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4950                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4951                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4952                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4953                         {
4954                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4955                                 if (r_glsl_offsetmapping_reliefmapping.integer)
4956                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4957                         }
4958                 }
4959                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4960                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4961                 // normalmap (deferred prepass), may use alpha test on diffuse
4962                 mode = SHADERMODE_DEFERREDGEOMETRY;
4963                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4964                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4965                 GL_BlendFunc(GL_ONE, GL_ZERO);
4966                 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4967         }
4968         else if (rsurfacepass == RSURFPASS_RTLIGHT)
4969         {
4970                 if (r_glsl_offsetmapping.integer)
4971                 {
4972                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4973                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4974                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4975                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4976                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4977                         {
4978                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4979                                 if (r_glsl_offsetmapping_reliefmapping.integer)
4980                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4981                         }
4982                 }
4983                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4984                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4985                 // light source
4986                 mode = SHADERMODE_LIGHTSOURCE;
4987                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4988                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4989                 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4990                         permutation |= SHADERPERMUTATION_CUBEFILTER;
4991                 if (diffusescale > 0)
4992                         permutation |= SHADERPERMUTATION_DIFFUSE;
4993                 if (specularscale > 0)
4994                         permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4995                 if (r_refdef.fogenabled)
4996                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4997                 if (rsurface.texture->colormapping)
4998                         permutation |= SHADERPERMUTATION_COLORMAPPING;
4999                 if (r_shadow_usingshadowmap2d)
5000                 {
5001                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5002                         if(r_shadow_shadowmapvsdct)
5003                                 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5004
5005                         if (r_shadow_shadowmapsampler)
5006                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5007                         if (r_shadow_shadowmappcf > 1)
5008                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5009                         else if (r_shadow_shadowmappcf)
5010                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5011                 }
5012                 if (rsurface.texture->reflectmasktexture)
5013                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5014                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
5015                 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE);
5016         }
5017         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5018         {
5019                 if (r_glsl_offsetmapping.integer)
5020                 {
5021                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5022                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5023                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5024                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5025                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5026                         {
5027                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5028                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5029                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5030                         }
5031                 }
5032                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5033                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5034                 // unshaded geometry (fullbright or ambient model lighting)
5035                 mode = SHADERMODE_FLATCOLOR;
5036                 ambientscale = diffusescale = specularscale = 0;
5037                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5038                         permutation |= SHADERPERMUTATION_GLOW;
5039                 if (r_refdef.fogenabled)
5040                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5041                 if (rsurface.texture->colormapping)
5042                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5043                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5044                 {
5045                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5046                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5047
5048                         if (r_shadow_shadowmapsampler)
5049                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5050                         if (r_shadow_shadowmappcf > 1)
5051                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5052                         else if (r_shadow_shadowmappcf)
5053                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5054                 }
5055                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5056                         permutation |= SHADERPERMUTATION_REFLECTION;
5057                 if (rsurface.texture->reflectmasktexture)
5058                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5059                 if (r_shadow_bouncegridtexture)
5060                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
5061                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5062                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5063         }
5064         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
5065         {
5066                 if (r_glsl_offsetmapping.integer)
5067                 {
5068                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5069                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5070                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5071                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5072                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5073                         {
5074                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5075                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5076                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5077                         }
5078                 }
5079                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5080                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5081                 // directional model lighting
5082                 mode = SHADERMODE_LIGHTDIRECTION;
5083                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5084                         permutation |= SHADERPERMUTATION_GLOW;
5085                 permutation |= SHADERPERMUTATION_DIFFUSE;
5086                 if (specularscale > 0)
5087                         permutation |= SHADERPERMUTATION_SPECULAR;
5088                 if (r_refdef.fogenabled)
5089                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5090                 if (rsurface.texture->colormapping)
5091                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5092                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5093                 {
5094                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5095                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5096
5097                         if (r_shadow_shadowmapsampler)
5098                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5099                         if (r_shadow_shadowmappcf > 1)
5100                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5101                         else if (r_shadow_shadowmappcf)
5102                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5103                 }
5104                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5105                         permutation |= SHADERPERMUTATION_REFLECTION;
5106                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5107                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5108                 if (rsurface.texture->reflectmasktexture)
5109                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5110                 if (r_shadow_bouncegridtexture)
5111                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
5112                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5113                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5114         }
5115         else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5116         {
5117                 if (r_glsl_offsetmapping.integer)
5118                 {
5119                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5120                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5121                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5122                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5123                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5124                         {
5125                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5126                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5127                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5128                         }
5129                 }
5130                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5131                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5132                 // ambient model lighting
5133                 mode = SHADERMODE_LIGHTDIRECTION;
5134                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5135                         permutation |= SHADERPERMUTATION_GLOW;
5136                 if (r_refdef.fogenabled)
5137                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5138                 if (rsurface.texture->colormapping)
5139                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5140                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5141                 {
5142                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5143                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5144
5145                         if (r_shadow_shadowmapsampler)
5146                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5147                         if (r_shadow_shadowmappcf > 1)
5148                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5149                         else if (r_shadow_shadowmappcf)
5150                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5151                 }
5152                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5153                         permutation |= SHADERPERMUTATION_REFLECTION;
5154                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5155                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5156                 if (rsurface.texture->reflectmasktexture)
5157                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5158                 if (r_shadow_bouncegridtexture)
5159                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
5160                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5161                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5162         }
5163         else
5164         {
5165                 if (r_glsl_offsetmapping.integer)
5166                 {
5167                         if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5168                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5169                         else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5170                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5171                         else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5172                         {
5173                                 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5174                                 if (r_glsl_offsetmapping_reliefmapping.integer)
5175                                         permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5176                         }
5177                 }
5178                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5179                         permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5180                 // lightmapped wall
5181                 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5182                         permutation |= SHADERPERMUTATION_GLOW;
5183                 if (r_refdef.fogenabled)
5184                         permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5185                 if (rsurface.texture->colormapping)
5186                         permutation |= SHADERPERMUTATION_COLORMAPPING;
5187                 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5188                 {
5189                         permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5190                         permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5191
5192                         if (r_shadow_shadowmapsampler)
5193                                 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5194                         if (r_shadow_shadowmappcf > 1)
5195                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5196                         else if (r_shadow_shadowmappcf)
5197                                 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5198                 }
5199                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5200                         permutation |= SHADERPERMUTATION_REFLECTION;
5201                 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5202                         permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5203                 if (rsurface.texture->reflectmasktexture)
5204                         permutation |= SHADERPERMUTATION_REFLECTCUBE;
5205                 if (FAKELIGHT_ENABLED)
5206                 {
5207                         // fake lightmapping (q1bsp, q3bsp, fullbright map)
5208                         mode = SHADERMODE_FAKELIGHT;
5209                         permutation |= SHADERPERMUTATION_DIFFUSE;
5210                         if (specularscale > 0)
5211                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5212                 }
5213                 else if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
5214                 {
5215                         // deluxemapping (light direction texture)
5216                         if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
5217                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
5218                         else
5219                                 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5220                         permutation |= SHADERPERMUTATION_DIFFUSE;
5221                         if (specularscale > 0)
5222                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5223                 }
5224                 else if (r_glsl_deluxemapping.integer >= 2 && rsurface.uselightmaptexture)
5225                 {
5226                         // fake deluxemapping (uniform light direction in tangentspace)
5227                         mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5228                         permutation |= SHADERPERMUTATION_DIFFUSE;
5229                         if (specularscale > 0)
5230                                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5231                 }
5232                 else if (rsurface.uselightmaptexture)
5233                 {
5234                         // ordinary lightmapping (q1bsp, q3bsp)
5235                         mode = SHADERMODE_LIGHTMAP;
5236                 }
5237                 else
5238                 {
5239                         // ordinary vertex coloring (q3bsp)
5240                         mode = SHADERMODE_VERTEXCOLOR;
5241                 }
5242                 if (r_shadow_bouncegridtexture)
5243                         permutation |= SHADERPERMUTATION_BOUNCEGRID;
5244                 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5245                 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5246         }
5247         if(!allow_colormod)
5248                 colormod = dummy_colormod;
5249         switch(vid.renderpath)
5250         {
5251         case RENDERPATH_D3D9:
5252 #ifdef SUPPORTD3D
5253                 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5254                 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5255                 R_SetupShader_SetPermutationHLSL(mode, permutation);
5256                 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
5257                 if (mode == SHADERMODE_LIGHTSOURCE)
5258                 {
5259                         Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
5260                         hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5261                 }
5262                 else
5263                 {
5264                         if (mode == SHADERMODE_LIGHTDIRECTION)
5265                         {
5266                                 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5267                         }
5268                 }
5269                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
5270                 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
5271                 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
5272                 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5273                 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5274
5275                 if (mode == SHADERMODE_LIGHTSOURCE)
5276                 {
5277                         hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5278                         hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5279                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5280                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5281                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5282
5283                         // additive passes are only darkened by fog, not tinted
5284                         hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5285                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5286                 }
5287                 else
5288                 {
5289                         if (mode == SHADERMODE_FLATCOLOR)
5290                         {
5291                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5292                         }
5293                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5294                         {
5295                                 hlslPSSetParameter3f(D3DPSREGISTER_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]);
5296                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5297                                 hlslPSSetParameter3f(D3DPSREGISTER_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);
5298                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5299                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5300                                 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5301                                 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5302                         }
5303                         else
5304                         {
5305                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5306                                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5307                                 hlslPSSetParameter3f(D3DPSREGISTER_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);
5308                                 hlslPSSetParameter3f(D3DPSREGISTER_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);
5309                                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5310                         }
5311                         // additive passes are only darkened by fog, not tinted
5312                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5313                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5314                         else
5315                                 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5316                         hlslPSSetParameter4f(D3DPSREGISTER_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);
5317                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5318                         hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5319                         hlslPSSetParameter4f(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5320                         hlslPSSetParameter4f(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5321                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5322                         hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
5323                         hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5324                         if (mode == SHADERMODE_WATER)
5325                                 hlslPSSetParameter2f(D3DPSREGISTER_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
5326                 }
5327                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5328                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5329                 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5330                 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5331                 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5332                 if (rsurface.texture->pantstexture)
5333                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5334                 else
5335                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
5336                 if (rsurface.texture->shirttexture)
5337                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5338                 else
5339                         hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
5340                 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5341                 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
5342                 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
5343                 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
5344                 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
5345                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5346                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5347
5348                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
5349                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
5350                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
5351                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
5352                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
5353                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
5354                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
5355                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
5356                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
5357                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
5358                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
5359                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5360                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
5361                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
5362                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5363                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5364                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
5365                 if (rsurfacepass == RSURFPASS_BACKGROUND)
5366                 {
5367                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5368                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5369                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5370                 }
5371                 else
5372                 {
5373                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5374                 }
5375 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
5376 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
5377                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
5378                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
5379                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5380                 {
5381                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
5382                         if (rsurface.rtlight)
5383                         {
5384                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
5385                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
5386                         }
5387                 }
5388 #endif
5389                 break;
5390         case RENDERPATH_D3D10:
5391                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5392                 break;
5393         case RENDERPATH_D3D11:
5394                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5395                 break;
5396         case RENDERPATH_GL20:
5397         case RENDERPATH_GLES2:
5398                 if (!vid.useinterleavedarrays)
5399                 {
5400                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5401                         R_Mesh_VertexPointer(     3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5402                         R_Mesh_ColorPointer(      4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5403                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5404                         R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5405                         R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5406                         R_Mesh_TexCoordPointer(3, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5407                         R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5408                 }
5409                 else
5410                 {
5411                         RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5412                         R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5413                 }
5414                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5415                 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5416                 if (mode == SHADERMODE_LIGHTSOURCE)
5417                 {
5418                         if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5419                         if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3f(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5420                         if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5421                         if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5422                         if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5423                         if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5424         
5425                         // additive passes are only darkened by fog, not tinted
5426                         if (r_glsl_permutation->loc_FogColor >= 0)
5427                                 qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5428                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5429                 }
5430                 else
5431                 {
5432                         if (mode == SHADERMODE_FLATCOLOR)
5433                         {
5434                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5435                         }
5436                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5437                         {
5438                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
5439                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5440                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(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);
5441                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(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);
5442                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5443                                 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
5444                                 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3f(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5445                         }
5446                         else
5447                         {
5448                                 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5449                                 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5450                                 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(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);
5451                                 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(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);
5452                                 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5453                         }
5454                         // additive passes are only darkened by fog, not tinted
5455                         if (r_glsl_permutation->loc_FogColor >= 0)
5456                         {
5457                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5458                                         qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5459                                 else
5460                                         qglUniform3f(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5461                         }
5462                         if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4f(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);
5463                         if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5464                         if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5465                         if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4f(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]);
5466                         if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4f(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]);
5467                         if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5468                         if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5469                         if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5470                         if (r_glsl_permutation->loc_NormalmapScrollBlend >= 0) qglUniform2f(r_glsl_permutation->loc_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
5471                 }
5472                 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5473                 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5474                 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5475                 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2f(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5476                 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4f(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]);
5477
5478                 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5479                 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1f(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));
5480                 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3f(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5481                 if (r_glsl_permutation->loc_Color_Pants >= 0)
5482                 {
5483                         if (rsurface.texture->pantstexture)
5484                                 qglUniform3f(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5485                         else
5486                                 qglUniform3f(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5487                 }
5488                 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5489                 {
5490                         if (rsurface.texture->shirttexture)
5491                                 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5492                         else
5493                                 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5494                 }
5495                 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4f(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5496                 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1f(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5497                 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1f(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5498                 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1f(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5499                 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1f(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5500                 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2f(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5501                 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5502                 if (r_glsl_permutation->loc_BounceGridMatrix >= 0) {Matrix4x4_Concat(&tempmatrix, &r_shadow_bouncegridmatrix, &rsurface.matrix);Matrix4x4_ToArrayFloatGL(&tempmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BounceGridMatrix, 1, false, m16f);}
5503                 if (r_glsl_permutation->loc_BounceGridIntensity >= 0) qglUniform1f(r_glsl_permutation->loc_BounceGridIntensity, r_shadow_bouncegridintensity);
5504
5505                 if (r_glsl_permutation->tex_Texture_First           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First            , r_texture_white                                     );
5506                 if (r_glsl_permutation->tex_Texture_Second          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second           , r_texture_white                                     );
5507                 if (r_glsl_permutation->tex_Texture_GammaRamps      >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps       , r_texture_gammaramps                                );
5508                 if (r_glsl_permutation->tex_Texture_Normal          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Normal           , rsurface.texture->nmaptexture                       );
5509                 if (r_glsl_permutation->tex_Texture_Color           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Color            , rsurface.texture->basetexture                       );
5510                 if (r_glsl_permutation->tex_Texture_Gloss           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Gloss            , rsurface.texture->glosstexture                      );
5511                 if (r_glsl_permutation->tex_Texture_Glow            >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Glow             , rsurface.texture->glowtexture                       );
5512                 if (r_glsl_permutation->tex_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryNormal  , rsurface.texture->backgroundnmaptexture             );
5513                 if (r_glsl_permutation->tex_Texture_SecondaryColor  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryColor   , rsurface.texture->backgroundbasetexture             );
5514                 if (r_glsl_permutation->tex_Texture_SecondaryGloss  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGloss   , rsurface.texture->backgroundglosstexture            );
5515                 if (r_glsl_permutation->tex_Texture_SecondaryGlow   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGlow    , rsurface.texture->backgroundglowtexture             );
5516                 if (r_glsl_permutation->tex_Texture_Pants           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Pants            , rsurface.texture->pantstexture                      );
5517                 if (r_glsl_permutation->tex_Texture_Shirt           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Shirt            , rsurface.texture->shirttexture                      );
5518                 if (r_glsl_permutation->tex_Texture_ReflectMask     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectMask      , rsurface.texture->reflectmasktexture                );
5519                 if (r_glsl_permutation->tex_Texture_ReflectCube     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectCube      , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5520                 if (r_glsl_permutation->tex_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogHeightTexture , r_texture_fogheighttexture                          );
5521                 if (r_glsl_permutation->tex_Texture_FogMask         >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogMask          , r_texture_fogattenuation                            );
5522                 if (r_glsl_permutation->tex_Texture_Lightmap        >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Lightmap         , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5523                 if (r_glsl_permutation->tex_Texture_Deluxemap       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Deluxemap        , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5524                 if (r_glsl_permutation->tex_Texture_Attenuation     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation      , r_shadow_attenuationgradienttexture                 );
5525                 if (rsurfacepass == RSURFPASS_BACKGROUND)
5526                 {
5527                         if (r_glsl_permutation->tex_Texture_Refraction  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Refraction        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5528                         if (r_glsl_permutation->tex_Texture_First       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5529                         if (r_glsl_permutation->tex_Texture_Reflection  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5530                 }
5531                 else
5532                 {
5533                         if (r_glsl_permutation->tex_Texture_Reflection >= 0 && waterplane) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5534                 }
5535                 if (r_glsl_permutation->tex_Texture_ScreenDepth     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth       , r_shadow_prepassgeometrydepthtexture                );
5536                 if (r_glsl_permutation->tex_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap   , r_shadow_prepassgeometrynormalmaptexture            );
5537                 if (r_glsl_permutation->tex_Texture_ScreenDiffuse   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDiffuse     , r_shadow_prepasslightingdiffusetexture              );
5538                 if (r_glsl_permutation->tex_Texture_ScreenSpecular  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenSpecular    , r_shadow_prepasslightingspeculartexture             );
5539                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5540                 {
5541                         if (r_glsl_permutation->tex_Texture_ShadowMap2D     >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D, r_shadow_shadowmap2dtexture                         );
5542                         if (rsurface.rtlight)
5543                         {
5544                                 if (r_glsl_permutation->tex_Texture_Cube            >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube              , rsurface.rtlight->currentcubemap                    );
5545                                 if (r_glsl_permutation->tex_Texture_CubeProjection  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection    , r_shadow_shadowmapvsdcttexture                      );
5546                         }
5547                 }
5548                 if (r_glsl_permutation->tex_Texture_BounceGrid  >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_BounceGrid, r_shadow_bouncegridtexture);
5549                 CHECKGLERROR
5550                 break;
5551         case RENDERPATH_GL13:
5552         case RENDERPATH_GL11:
5553                 break;
5554         case RENDERPATH_SOFT:
5555                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5556                 R_Mesh_PrepareVertices_Mesh_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchsvector3f, rsurface.batchtvector3f, rsurface.batchnormal3f, rsurface.batchlightmapcolor4f, rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordlightmap2f);
5557                 R_SetupShader_SetPermutationSoft(mode, permutation);
5558                 {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToReflectCubeM1, 1, false, m16f);}
5559                 if (mode == SHADERMODE_LIGHTSOURCE)
5560                 {
5561                         {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToLightM1, 1, false, m16f);}
5562                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5563                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5564                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5565                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5566                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5567         
5568                         // additive passes are only darkened by fog, not tinted
5569                         DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
5570                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5571                 }
5572                 else
5573                 {
5574                         if (mode == SHADERMODE_FLATCOLOR)
5575                         {
5576                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5577                         }
5578                         else if (mode == SHADERMODE_LIGHTDIRECTION)
5579                         {
5580                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
5581                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5582                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_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);
5583                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5584                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5585                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
5586                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5587                         }
5588                         else
5589                         {
5590                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5591                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5592                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_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);
5593                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_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);
5594                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5595                         }
5596                         // additive passes are only darkened by fog, not tinted
5597                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5598                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
5599                         else
5600                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5601                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_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);
5602                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5603                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5604                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5605                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5606                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5607                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectOffset, rsurface.texture->reflectmin);
5608                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5609                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
5610                 }
5611                 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_TexMatrixM1, 1, false, m16f);}
5612                 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_BackgroundTexMatrixM1, 1, false, m16f);}
5613                 {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ShadowMapMatrixM1, 1, false, m16f);}
5614                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5615                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5616
5617                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5618                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5619                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5620                 if (DPSOFTRAST_UNIFORM_Color_Pants >= 0)
5621                 {
5622                         if (rsurface.texture->pantstexture)
5623                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5624                         else
5625                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, 0, 0, 0);
5626                 }
5627                 if (DPSOFTRAST_UNIFORM_Color_Shirt >= 0)
5628                 {
5629                         if (rsurface.texture->shirttexture)
5630                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5631                         else
5632                                 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, 0, 0, 0);
5633                 }
5634                 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5635                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogPlaneViewDist, rsurface.fogplaneviewdist);
5636                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogRangeRecip, rsurface.fograngerecip);
5637                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogHeightFade, rsurface.fogheightfade);
5638                 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5639                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5640                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5641
5642                 R_Mesh_TexBind(GL20TU_NORMAL            , rsurface.texture->nmaptexture                       );
5643                 R_Mesh_TexBind(GL20TU_COLOR             , rsurface.texture->basetexture                       );
5644                 R_Mesh_TexBind(GL20TU_GLOSS             , rsurface.texture->glosstexture                      );
5645                 R_Mesh_TexBind(GL20TU_GLOW              , rsurface.texture->glowtexture                       );
5646                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL  , rsurface.texture->backgroundnmaptexture             );
5647                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR   , rsurface.texture->backgroundbasetexture             );
5648                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS   , rsurface.texture->backgroundglosstexture            );
5649                 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW    , rsurface.texture->backgroundglowtexture             );
5650                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS             , rsurface.texture->pantstexture                      );
5651                 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT             , rsurface.texture->shirttexture                      );
5652                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK       , rsurface.texture->reflectmasktexture                );
5653                 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE       , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5654                 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE  , r_texture_fogheighttexture                          );
5655                 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK           , r_texture_fogattenuation                            );
5656                 R_Mesh_TexBind(GL20TU_LIGHTMAP          , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5657                 R_Mesh_TexBind(GL20TU_DELUXEMAP         , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5658                 if (rsurface.rtlight                                  ) R_Mesh_TexBind(GL20TU_ATTENUATION       , r_shadow_attenuationgradienttexture                 );
5659                 if (rsurfacepass == RSURFPASS_BACKGROUND)
5660                 {
5661                         R_Mesh_TexBind(GL20TU_REFRACTION        , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5662                         if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST             , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5663                         R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5664                 }
5665                 else
5666                 {
5667                         if (permutation & SHADERPERMUTATION_REFLECTION        ) R_Mesh_TexBind(GL20TU_REFLECTION        , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5668                 }
5669 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENDEPTH       , r_shadow_prepassgeometrydepthtexture                );
5670 //              if (rsurfacepass == RSURFPASS_DEFERREDLIGHT           ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP   , r_shadow_prepassgeometrynormalmaptexture            );
5671                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE     , r_shadow_prepasslightingdiffusetexture              );
5672                 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP  ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR    , r_shadow_prepasslightingspeculartexture             );
5673                 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5674                 {
5675                         R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
5676                         if (rsurface.rtlight)
5677                         {
5678                                 if (permutation & SHADERPERMUTATION_CUBEFILTER        ) R_Mesh_TexBind(GL20TU_CUBE              , rsurface.rtlight->currentcubemap                    );
5679                                 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT    ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION    , r_shadow_shadowmapvsdcttexture                      );
5680                         }
5681                 }
5682                 break;
5683         }
5684 }
5685
5686 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5687 {
5688         // select a permutation of the lighting shader appropriate to this
5689         // combination of texture, entity, light source, and fogging, only use the
5690         // minimum features necessary to avoid wasting rendering time in the
5691         // fragment shader on features that are not being used
5692         unsigned int permutation = 0;
5693         unsigned int mode = 0;
5694         const float *lightcolorbase = rtlight->currentcolor;
5695         float ambientscale = rtlight->ambientscale;
5696         float diffusescale = rtlight->diffusescale;
5697         float specularscale = rtlight->specularscale;
5698         // this is the location of the light in view space
5699         vec3_t viewlightorigin;
5700         // this transforms from view space (camera) to light space (cubemap)
5701         matrix4x4_t viewtolight;
5702         matrix4x4_t lighttoview;
5703         float viewtolight16f[16];
5704         float range = 1.0f / r_shadow_deferred_8bitrange.value;
5705         // light source
5706         mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5707         if (rtlight->currentcubemap != r_texture_whitecube)
5708                 permutation |= SHADERPERMUTATION_CUBEFILTER;
5709         if (diffusescale > 0)
5710                 permutation |= SHADERPERMUTATION_DIFFUSE;
5711         if (specularscale > 0)
5712                 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5713         if (r_shadow_usingshadowmap2d)
5714         {
5715                 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5716                 if (r_shadow_shadowmapvsdct)
5717                         permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5718
5719                 if (r_shadow_shadowmapsampler)
5720                         permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5721                 if (r_shadow_shadowmappcf > 1)
5722                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5723                 else if (r_shadow_shadowmappcf)
5724                         permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5725         }
5726         Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5727         Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5728         Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5729         Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5730         switch(vid.renderpath)
5731         {
5732         case RENDERPATH_D3D9:
5733 #ifdef SUPPORTD3D
5734                 R_SetupShader_SetPermutationHLSL(mode, permutation);
5735                 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5736                 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
5737                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
5738                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
5739                 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5740                 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5741                 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5742                 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5743                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5744                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5745
5746                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
5747                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthcolortexture           );
5748                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
5749                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
5750                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dcolortexture                    );
5751                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
5752 #endif
5753                 break;
5754         case RENDERPATH_D3D10:
5755                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5756                 break;
5757         case RENDERPATH_D3D11:
5758                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5759                 break;
5760         case RENDERPATH_GL20:
5761         case RENDERPATH_GLES2:
5762                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5763                 if (r_glsl_permutation->loc_LightPosition             >= 0) qglUniform3f(       r_glsl_permutation->loc_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5764                 if (r_glsl_permutation->loc_ViewToLight               >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ViewToLight              , 1, false, viewtolight16f);
5765                 if (r_glsl_permutation->loc_DeferredColor_Ambient     >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
5766                 if (r_glsl_permutation->loc_DeferredColor_Diffuse     >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
5767                 if (r_glsl_permutation->loc_DeferredColor_Specular    >= 0) qglUniform3f(       r_glsl_permutation->loc_DeferredColor_Specular   , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5768                 if (r_glsl_permutation->loc_ShadowMap_TextureScale    >= 0) qglUniform2f(       r_glsl_permutation->loc_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5769                 if (r_glsl_permutation->loc_ShadowMap_Parameters      >= 0) qglUniform4f(       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]);
5770                 if (r_glsl_permutation->loc_SpecularPower             >= 0) qglUniform1f(       r_glsl_permutation->loc_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5771                 if (r_glsl_permutation->loc_ScreenToDepth             >= 0) qglUniform2f(       r_glsl_permutation->loc_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5772                 if (r_glsl_permutation->loc_PixelToScreenTexCoord     >= 0) qglUniform2f(       r_glsl_permutation->loc_PixelToScreenTexCoord    , 1.0f/vid.width, 1.0f/vid.height);
5773
5774                 if (r_glsl_permutation->tex_Texture_Attenuation       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation        , r_shadow_attenuationgradienttexture                 );
5775                 if (r_glsl_permutation->tex_Texture_ScreenDepth       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth        , r_shadow_prepassgeometrydepthtexture                );
5776                 if (r_glsl_permutation->tex_Texture_ScreenNormalMap   >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap    , r_shadow_prepassgeometrynormalmaptexture            );
5777                 if (r_glsl_permutation->tex_Texture_Cube              >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube               , rsurface.rtlight->currentcubemap                    );
5778                 if (r_glsl_permutation->tex_Texture_ShadowMap2D       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D        , r_shadow_shadowmap2dtexture                         );
5779                 if (r_glsl_permutation->tex_Texture_CubeProjection    >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection     , r_shadow_shadowmapvsdcttexture                      );
5780                 break;
5781         case RENDERPATH_GL13:
5782         case RENDERPATH_GL11:
5783                 break;
5784         case RENDERPATH_SOFT:
5785                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5786                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_LightPosition            , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5787                 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ViewToLightM1            , 1, false, viewtolight16f);
5788                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Ambient    , lightcolorbase[0] * ambientscale  * range, lightcolorbase[1] * ambientscale  * range, lightcolorbase[2] * ambientscale  * range);
5789                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Diffuse    , lightcolorbase[0] * diffusescale  * range, lightcolorbase[1] * diffusescale  * range, lightcolorbase[2] * diffusescale  * range);
5790                 DPSOFTRAST_Uniform3f(       DPSOFTRAST_UNIFORM_DeferredColor_Specular   , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5791                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ShadowMap_TextureScale   , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5792                 DPSOFTRAST_Uniform4f(       DPSOFTRAST_UNIFORM_ShadowMap_Parameters     , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5793                 DPSOFTRAST_Uniform1f(       DPSOFTRAST_UNIFORM_SpecularPower            , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5794                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5795                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5796
5797                 R_Mesh_TexBind(GL20TU_ATTENUATION        , r_shadow_attenuationgradienttexture                 );
5798                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthtexture                );
5799                 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP    , r_shadow_prepassgeometrynormalmaptexture            );
5800                 R_Mesh_TexBind(GL20TU_CUBE               , rsurface.rtlight->currentcubemap                    );
5801                 R_Mesh_TexBind(GL20TU_SHADOWMAP2D        , r_shadow_shadowmap2dtexture                         );
5802                 R_Mesh_TexBind(GL20TU_CUBEPROJECTION     , r_shadow_shadowmapvsdcttexture                      );
5803                 break;
5804         }
5805 }
5806
5807 void R_SetupShader_DeferredBounceLight(void)
5808 {
5809         // array of particle lights that contribute only ambient color
5810         unsigned int permutation = 0;
5811         unsigned int mode = 0;
5812         mode = SHADERMODE_DEFERREDBOUNCELIGHT;
5813         switch(vid.renderpath)
5814         {
5815         case RENDERPATH_D3D9:
5816 #ifdef SUPPORTD3D
5817                 R_SetupShader_SetPermutationHLSL(mode, permutation);
5818                 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5819                 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5820
5821                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthcolortexture           );
5822 #endif
5823                 break;
5824         case RENDERPATH_D3D10:
5825                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5826                 break;
5827         case RENDERPATH_D3D11:
5828                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5829                 break;
5830         case RENDERPATH_GL20:
5831         case RENDERPATH_GLES2:
5832                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5833                 if (r_glsl_permutation->loc_ScreenToDepth             >= 0) qglUniform2f(       r_glsl_permutation->loc_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5834                 if (r_glsl_permutation->loc_PixelToScreenTexCoord     >= 0) qglUniform2f(       r_glsl_permutation->loc_PixelToScreenTexCoord    , 1.0f/vid.width, 1.0f/vid.height);
5835
5836                 if (r_glsl_permutation->tex_Texture_ScreenDepth       >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth        , r_shadow_prepassgeometrydepthtexture                );
5837                 break;
5838         case RENDERPATH_GL13:
5839         case RENDERPATH_GL11:
5840                 break;
5841         case RENDERPATH_SOFT:
5842                 R_SetupShader_SetPermutationGLSL(mode, permutation);
5843                 DPSOFTRAST_Uniform2f(       DPSOFTRAST_UNIFORM_ScreenToDepth            , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5844                 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5845
5846                 R_Mesh_TexBind(GL20TU_SCREENDEPTH        , r_shadow_prepassgeometrydepthtexture                );
5847                 break;
5848         }
5849 }
5850
5851 #define SKINFRAME_HASH 1024
5852
5853 typedef struct
5854 {
5855         int loadsequence; // incremented each level change
5856         memexpandablearray_t array;
5857         skinframe_t *hash[SKINFRAME_HASH];
5858 }
5859 r_skinframe_t;
5860 r_skinframe_t r_skinframe;
5861
5862 void R_SkinFrame_PrepareForPurge(void)
5863 {
5864         r_skinframe.loadsequence++;
5865         // wrap it without hitting zero
5866         if (r_skinframe.loadsequence >= 200)
5867                 r_skinframe.loadsequence = 1;
5868 }
5869
5870 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5871 {
5872         if (!skinframe)
5873                 return;
5874         // mark the skinframe as used for the purging code
5875         skinframe->loadsequence = r_skinframe.loadsequence;
5876 }
5877
5878 void R_SkinFrame_Purge(void)
5879 {
5880         int i;
5881         skinframe_t *s;
5882         for (i = 0;i < SKINFRAME_HASH;i++)
5883         {
5884                 for (s = r_skinframe.hash[i];s;s = s->next)
5885                 {
5886                         if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5887                         {
5888                                 if (s->merged == s->base)
5889                                         s->merged = NULL;
5890                                 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5891                                 R_PurgeTexture(s->stain );s->stain  = NULL;
5892                                 R_PurgeTexture(s->merged);s->merged = NULL;
5893                                 R_PurgeTexture(s->base  );s->base   = NULL;
5894                                 R_PurgeTexture(s->pants );s->pants  = NULL;
5895                                 R_PurgeTexture(s->shirt );s->shirt  = NULL;
5896                                 R_PurgeTexture(s->nmap  );s->nmap   = NULL;
5897                                 R_PurgeTexture(s->gloss );s->gloss  = NULL;
5898                                 R_PurgeTexture(s->glow  );s->glow   = NULL;
5899                                 R_PurgeTexture(s->fog   );s->fog    = NULL;
5900                                 R_PurgeTexture(s->reflect);s->reflect = NULL;
5901                                 s->loadsequence = 0;
5902                         }
5903                 }
5904         }
5905 }
5906
5907 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5908         skinframe_t *item;
5909         char basename[MAX_QPATH];
5910
5911         Image_StripImageExtension(name, basename, sizeof(basename));
5912
5913         if( last == NULL ) {
5914                 int hashindex;
5915                 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5916                 item = r_skinframe.hash[hashindex];
5917         } else {
5918                 item = last->next;
5919         }
5920
5921         // linearly search through the hash bucket
5922         for( ; item ; item = item->next ) {
5923                 if( !strcmp( item->basename, basename ) ) {
5924                         return item;
5925                 }
5926         }
5927         return NULL;
5928 }
5929
5930 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5931 {
5932         skinframe_t *item;
5933         int hashindex;
5934         char basename[MAX_QPATH];
5935
5936         Image_StripImageExtension(name, basename, sizeof(basename));
5937
5938         hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5939         for (item = r_skinframe.hash[hashindex];item;item = item->next)
5940                 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5941                         break;
5942
5943         if (!item) {
5944                 rtexture_t *dyntexture;
5945                 // check whether its a dynamic texture
5946                 dyntexture = CL_GetDynTexture( basename );
5947                 if (!add && !dyntexture)
5948                         return NULL;
5949                 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5950                 memset(item, 0, sizeof(*item));
5951                 strlcpy(item->basename, basename, sizeof(item->basename));
5952                 item->base = dyntexture; // either NULL or dyntexture handle
5953                 item->textureflags = textureflags;
5954                 item->comparewidth = comparewidth;
5955                 item->compareheight = compareheight;
5956                 item->comparecrc = comparecrc;
5957                 item->next = r_skinframe.hash[hashindex];
5958                 r_skinframe.hash[hashindex] = item;
5959         }
5960         else if( item->base == NULL )
5961         {
5962                 rtexture_t *dyntexture;
5963                 // check whether its a dynamic texture
5964                 // 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]
5965                 dyntexture = CL_GetDynTexture( basename );
5966                 item->base = dyntexture; // either NULL or dyntexture handle
5967         }
5968
5969         R_SkinFrame_MarkUsed(item);
5970         return item;
5971 }
5972
5973 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5974         { \
5975                 unsigned long long avgcolor[5], wsum; \
5976                 int pix, comp, w; \
5977                 avgcolor[0] = 0; \
5978                 avgcolor[1] = 0; \
5979                 avgcolor[2] = 0; \
5980                 avgcolor[3] = 0; \
5981                 avgcolor[4] = 0; \
5982                 wsum = 0; \
5983                 for(pix = 0; pix < cnt; ++pix) \
5984                 { \
5985                         w = 0; \
5986                         for(comp = 0; comp < 3; ++comp) \
5987                                 w += getpixel; \
5988                         if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5989                         { \
5990                                 ++wsum; \
5991                                 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5992                                 w = getpixel; \
5993                                 for(comp = 0; comp < 3; ++comp) \
5994                                         avgcolor[comp] += getpixel * w; \
5995                                 avgcolor[3] += w; \
5996                         } \
5997                         /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5998                         avgcolor[4] += getpixel; \
5999                 } \
6000                 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
6001                         avgcolor[3] = 1; \
6002                 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
6003                 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
6004                 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
6005                 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
6006         }
6007
6008 extern cvar_t gl_picmip;
6009 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
6010 {
6011         int j;
6012         unsigned char *pixels;
6013         unsigned char *bumppixels;
6014         unsigned char *basepixels = NULL;
6015         int basepixels_width = 0;
6016         int basepixels_height = 0;
6017         skinframe_t *skinframe;
6018         rtexture_t *ddsbase = NULL;
6019         qboolean ddshasalpha = false;
6020         float ddsavgcolor[4];
6021         char basename[MAX_QPATH];
6022         int miplevel = R_PicmipForFlags(textureflags);
6023         int savemiplevel = miplevel;
6024         int mymiplevel;
6025
6026         if (cls.state == ca_dedicated)
6027                 return NULL;
6028
6029         // return an existing skinframe if already loaded
6030         // if loading of the first image fails, don't make a new skinframe as it
6031         // would cause all future lookups of this to be missing
6032         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
6033         if (skinframe && skinframe->base)
6034                 return skinframe;
6035
6036         Image_StripImageExtension(name, basename, sizeof(basename));
6037
6038         // check for DDS texture file first
6039         if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
6040         {
6041                 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer != 0, &miplevel);
6042                 if (basepixels == NULL)
6043                         return NULL;
6044         }
6045
6046         // FIXME handle miplevel
6047
6048         if (developer_loading.integer)
6049                 Con_Printf("loading skin \"%s\"\n", name);
6050
6051         // we've got some pixels to store, so really allocate this new texture now
6052         if (!skinframe)
6053                 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
6054         skinframe->stain = NULL;
6055         skinframe->merged = NULL;
6056         skinframe->base = NULL;
6057         skinframe->pants = NULL;
6058         skinframe->shirt = NULL;
6059         skinframe->nmap = NULL;
6060         skinframe->gloss = NULL;
6061         skinframe->glow = NULL;
6062         skinframe->fog = NULL;
6063         skinframe->reflect = NULL;
6064         skinframe->hasalpha = false;
6065
6066         if (ddsbase)
6067         {
6068                 skinframe->base = ddsbase;
6069                 skinframe->hasalpha = ddshasalpha;
6070                 VectorCopy(ddsavgcolor, skinframe->avgcolor);
6071                 if (r_loadfog && skinframe->hasalpha)
6072                         skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
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         else
6076         {
6077                 basepixels_width = image_width;
6078                 basepixels_height = image_height;
6079                 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);
6080                 if (textureflags & TEXF_ALPHA)
6081                 {
6082                         for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
6083                         {
6084                                 if (basepixels[j] < 255)
6085                                 {
6086                                         skinframe->hasalpha = true;
6087                                         break;
6088                                 }
6089                         }
6090                         if (r_loadfog && skinframe->hasalpha)
6091                         {
6092                                 // has transparent pixels
6093                                 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6094                                 for (j = 0;j < image_width * image_height * 4;j += 4)
6095                                 {
6096                                         pixels[j+0] = 255;
6097                                         pixels[j+1] = 255;
6098                                         pixels[j+2] = 255;
6099                                         pixels[j+3] = basepixels[j+3];
6100                                 }
6101                                 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);
6102                                 Mem_Free(pixels);
6103                         }
6104                 }
6105                 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
6106                 //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]);
6107                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
6108                         R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true, skinframe->hasalpha);
6109                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
6110                         R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true, true);
6111         }
6112
6113         if (r_loaddds)
6114         {
6115                 mymiplevel = savemiplevel;
6116                 if (r_loadnormalmap)
6117                         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);
6118                 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6119                 if (r_loadgloss)
6120                         skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6121                 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6122                 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6123                 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6124         }
6125
6126         // _norm is the name used by tenebrae and has been adopted as standard
6127         if (r_loadnormalmap && skinframe->nmap == NULL)
6128         {
6129                 mymiplevel = savemiplevel;
6130                 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6131                 {
6132                         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);
6133                         Mem_Free(pixels);
6134                         pixels = NULL;
6135                 }
6136                 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6137                 {
6138                         pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6139                         Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
6140                         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);
6141                         Mem_Free(pixels);
6142                         Mem_Free(bumppixels);
6143                 }
6144                 else if (r_shadow_bumpscale_basetexture.value > 0)
6145                 {
6146                         pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
6147                         Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
6148                         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);
6149                         Mem_Free(pixels);
6150                 }
6151                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
6152                         R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true, true);
6153         }
6154
6155         // _luma is supported only for tenebrae compatibility
6156         // _glow is the preferred name
6157         mymiplevel = savemiplevel;
6158         if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow",  skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel))))
6159         {
6160                 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);
6161                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
6162                         R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true, true);
6163                 Mem_Free(pixels);pixels = NULL;
6164         }
6165
6166         mymiplevel = savemiplevel;
6167         if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6168         {
6169                 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);
6170                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
6171                         R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true, true);
6172                 Mem_Free(pixels);
6173                 pixels = NULL;
6174         }
6175
6176         mymiplevel = savemiplevel;
6177         if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6178         {
6179                 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);
6180                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
6181                         R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true, false);
6182                 Mem_Free(pixels);
6183                 pixels = NULL;
6184         }
6185
6186         mymiplevel = savemiplevel;
6187         if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6188         {
6189                 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);
6190                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
6191                         R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true, false);
6192                 Mem_Free(pixels);
6193                 pixels = NULL;
6194         }
6195
6196         mymiplevel = savemiplevel;
6197         if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6198         {
6199                 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);
6200                 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
6201                         R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true, true);
6202                 Mem_Free(pixels);
6203                 pixels = NULL;
6204         }
6205
6206         if (basepixels)
6207                 Mem_Free(basepixels);
6208
6209         return skinframe;
6210 }
6211
6212 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
6213 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
6214 {
6215         int i;
6216         unsigned char *temp1, *temp2;
6217         skinframe_t *skinframe;
6218
6219         if (cls.state == ca_dedicated)
6220                 return NULL;
6221
6222         // if already loaded just return it, otherwise make a new skinframe
6223         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
6224         if (skinframe && skinframe->base)
6225                 return skinframe;
6226
6227         skinframe->stain = NULL;
6228         skinframe->merged = NULL;
6229         skinframe->base = NULL;
6230         skinframe->pants = NULL;
6231         skinframe->shirt = NULL;
6232         skinframe->nmap = NULL;
6233         skinframe->gloss = NULL;
6234         skinframe->glow = NULL;
6235         skinframe->fog = NULL;
6236         skinframe->reflect = NULL;
6237         skinframe->hasalpha = false;
6238
6239         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6240         if (!skindata)
6241                 return NULL;
6242
6243         if (developer_loading.integer)
6244                 Con_Printf("loading 32bit skin \"%s\"\n", name);
6245
6246         if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
6247         {
6248                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6249                 temp2 = temp1 + width * height * 4;
6250                 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6251                 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);
6252                 Mem_Free(temp1);
6253         }
6254         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
6255         if (textureflags & TEXF_ALPHA)
6256         {
6257                 for (i = 3;i < width * height * 4;i += 4)
6258                 {
6259                         if (skindata[i] < 255)
6260                         {
6261                                 skinframe->hasalpha = true;
6262                                 break;
6263                         }
6264                 }
6265                 if (r_loadfog && skinframe->hasalpha)
6266                 {
6267                         unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
6268                         memcpy(fogpixels, skindata, width * height * 4);
6269                         for (i = 0;i < width * height * 4;i += 4)
6270                                 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
6271                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
6272                         Mem_Free(fogpixels);
6273                 }
6274         }
6275
6276         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
6277         //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]);
6278
6279         return skinframe;
6280 }
6281
6282 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
6283 {
6284         int i;
6285         int featuresmask;
6286         skinframe_t *skinframe;
6287
6288         if (cls.state == ca_dedicated)
6289                 return NULL;
6290
6291         // if already loaded just return it, otherwise make a new skinframe
6292         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6293         if (skinframe && skinframe->base)
6294                 return skinframe;
6295
6296         skinframe->stain = NULL;
6297         skinframe->merged = NULL;
6298         skinframe->base = NULL;
6299         skinframe->pants = NULL;
6300         skinframe->shirt = NULL;
6301         skinframe->nmap = NULL;
6302         skinframe->gloss = NULL;
6303         skinframe->glow = NULL;
6304         skinframe->fog = NULL;
6305         skinframe->reflect = NULL;
6306         skinframe->hasalpha = false;
6307
6308         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6309         if (!skindata)
6310                 return NULL;
6311
6312         if (developer_loading.integer)
6313                 Con_Printf("loading quake skin \"%s\"\n", name);
6314
6315         // 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)
6316         skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height); // FIXME LEAK
6317         memcpy(skinframe->qpixels, skindata, width*height);
6318         skinframe->qwidth = width;
6319         skinframe->qheight = height;
6320
6321         featuresmask = 0;
6322         for (i = 0;i < width * height;i++)
6323                 featuresmask |= palette_featureflags[skindata[i]];
6324
6325         skinframe->hasalpha = false;
6326         skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
6327         skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
6328         skinframe->qgeneratemerged = true;
6329         skinframe->qgeneratebase = skinframe->qhascolormapping;
6330         skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
6331
6332         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
6333         //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]);
6334
6335         return skinframe;
6336 }
6337
6338 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
6339 {
6340         int width;
6341         int height;
6342         unsigned char *skindata;
6343
6344         if (!skinframe->qpixels)
6345                 return;
6346
6347         if (!skinframe->qhascolormapping)
6348                 colormapped = false;
6349
6350         if (colormapped)
6351         {
6352                 if (!skinframe->qgeneratebase)
6353                         return;
6354         }
6355         else
6356         {
6357                 if (!skinframe->qgeneratemerged)
6358                         return;
6359         }
6360
6361         width = skinframe->qwidth;
6362         height = skinframe->qheight;
6363         skindata = skinframe->qpixels;
6364
6365         if (skinframe->qgeneratenmap)
6366         {
6367                 unsigned char *temp1, *temp2;
6368                 skinframe->qgeneratenmap = false;
6369                 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6370                 temp2 = temp1 + width * height * 4;
6371                 // use either a custom palette or the quake palette
6372                 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
6373                 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6374                 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);
6375                 Mem_Free(temp1);
6376         }
6377
6378         if (skinframe->qgenerateglow)
6379         {
6380                 skinframe->qgenerateglow = false;
6381                 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
6382         }
6383
6384         if (colormapped)
6385         {
6386                 skinframe->qgeneratebase = false;
6387                 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);
6388                 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6389                 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6390         }
6391         else
6392         {
6393                 skinframe->qgeneratemerged = false;
6394                 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);
6395         }
6396
6397         if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6398         {
6399                 Mem_Free(skinframe->qpixels);
6400                 skinframe->qpixels = NULL;
6401         }
6402 }
6403
6404 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)
6405 {
6406         int i;
6407         skinframe_t *skinframe;
6408
6409         if (cls.state == ca_dedicated)
6410                 return NULL;
6411
6412         // if already loaded just return it, otherwise make a new skinframe
6413         skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6414         if (skinframe && skinframe->base)
6415                 return skinframe;
6416
6417         skinframe->stain = NULL;
6418         skinframe->merged = NULL;
6419         skinframe->base = NULL;
6420         skinframe->pants = NULL;
6421         skinframe->shirt = NULL;
6422         skinframe->nmap = NULL;
6423         skinframe->gloss = NULL;
6424         skinframe->glow = NULL;
6425         skinframe->fog = NULL;
6426         skinframe->reflect = NULL;
6427         skinframe->hasalpha = false;
6428
6429         // if no data was provided, then clearly the caller wanted to get a blank skinframe
6430         if (!skindata)
6431                 return NULL;
6432
6433         if (developer_loading.integer)
6434                 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6435
6436         skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6437         if (textureflags & TEXF_ALPHA)
6438         {
6439                 for (i = 0;i < width * height;i++)
6440                 {
6441                         if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6442                         {
6443                                 skinframe->hasalpha = true;
6444                                 break;
6445                         }
6446                 }
6447                 if (r_loadfog && skinframe->hasalpha)
6448                         skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6449         }
6450
6451         R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6452         //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]);
6453
6454         return skinframe;
6455 }
6456
6457 skinframe_t *R_SkinFrame_LoadMissing(void)
6458 {
6459         skinframe_t *skinframe;
6460
6461         if (cls.state == ca_dedicated)
6462                 return NULL;
6463
6464         skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6465         skinframe->stain = NULL;
6466         skinframe->merged = NULL;
6467         skinframe->base = NULL;
6468         skinframe->pants = NULL;
6469         skinframe->shirt = NULL;
6470         skinframe->nmap = NULL;
6471         skinframe->gloss = NULL;
6472         skinframe->glow = NULL;
6473         skinframe->fog = NULL;
6474         skinframe->reflect = NULL;
6475         skinframe->hasalpha = false;
6476
6477         skinframe->avgcolor[0] = rand() / RAND_MAX;
6478         skinframe->avgcolor[1] = rand() / RAND_MAX;
6479         skinframe->avgcolor[2] = rand() / RAND_MAX;
6480         skinframe->avgcolor[3] = 1;
6481
6482         return skinframe;
6483 }
6484
6485 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6486 typedef struct suffixinfo_s
6487 {
6488         const char *suffix;
6489         qboolean flipx, flipy, flipdiagonal;
6490 }
6491 suffixinfo_t;
6492 static suffixinfo_t suffix[3][6] =
6493 {
6494         {
6495                 {"px",   false, false, false},
6496                 {"nx",   false, false, false},
6497                 {"py",   false, false, false},
6498                 {"ny",   false, false, false},
6499                 {"pz",   false, false, false},
6500                 {"nz",   false, false, false}
6501         },
6502         {
6503                 {"posx", false, false, false},
6504                 {"negx", false, false, false},
6505                 {"posy", false, false, false},
6506                 {"negy", false, false, false},
6507                 {"posz", false, false, false},
6508                 {"negz", false, false, false}
6509         },
6510         {
6511                 {"rt",    true, false,  true},
6512                 {"lf",   false,  true,  true},
6513                 {"ft",    true,  true, false},
6514                 {"bk",   false, false, false},
6515                 {"up",    true, false,  true},
6516                 {"dn",    true, false,  true}
6517         }
6518 };
6519
6520 static int componentorder[4] = {0, 1, 2, 3};
6521
6522 rtexture_t *R_LoadCubemap(const char *basename)
6523 {
6524         int i, j, cubemapsize;
6525         unsigned char *cubemappixels, *image_buffer;
6526         rtexture_t *cubemaptexture;
6527         char name[256];
6528         // must start 0 so the first loadimagepixels has no requested width/height
6529         cubemapsize = 0;
6530         cubemappixels = NULL;
6531         cubemaptexture = NULL;
6532         // keep trying different suffix groups (posx, px, rt) until one loads
6533         for (j = 0;j < 3 && !cubemappixels;j++)
6534         {
6535                 // load the 6 images in the suffix group
6536                 for (i = 0;i < 6;i++)
6537                 {
6538                         // generate an image name based on the base and and suffix
6539                         dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6540                         // load it
6541                         if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer != 0, NULL)))
6542                         {
6543                                 // an image loaded, make sure width and height are equal
6544                                 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6545                                 {
6546                                         // if this is the first image to load successfully, allocate the cubemap memory
6547                                         if (!cubemappixels && image_width >= 1)
6548                                         {
6549                                                 cubemapsize = image_width;
6550                                                 // note this clears to black, so unavailable sides are black
6551                                                 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6552                                         }
6553                                         // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6554                                         if (cubemappixels)
6555                                                 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);
6556                                 }
6557                                 else
6558                                         Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6559                                 // free the image
6560                                 Mem_Free(image_buffer);
6561                         }
6562                 }
6563         }
6564         // if a cubemap loaded, upload it
6565         if (cubemappixels)
6566         {
6567                 if (developer_loading.integer)
6568                         Con_Printf("loading cubemap \"%s\"\n", basename);
6569
6570                 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6571                 Mem_Free(cubemappixels);
6572         }
6573         else
6574         {
6575                 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6576                 if (developer_loading.integer)
6577                 {
6578                         Con_Printf("(tried tried images ");
6579                         for (j = 0;j < 3;j++)
6580                                 for (i = 0;i < 6;i++)
6581                                         Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6582                         Con_Print(" and was unable to find any of them).\n");
6583                 }
6584         }
6585         return cubemaptexture;
6586 }
6587
6588 rtexture_t *R_GetCubemap(const char *basename)
6589 {
6590         int i;
6591         for (i = 0;i < r_texture_numcubemaps;i++)
6592                 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6593                         return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6594         if (i >= MAX_CUBEMAPS)
6595                 return r_texture_whitecube;
6596         r_texture_numcubemaps++;
6597         strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6598         r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6599         return r_texture_cubemaps[i].texture;
6600 }
6601
6602 void R_FreeCubemaps(void)
6603 {
6604         int i;
6605         for (i = 0;i < r_texture_numcubemaps;i++)
6606         {
6607                 if (developer_loading.integer)
6608                         Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6609                 if (r_texture_cubemaps[i].texture)
6610                         R_FreeTexture(r_texture_cubemaps[i].texture);
6611         }
6612         r_texture_numcubemaps = 0;
6613 }
6614
6615 void R_Main_FreeViewCache(void)
6616 {
6617         if (r_refdef.viewcache.entityvisible)
6618                 Mem_Free(r_refdef.viewcache.entityvisible);
6619         if (r_refdef.viewcache.world_pvsbits)
6620                 Mem_Free(r_refdef.viewcache.world_pvsbits);
6621         if (r_refdef.viewcache.world_leafvisible)
6622                 Mem_Free(r_refdef.viewcache.world_leafvisible);
6623         if (r_refdef.viewcache.world_surfacevisible)
6624                 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6625         memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6626 }
6627
6628 void R_Main_ResizeViewCache(void)
6629 {
6630         int numentities = r_refdef.scene.numentities;
6631         int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6632         int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6633         int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6634         int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6635         if (r_refdef.viewcache.maxentities < numentities)
6636         {
6637                 r_refdef.viewcache.maxentities = numentities;
6638                 if (r_refdef.viewcache.entityvisible)
6639                         Mem_Free(r_refdef.viewcache.entityvisible);
6640                 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6641         }
6642         if (r_refdef.viewcache.world_numclusters != numclusters)
6643         {
6644                 r_refdef.viewcache.world_numclusters = numclusters;
6645                 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6646                 if (r_refdef.viewcache.world_pvsbits)
6647                         Mem_Free(r_refdef.viewcache.world_pvsbits);
6648                 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6649         }
6650         if (r_refdef.viewcache.world_numleafs != numleafs)
6651         {
6652                 r_refdef.viewcache.world_numleafs = numleafs;
6653                 if (r_refdef.viewcache.world_leafvisible)
6654                         Mem_Free(r_refdef.viewcache.world_leafvisible);
6655                 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6656         }
6657         if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6658         {
6659                 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6660                 if (r_refdef.viewcache.world_surfacevisible)
6661                         Mem_Free(r_refdef.viewcache.world_surfacevisible);
6662                 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6663         }
6664 }
6665
6666 extern rtexture_t *loadingscreentexture;
6667 void gl_main_start(void)
6668 {
6669         loadingscreentexture = NULL;
6670         r_texture_blanknormalmap = NULL;
6671         r_texture_white = NULL;
6672         r_texture_grey128 = NULL;
6673         r_texture_black = NULL;
6674         r_texture_whitecube = NULL;
6675         r_texture_normalizationcube = NULL;
6676         r_texture_fogattenuation = NULL;
6677         r_texture_fogheighttexture = NULL;
6678         r_texture_gammaramps = NULL;
6679         r_texture_numcubemaps = 0;
6680
6681         r_loaddds = r_texture_dds_load.integer != 0;
6682         r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6683
6684         switch(vid.renderpath)
6685         {
6686         case RENDERPATH_GL20:
6687         case RENDERPATH_D3D9:
6688         case RENDERPATH_D3D10:
6689         case RENDERPATH_D3D11:
6690         case RENDERPATH_SOFT:
6691                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6692                 Cvar_SetValueQuick(&gl_combine, 1);
6693                 Cvar_SetValueQuick(&r_glsl, 1);
6694                 r_loadnormalmap = true;
6695                 r_loadgloss = true;
6696                 r_loadfog = false;
6697                 break;
6698         case RENDERPATH_GL13:
6699                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6700                 Cvar_SetValueQuick(&gl_combine, 1);
6701                 Cvar_SetValueQuick(&r_glsl, 0);
6702                 r_loadnormalmap = false;
6703                 r_loadgloss = false;
6704                 r_loadfog = true;
6705                 break;
6706         case RENDERPATH_GL11:
6707                 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6708                 Cvar_SetValueQuick(&gl_combine, 0);
6709                 Cvar_SetValueQuick(&r_glsl, 0);
6710                 r_loadnormalmap = false;
6711                 r_loadgloss = false;
6712                 r_loadfog = true;
6713                 break;
6714         case RENDERPATH_GLES2:
6715                 Cvar_SetValueQuick(&r_textureunits, 1);
6716                 Cvar_SetValueQuick(&gl_combine, 1);
6717                 Cvar_SetValueQuick(&r_glsl, 1);
6718                 r_loadnormalmap = true;
6719                 r_loadgloss = false;
6720                 r_loadfog = false;
6721                 break;
6722         }
6723
6724         R_AnimCache_Free();
6725         R_FrameData_Reset();
6726
6727         r_numqueries = 0;
6728         r_maxqueries = 0;
6729         memset(r_queries, 0, sizeof(r_queries));
6730
6731         r_qwskincache = NULL;
6732         r_qwskincache_size = 0;
6733
6734         // set up r_skinframe loading system for textures
6735         memset(&r_skinframe, 0, sizeof(r_skinframe));
6736         r_skinframe.loadsequence = 1;
6737         Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6738
6739         r_main_texturepool = R_AllocTexturePool();
6740         R_BuildBlankTextures();
6741         R_BuildNoTexture();
6742         if (vid.support.arb_texture_cube_map)
6743         {
6744                 R_BuildWhiteCube();
6745                 R_BuildNormalizationCube();
6746         }
6747         r_texture_fogattenuation = NULL;
6748         r_texture_fogheighttexture = NULL;
6749         r_texture_gammaramps = NULL;
6750         //r_texture_fogintensity = NULL;
6751         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6752         memset(&r_waterstate, 0, sizeof(r_waterstate));
6753         r_glsl_permutation = NULL;
6754         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6755         Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6756         glslshaderstring = NULL;
6757 #ifdef SUPPORTD3D
6758         r_hlsl_permutation = NULL;
6759         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
6760         Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
6761 #endif
6762         hlslshaderstring = NULL;
6763         memset(&r_svbsp, 0, sizeof (r_svbsp));
6764
6765         r_refdef.fogmasktable_density = 0;
6766 }
6767
6768 void gl_main_shutdown(void)
6769 {
6770         R_AnimCache_Free();
6771         R_FrameData_Reset();
6772
6773         R_Main_FreeViewCache();
6774
6775         switch(vid.renderpath)
6776         {
6777         case RENDERPATH_GL11:
6778         case RENDERPATH_GL13:
6779         case RENDERPATH_GL20:
6780         case RENDERPATH_GLES2:
6781                 if (r_maxqueries)
6782                         qglDeleteQueriesARB(r_maxqueries, r_queries);
6783                 break;
6784         case RENDERPATH_D3D9:
6785                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6786                 break;
6787         case RENDERPATH_D3D10:
6788                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6789                 break;
6790         case RENDERPATH_D3D11:
6791                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6792                 break;
6793         case RENDERPATH_SOFT:
6794                 break;
6795         }
6796
6797         r_numqueries = 0;
6798         r_maxqueries = 0;
6799         memset(r_queries, 0, sizeof(r_queries));
6800
6801         r_qwskincache = NULL;
6802         r_qwskincache_size = 0;
6803
6804         // clear out the r_skinframe state
6805         Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6806         memset(&r_skinframe, 0, sizeof(r_skinframe));
6807
6808         if (r_svbsp.nodes)
6809                 Mem_Free(r_svbsp.nodes);
6810         memset(&r_svbsp, 0, sizeof (r_svbsp));
6811         R_FreeTexturePool(&r_main_texturepool);
6812         loadingscreentexture = NULL;
6813         r_texture_blanknormalmap = NULL;
6814         r_texture_white = NULL;
6815         r_texture_grey128 = NULL;
6816         r_texture_black = NULL;
6817         r_texture_whitecube = NULL;
6818         r_texture_normalizationcube = NULL;
6819         r_texture_fogattenuation = NULL;
6820         r_texture_fogheighttexture = NULL;
6821         r_texture_gammaramps = NULL;
6822         r_texture_numcubemaps = 0;
6823         //r_texture_fogintensity = NULL;
6824         memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6825         memset(&r_waterstate, 0, sizeof(r_waterstate));
6826         R_GLSL_Restart_f();
6827
6828         r_glsl_permutation = NULL;
6829         memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6830         Mem_ExpandableArray_FreeArray(&r_glsl_permutationarray);
6831         glslshaderstring = NULL;
6832 #ifdef SUPPORTD3D
6833         r_hlsl_permutation = NULL;
6834         memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
6835         Mem_ExpandableArray_FreeArray(&r_hlsl_permutationarray);
6836 #endif
6837         hlslshaderstring = NULL;
6838 }
6839
6840 extern void CL_ParseEntityLump(char *entitystring);
6841 void gl_main_newmap(void)
6842 {
6843         // FIXME: move this code to client
6844         char *entities, entname[MAX_QPATH];
6845         if (r_qwskincache)
6846                 Mem_Free(r_qwskincache);
6847         r_qwskincache = NULL;
6848         r_qwskincache_size = 0;
6849         if (cl.worldmodel)
6850         {
6851                 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
6852                 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6853                 {
6854                         CL_ParseEntityLump(entities);
6855                         Mem_Free(entities);
6856                         return;
6857                 }
6858                 if (cl.worldmodel->brush.entities)
6859                         CL_ParseEntityLump(cl.worldmodel->brush.entities);
6860         }
6861         R_Main_FreeViewCache();
6862
6863         R_FrameData_Reset();
6864 }
6865
6866 void GL_Main_Init(void)
6867 {
6868         r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6869
6870         Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6871         Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6872         // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6873         if (gamemode == GAME_NEHAHRA)
6874         {
6875                 Cvar_RegisterVariable (&gl_fogenable);
6876                 Cvar_RegisterVariable (&gl_fogdensity);
6877                 Cvar_RegisterVariable (&gl_fogred);
6878                 Cvar_RegisterVariable (&gl_foggreen);
6879                 Cvar_RegisterVariable (&gl_fogblue);
6880                 Cvar_RegisterVariable (&gl_fogstart);
6881                 Cvar_RegisterVariable (&gl_fogend);
6882                 Cvar_RegisterVariable (&gl_skyclip);
6883         }
6884         Cvar_RegisterVariable(&r_motionblur);
6885         Cvar_RegisterVariable(&r_motionblur_maxblur);
6886         Cvar_RegisterVariable(&r_motionblur_bmin);
6887         Cvar_RegisterVariable(&r_motionblur_vmin);
6888         Cvar_RegisterVariable(&r_motionblur_vmax);
6889         Cvar_RegisterVariable(&r_motionblur_vcoeff);
6890         Cvar_RegisterVariable(&r_motionblur_randomize);
6891         Cvar_RegisterVariable(&r_damageblur);
6892         Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6893         Cvar_RegisterVariable(&r_equalize_entities_minambient);
6894         Cvar_RegisterVariable(&r_equalize_entities_by);
6895         Cvar_RegisterVariable(&r_equalize_entities_to);
6896         Cvar_RegisterVariable(&r_depthfirst);
6897         Cvar_RegisterVariable(&r_useinfinitefarclip);
6898         Cvar_RegisterVariable(&r_farclip_base);
6899         Cvar_RegisterVariable(&r_farclip_world);
6900         Cvar_RegisterVariable(&r_nearclip);
6901         Cvar_RegisterVariable(&r_showbboxes);
6902         Cvar_RegisterVariable(&r_showsurfaces);
6903         Cvar_RegisterVariable(&r_showtris);
6904         Cvar_RegisterVariable(&r_shownormals);
6905         Cvar_RegisterVariable(&r_showlighting);
6906         Cvar_RegisterVariable(&r_showshadowvolumes);
6907         Cvar_RegisterVariable(&r_showcollisionbrushes);
6908         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6909         Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6910         Cvar_RegisterVariable(&r_showdisabledepthtest);
6911         Cvar_RegisterVariable(&r_drawportals);
6912         Cvar_RegisterVariable(&r_drawentities);
6913         Cvar_RegisterVariable(&r_draw2d);
6914         Cvar_RegisterVariable(&r_drawworld);
6915         Cvar_RegisterVariable(&r_cullentities_trace);
6916         Cvar_RegisterVariable(&r_cullentities_trace_samples);
6917         Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6918         Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6919         Cvar_RegisterVariable(&r_cullentities_trace_delay);
6920         Cvar_RegisterVariable(&r_drawviewmodel);
6921         Cvar_RegisterVariable(&r_drawexteriormodel);
6922         Cvar_RegisterVariable(&r_speeds);
6923         Cvar_RegisterVariable(&r_fullbrights);
6924         Cvar_RegisterVariable(&r_wateralpha);
6925         Cvar_RegisterVariable(&r_dynamic);
6926         Cvar_RegisterVariable(&r_fakelight);
6927         Cvar_RegisterVariable(&r_fakelight_intensity);
6928         Cvar_RegisterVariable(&r_fullbright);
6929         Cvar_RegisterVariable(&r_shadows);
6930         Cvar_RegisterVariable(&r_shadows_darken);
6931         Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6932         Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6933         Cvar_RegisterVariable(&r_shadows_throwdistance);
6934         Cvar_RegisterVariable(&r_shadows_throwdirection);
6935         Cvar_RegisterVariable(&r_shadows_focus);
6936         Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6937         Cvar_RegisterVariable(&r_q1bsp_skymasking);
6938         Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6939         Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6940         Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6941         Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6942         Cvar_RegisterVariable(&r_fog_exp2);
6943         Cvar_RegisterVariable(&r_drawfog);
6944         Cvar_RegisterVariable(&r_transparentdepthmasking);
6945         Cvar_RegisterVariable(&r_texture_dds_load);
6946         Cvar_RegisterVariable(&r_texture_dds_save);
6947         Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6948         Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6949         Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6950         Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6951         Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6952         Cvar_RegisterVariable(&r_textureunits);
6953         Cvar_RegisterVariable(&gl_combine);
6954         Cvar_RegisterVariable(&r_glsl);
6955         Cvar_RegisterVariable(&r_glsl_deluxemapping);
6956         Cvar_RegisterVariable(&r_glsl_offsetmapping);
6957         Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6958         Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6959         Cvar_RegisterVariable(&r_glsl_postprocess);
6960         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6961         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6962         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6963         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6964         Cvar_RegisterVariable(&r_glsl_postprocess_uservec1_enable);
6965         Cvar_RegisterVariable(&r_glsl_postprocess_uservec2_enable);
6966         Cvar_RegisterVariable(&r_glsl_postprocess_uservec3_enable);
6967         Cvar_RegisterVariable(&r_glsl_postprocess_uservec4_enable);
6968
6969         Cvar_RegisterVariable(&r_water);
6970         Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6971         Cvar_RegisterVariable(&r_water_clippingplanebias);
6972         Cvar_RegisterVariable(&r_water_refractdistort);
6973         Cvar_RegisterVariable(&r_water_reflectdistort);
6974         Cvar_RegisterVariable(&r_water_scissormode);
6975         Cvar_RegisterVariable(&r_lerpsprites);
6976         Cvar_RegisterVariable(&r_lerpmodels);
6977         Cvar_RegisterVariable(&r_lerplightstyles);
6978         Cvar_RegisterVariable(&r_waterscroll);
6979         Cvar_RegisterVariable(&r_bloom);
6980         Cvar_RegisterVariable(&r_bloom_colorscale);
6981         Cvar_RegisterVariable(&r_bloom_brighten);
6982         Cvar_RegisterVariable(&r_bloom_blur);
6983         Cvar_RegisterVariable(&r_bloom_resolution);
6984         Cvar_RegisterVariable(&r_bloom_colorexponent);
6985         Cvar_RegisterVariable(&r_bloom_colorsubtract);
6986         Cvar_RegisterVariable(&r_hdr);
6987         Cvar_RegisterVariable(&r_hdr_scenebrightness);
6988         Cvar_RegisterVariable(&r_hdr_glowintensity);
6989         Cvar_RegisterVariable(&r_hdr_range);
6990         Cvar_RegisterVariable(&r_hdr_irisadaptation);
6991         Cvar_RegisterVariable(&r_hdr_irisadaptation_multiplier);
6992         Cvar_RegisterVariable(&r_hdr_irisadaptation_minvalue);
6993         Cvar_RegisterVariable(&r_hdr_irisadaptation_maxvalue);
6994         Cvar_RegisterVariable(&r_hdr_irisadaptation_value);
6995         Cvar_RegisterVariable(&r_hdr_irisadaptation_fade);
6996         Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6997         Cvar_RegisterVariable(&developer_texturelogging);
6998         Cvar_RegisterVariable(&gl_lightmaps);
6999         Cvar_RegisterVariable(&r_test);
7000         Cvar_RegisterVariable(&r_glsl_saturation);
7001         Cvar_RegisterVariable(&r_glsl_saturation_redcompensate);
7002         Cvar_RegisterVariable(&r_framedatasize);
7003         if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
7004                 Cvar_SetValue("r_fullbrights", 0);
7005         R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
7006
7007         Cvar_RegisterVariable(&r_track_sprites);
7008         Cvar_RegisterVariable(&r_track_sprites_flags);
7009         Cvar_RegisterVariable(&r_track_sprites_scalew);
7010         Cvar_RegisterVariable(&r_track_sprites_scaleh);
7011         Cvar_RegisterVariable(&r_overheadsprites_perspective);
7012         Cvar_RegisterVariable(&r_overheadsprites_pushback);
7013         Cvar_RegisterVariable(&r_overheadsprites_scalex);
7014         Cvar_RegisterVariable(&r_overheadsprites_scaley);
7015 }
7016
7017 extern void R_Textures_Init(void);
7018 extern void GL_Draw_Init(void);
7019 extern void GL_Main_Init(void);
7020 extern void R_Shadow_Init(void);
7021 extern void R_Sky_Init(void);
7022 extern void GL_Surf_Init(void);
7023 extern void R_Particles_Init(void);
7024 extern void R_Explosion_Init(void);
7025 extern void gl_backend_init(void);
7026 extern void Sbar_Init(void);
7027 extern void R_LightningBeams_Init(void);
7028 extern void Mod_RenderInit(void);
7029 extern void Font_Init(void);
7030
7031 void Render_Init(void)
7032 {
7033         gl_backend_init();
7034         R_Textures_Init();
7035         GL_Main_Init();
7036         Font_Init();
7037         GL_Draw_Init();
7038         R_Shadow_Init();
7039         R_Sky_Init();
7040         GL_Surf_Init();
7041         Sbar_Init();
7042         R_Particles_Init();
7043         R_Explosion_Init();
7044         R_LightningBeams_Init();
7045         Mod_RenderInit();
7046 }
7047
7048 /*
7049 ===============
7050 GL_Init
7051 ===============
7052 */
7053 extern char *ENGINE_EXTENSIONS;
7054 void GL_Init (void)
7055 {
7056         gl_renderer = (const char *)qglGetString(GL_RENDERER);
7057         gl_vendor = (const char *)qglGetString(GL_VENDOR);
7058         gl_version = (const char *)qglGetString(GL_VERSION);
7059         gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
7060
7061         if (!gl_extensions)
7062                 gl_extensions = "";
7063         if (!gl_platformextensions)
7064                 gl_platformextensions = "";
7065
7066         Con_Printf("GL_VENDOR: %s\n", gl_vendor);
7067         Con_Printf("GL_RENDERER: %s\n", gl_renderer);
7068         Con_Printf("GL_VERSION: %s\n", gl_version);
7069         Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
7070         Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
7071
7072         VID_CheckExtensions();
7073
7074         // LordHavoc: report supported extensions
7075         Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
7076
7077         // clear to black (loading plaque will be seen over this)
7078         GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
7079 }
7080
7081 int R_CullBox(const vec3_t mins, const vec3_t maxs)
7082 {
7083         int i;
7084         mplane_t *p;
7085         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7086         {
7087                 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
7088                 if (i == 4)
7089                         continue;
7090                 p = r_refdef.view.frustum + i;
7091                 switch(p->signbits)
7092                 {
7093                 default:
7094                 case 0:
7095                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7096                                 return true;
7097                         break;
7098                 case 1:
7099                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7100                                 return true;
7101                         break;
7102                 case 2:
7103                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7104                                 return true;
7105                         break;
7106                 case 3:
7107                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7108                                 return true;
7109                         break;
7110                 case 4:
7111                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7112                                 return true;
7113                         break;
7114                 case 5:
7115                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7116                                 return true;
7117                         break;
7118                 case 6:
7119                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7120                                 return true;
7121                         break;
7122                 case 7:
7123                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7124                                 return true;
7125                         break;
7126                 }
7127         }
7128         return false;
7129 }
7130
7131 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
7132 {
7133         int i;
7134         const mplane_t *p;
7135         for (i = 0;i < numplanes;i++)
7136         {
7137                 p = planes + i;
7138                 switch(p->signbits)
7139                 {
7140                 default:
7141                 case 0:
7142                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7143                                 return true;
7144                         break;
7145                 case 1:
7146                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7147                                 return true;
7148                         break;
7149                 case 2:
7150                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7151                                 return true;
7152                         break;
7153                 case 3:
7154                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7155                                 return true;
7156                         break;
7157                 case 4:
7158                         if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7159                                 return true;
7160                         break;
7161                 case 5:
7162                         if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7163                                 return true;
7164                         break;
7165                 case 6:
7166                         if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7167                                 return true;
7168                         break;
7169                 case 7:
7170                         if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7171                                 return true;
7172                         break;
7173                 }
7174         }
7175         return false;
7176 }
7177
7178 //==================================================================================
7179
7180 // LordHavoc: this stores temporary data used within the same frame
7181
7182 typedef struct r_framedata_mem_s
7183 {
7184         struct r_framedata_mem_s *purge; // older mem block to free on next frame
7185         size_t size; // how much usable space
7186         size_t current; // how much space in use
7187         size_t mark; // last "mark" location, temporary memory can be freed by returning to this
7188         size_t wantedsize; // how much space was allocated
7189         unsigned char *data; // start of real data (16byte aligned)
7190 }
7191 r_framedata_mem_t;
7192
7193 static r_framedata_mem_t *r_framedata_mem;
7194
7195 void R_FrameData_Reset(void)
7196 {
7197         while (r_framedata_mem)
7198         {
7199                 r_framedata_mem_t *next = r_framedata_mem->purge;
7200                 Mem_Free(r_framedata_mem);
7201                 r_framedata_mem = next;
7202         }
7203 }
7204
7205 void R_FrameData_Resize(void)
7206 {
7207         size_t wantedsize;
7208         wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
7209         wantedsize = bound(65536, wantedsize, 1000*1024*1024);
7210         if (!r_framedata_mem || r_framedata_mem->wantedsize != wantedsize)
7211         {
7212                 r_framedata_mem_t *newmem = (r_framedata_mem_t *)Mem_Alloc(r_main_mempool, wantedsize);
7213                 newmem->wantedsize = wantedsize;
7214                 newmem->data = (unsigned char *)(((size_t)(newmem+1) + 15) & ~15);
7215                 newmem->size = (unsigned char *)newmem + wantedsize - newmem->data;
7216                 newmem->current = 0;
7217                 newmem->mark = 0;
7218                 newmem->purge = r_framedata_mem;
7219                 r_framedata_mem = newmem;
7220         }
7221 }
7222
7223 void R_FrameData_NewFrame(void)
7224 {
7225         R_FrameData_Resize();
7226         if (!r_framedata_mem)
7227                 return;
7228         // if we ran out of space on the last frame, free the old memory now
7229         while (r_framedata_mem->purge)
7230         {
7231                 // repeatedly remove the second item in the list, leaving only head
7232                 r_framedata_mem_t *next = r_framedata_mem->purge->purge;
7233                 Mem_Free(r_framedata_mem->purge);
7234                 r_framedata_mem->purge = next;
7235         }
7236         // reset the current mem pointer
7237         r_framedata_mem->current = 0;
7238         r_framedata_mem->mark = 0;
7239 }
7240
7241 void *R_FrameData_Alloc(size_t size)
7242 {
7243         void *data;
7244
7245         // align to 16 byte boundary - the data pointer is already aligned, so we
7246         // only need to ensure the size of every allocation is also aligned
7247         size = (size + 15) & ~15;
7248
7249         while (!r_framedata_mem || r_framedata_mem->current + size > r_framedata_mem->size)
7250         {
7251                 // emergency - we ran out of space, allocate more memory
7252                 Cvar_SetValueQuick(&r_framedatasize, bound(0.25f, r_framedatasize.value * 2.0f, 128.0f));
7253                 R_FrameData_Resize();
7254         }
7255
7256         data = r_framedata_mem->data + r_framedata_mem->current;
7257         r_framedata_mem->current += size;
7258
7259         // count the usage for stats
7260         r_refdef.stats.framedatacurrent = max(r_refdef.stats.framedatacurrent, (int)r_framedata_mem->current);
7261         r_refdef.stats.framedatasize = max(r_refdef.stats.framedatasize, (int)r_framedata_mem->size);
7262
7263         return (void *)data;
7264 }
7265
7266 void *R_FrameData_Store(size_t size, void *data)
7267 {
7268         void *d = R_FrameData_Alloc(size);
7269         if (d && data)
7270                 memcpy(d, data, size);
7271         return d;
7272 }
7273
7274 void R_FrameData_SetMark(void)
7275 {
7276         if (!r_framedata_mem)
7277                 return;
7278         r_framedata_mem->mark = r_framedata_mem->current;
7279 }
7280
7281 void R_FrameData_ReturnToMark(void)
7282 {
7283         if (!r_framedata_mem)
7284                 return;
7285         r_framedata_mem->current = r_framedata_mem->mark;
7286 }
7287
7288 //==================================================================================
7289
7290 // LordHavoc: animcache originally written by Echon, rewritten since then
7291
7292 /**
7293  * Animation cache prevents re-generating mesh data for an animated model
7294  * multiple times in one frame for lighting, shadowing, reflections, etc.
7295  */
7296
7297 void R_AnimCache_Free(void)
7298 {
7299 }
7300
7301 void R_AnimCache_ClearCache(void)
7302 {
7303         int i;
7304         entity_render_t *ent;
7305
7306         for (i = 0;i < r_refdef.scene.numentities;i++)
7307         {
7308                 ent = r_refdef.scene.entities[i];
7309                 ent->animcache_vertex3f = NULL;
7310                 ent->animcache_normal3f = NULL;
7311                 ent->animcache_svector3f = NULL;
7312                 ent->animcache_tvector3f = NULL;
7313                 ent->animcache_vertexmesh = NULL;
7314                 ent->animcache_vertex3fbuffer = NULL;
7315                 ent->animcache_vertexmeshbuffer = NULL;
7316         }
7317 }
7318
7319 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
7320 {
7321         int i;
7322
7323         // check if we need the meshbuffers
7324         if (!vid.useinterleavedarrays)
7325                 return;
7326
7327         if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
7328                 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
7329         // TODO: upload vertex3f buffer?
7330         if (ent->animcache_vertexmesh)
7331         {
7332                 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
7333                 for (i = 0;i < numvertices;i++)
7334                         memcpy(ent->animcache_vertexmesh[i].vertex3f, ent->animcache_vertex3f + 3*i, sizeof(float[3]));
7335                 if (ent->animcache_svector3f)
7336                         for (i = 0;i < numvertices;i++)
7337                                 memcpy(ent->animcache_vertexmesh[i].svector3f, ent->animcache_svector3f + 3*i, sizeof(float[3]));
7338                 if (ent->animcache_tvector3f)
7339                         for (i = 0;i < numvertices;i++)
7340                                 memcpy(ent->animcache_vertexmesh[i].tvector3f, ent->animcache_tvector3f + 3*i, sizeof(float[3]));
7341                 if (ent->animcache_normal3f)
7342                         for (i = 0;i < numvertices;i++)
7343                                 memcpy(ent->animcache_vertexmesh[i].normal3f, ent->animcache_normal3f + 3*i, sizeof(float[3]));
7344                 // TODO: upload vertexmeshbuffer?
7345         }
7346 }
7347
7348 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
7349 {
7350         dp_model_t *model = ent->model;
7351         int numvertices;
7352         // see if it's already cached this frame
7353         if (ent->animcache_vertex3f)
7354         {
7355                 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
7356                 if (wantnormals || wanttangents)
7357                 {
7358                         if (ent->animcache_normal3f)
7359                                 wantnormals = false;
7360                         if (ent->animcache_svector3f)
7361                                 wanttangents = false;
7362                         if (wantnormals || wanttangents)
7363                         {
7364                                 numvertices = model->surfmesh.num_vertices;
7365                                 if (wantnormals)
7366                                         ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7367                                 if (wanttangents)
7368                                 {
7369                                         ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7370                                         ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7371                                 }
7372                                 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
7373                                 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7374                         }
7375                 }
7376         }
7377         else
7378         {
7379                 // see if this ent is worth caching
7380                 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
7381                         return false;
7382                 // get some memory for this entity and generate mesh data
7383                 numvertices = model->surfmesh.num_vertices;
7384                 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7385                 if (wantnormals)
7386                         ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7387                 if (wanttangents)
7388                 {
7389                         ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7390                         ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7391                 }
7392                 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
7393                 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7394         }
7395         return true;
7396 }
7397
7398 void R_AnimCache_CacheVisibleEntities(void)
7399 {
7400         int i;
7401         qboolean wantnormals = true;
7402         qboolean wanttangents = !r_showsurfaces.integer;
7403
7404         switch(vid.renderpath)
7405         {
7406         case RENDERPATH_GL20:
7407         case RENDERPATH_D3D9:
7408         case RENDERPATH_D3D10:
7409         case RENDERPATH_D3D11:
7410         case RENDERPATH_GLES2:
7411                 break;
7412         case RENDERPATH_GL13:
7413         case RENDERPATH_GL11:
7414                 wanttangents = false;
7415                 break;
7416         case RENDERPATH_SOFT:
7417                 break;
7418         }
7419
7420         if (r_shownormals.integer)
7421                 wanttangents = wantnormals = true;
7422
7423         // TODO: thread this
7424         // NOTE: R_PrepareRTLights() also caches entities
7425
7426         for (i = 0;i < r_refdef.scene.numentities;i++)
7427                 if (r_refdef.viewcache.entityvisible[i])
7428                         R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
7429 }
7430
7431 //==================================================================================
7432
7433 static void R_View_UpdateEntityLighting (void)
7434 {
7435         int i;
7436         entity_render_t *ent;
7437         vec3_t tempdiffusenormal, avg;
7438         vec_t f, fa, fd, fdd;
7439         qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
7440
7441         for (i = 0;i < r_refdef.scene.numentities;i++)
7442         {
7443                 ent = r_refdef.scene.entities[i];
7444
7445                 // skip unseen models
7446                 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
7447                         continue;
7448
7449                 // skip bsp models
7450                 if (ent->model && ent->model->brush.num_leafs)
7451                 {
7452                         // TODO: use modellight for r_ambient settings on world?
7453                         VectorSet(ent->modellight_ambient, 0, 0, 0);
7454                         VectorSet(ent->modellight_diffuse, 0, 0, 0);
7455                         VectorSet(ent->modellight_lightdir, 0, 0, 1);
7456                         continue;
7457                 }
7458
7459                 // fetch the lighting from the worldmodel data
7460                 VectorClear(ent->modellight_ambient);
7461                 VectorClear(ent->modellight_diffuse);
7462                 VectorClear(tempdiffusenormal);
7463                 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
7464                 {
7465                         vec3_t org;
7466                         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7467
7468                         // complete lightning for lit sprites
7469                         // todo: make a EF_ field so small ents could be lit purely by modellight and skipping real rtlight pass (like EF_NORTLIGHT)?
7470                         if (ent->model->type == mod_sprite && !(ent->model->data_textures[0].basematerialflags & MATERIALFLAG_FULLBRIGHT))
7471                         {
7472                                 if (ent->model->sprite.sprnum_type == SPR_OVERHEAD) // apply offset for overhead sprites
7473                                         org[2] = org[2] + r_overheadsprites_pushback.value;
7474                                 R_CompleteLightPoint(ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal, org, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT);
7475                         }
7476                         else
7477                                 R_CompleteLightPoint(ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal, org, LP_LIGHTMAP);
7478
7479                         if(ent->flags & RENDER_EQUALIZE)
7480                         {
7481                                 // first fix up ambient lighting...
7482                                 if(r_equalize_entities_minambient.value > 0)
7483                                 {
7484                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7485                                         if(fd > 0)
7486                                         {
7487                                                 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
7488                                                 if(fa < r_equalize_entities_minambient.value * fd)
7489                                                 {
7490                                                         // solve:
7491                                                         //   fa'/fd' = minambient
7492                                                         //   fa'+0.25*fd' = fa+0.25*fd
7493                                                         //   ...
7494                                                         //   fa' = fd' * minambient
7495                                                         //   fd'*(0.25+minambient) = fa+0.25*fd
7496                                                         //   ...
7497                                                         //   fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7498                                                         //   fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7499                                                         //   ...
7500                                                         fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7501                                                         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
7502                                                         VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7503                                                         VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7504                                                 }
7505                                         }
7506                                 }
7507
7508                                 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7509                                 {
7510                                         fa = 0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2];
7511                                         fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7512                                         f = fa + 0.25 * fd;
7513                                         if(f > 0)
7514                                         {
7515                                                 // adjust brightness and saturation to target
7516                                                 avg[0] = avg[1] = avg[2] = fa / f;
7517                                                 VectorLerp(ent->modellight_ambient, r_equalize_entities_by.value, avg, ent->modellight_ambient);
7518                                                 avg[0] = avg[1] = avg[2] = fd / f;
7519                                                 VectorLerp(ent->modellight_diffuse, r_equalize_entities_by.value, avg, ent->modellight_diffuse);
7520                                         }
7521                                 }
7522                         }
7523                 }
7524                 else // highly rare
7525                         VectorSet(ent->modellight_ambient, 1, 1, 1);
7526
7527                 // move the light direction into modelspace coordinates for lighting code
7528                 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7529                 if(VectorLength2(ent->modellight_lightdir) == 0)
7530                         VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7531                 VectorNormalize(ent->modellight_lightdir);
7532         }
7533 }
7534
7535 #define MAX_LINEOFSIGHTTRACES 64
7536
7537 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7538 {
7539         int i;
7540         vec3_t boxmins, boxmaxs;
7541         vec3_t start;
7542         vec3_t end;
7543         dp_model_t *model = r_refdef.scene.worldmodel;
7544
7545         if (!model || !model->brush.TraceLineOfSight)
7546                 return true;
7547
7548         // expand the box a little
7549         boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7550         boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7551         boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7552         boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7553         boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7554         boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7555
7556         // return true if eye is inside enlarged box
7557         if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7558                 return true;
7559
7560         // try center
7561         VectorCopy(eye, start);
7562         VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7563         if (model->brush.TraceLineOfSight(model, start, end))
7564                 return true;
7565
7566         // try various random positions
7567         for (i = 0;i < numsamples;i++)
7568         {
7569                 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7570                 if (model->brush.TraceLineOfSight(model, start, end))
7571                         return true;
7572         }
7573
7574         return false;
7575 }
7576
7577
7578 static void R_View_UpdateEntityVisible (void)
7579 {
7580         int i;
7581         int renderimask;
7582         int samples;
7583         entity_render_t *ent;
7584
7585         renderimask = r_refdef.envmap                                    ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7586                 : r_waterstate.renderingrefraction                       ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7587                 : (chase_active.integer || r_waterstate.renderingscene)  ? RENDER_VIEWMODEL
7588                 :                                                          RENDER_EXTERIORMODEL;
7589         if (!r_drawviewmodel.integer)
7590                 renderimask |= RENDER_VIEWMODEL;
7591         if (!r_drawexteriormodel.integer)
7592                 renderimask |= RENDER_EXTERIORMODEL;
7593         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7594         {
7595                 // worldmodel can check visibility
7596                 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7597                 for (i = 0;i < r_refdef.scene.numentities;i++)
7598                 {
7599                         ent = r_refdef.scene.entities[i];
7600                         if (!(ent->flags & renderimask))
7601                         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)))
7602                         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))
7603                                 r_refdef.viewcache.entityvisible[i] = true;
7604                 }
7605                 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7606                         // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7607                 {
7608                         for (i = 0;i < r_refdef.scene.numentities;i++)
7609                         {
7610                                 ent = r_refdef.scene.entities[i];
7611                                 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7612                                 {
7613                                         samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7614                                         if (samples < 0)
7615                                                 continue; // temp entities do pvs only
7616                                         if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7617                                                 ent->last_trace_visibility = realtime;
7618                                         if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7619                                                 r_refdef.viewcache.entityvisible[i] = 0;
7620                                 }
7621                         }
7622                 }
7623         }
7624         else
7625         {
7626                 // no worldmodel or it can't check visibility
7627                 for (i = 0;i < r_refdef.scene.numentities;i++)
7628                 {
7629                         ent = r_refdef.scene.entities[i];
7630                         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));
7631                 }
7632         }
7633 }
7634
7635 /// only used if skyrendermasked, and normally returns false
7636 int R_DrawBrushModelsSky (void)
7637 {
7638         int i, sky;
7639         entity_render_t *ent;
7640
7641         sky = false;
7642         for (i = 0;i < r_refdef.scene.numentities;i++)
7643         {
7644                 if (!r_refdef.viewcache.entityvisible[i])
7645                         continue;
7646                 ent = r_refdef.scene.entities[i];
7647                 if (!ent->model || !ent->model->DrawSky)
7648                         continue;
7649                 ent->model->DrawSky(ent);
7650                 sky = true;
7651         }
7652         return sky;
7653 }
7654
7655 static void R_DrawNoModel(entity_render_t *ent);
7656 static void R_DrawModels(void)
7657 {
7658         int i;
7659         entity_render_t *ent;
7660
7661         for (i = 0;i < r_refdef.scene.numentities;i++)
7662         {
7663                 if (!r_refdef.viewcache.entityvisible[i])
7664                         continue;
7665                 ent = r_refdef.scene.entities[i];
7666                 r_refdef.stats.entities++;
7667                 if (ent->model && ent->model->Draw != NULL)
7668                         ent->model->Draw(ent);
7669                 else
7670                         R_DrawNoModel(ent);
7671         }
7672 }
7673
7674 static void R_DrawModelsDepth(void)
7675 {
7676         int i;
7677         entity_render_t *ent;
7678
7679         for (i = 0;i < r_refdef.scene.numentities;i++)
7680         {
7681                 if (!r_refdef.viewcache.entityvisible[i])
7682                         continue;
7683                 ent = r_refdef.scene.entities[i];
7684                 if (ent->model && ent->model->DrawDepth != NULL)
7685                         ent->model->DrawDepth(ent);
7686         }
7687 }
7688
7689 static void R_DrawModelsDebug(void)
7690 {
7691         int i;
7692         entity_render_t *ent;
7693
7694         for (i = 0;i < r_refdef.scene.numentities;i++)
7695         {
7696                 if (!r_refdef.viewcache.entityvisible[i])
7697                         continue;
7698                 ent = r_refdef.scene.entities[i];
7699                 if (ent->model && ent->model->DrawDebug != NULL)
7700                         ent->model->DrawDebug(ent);
7701         }
7702 }
7703
7704 static void R_DrawModelsAddWaterPlanes(void)
7705 {
7706         int i;
7707         entity_render_t *ent;
7708
7709         for (i = 0;i < r_refdef.scene.numentities;i++)
7710         {
7711                 if (!r_refdef.viewcache.entityvisible[i])
7712                         continue;
7713                 ent = r_refdef.scene.entities[i];
7714                 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7715                         ent->model->DrawAddWaterPlanes(ent);
7716         }
7717 }
7718
7719 void R_HDR_UpdateIrisAdaptation(const vec3_t point)
7720 {
7721         if (r_hdr_irisadaptation.integer)
7722         {
7723                 vec3_t ambient;
7724                 vec3_t diffuse;
7725                 vec3_t diffusenormal;
7726                 vec_t brightness;
7727                 vec_t goal;
7728                 vec_t adjust;
7729                 vec_t current;
7730                 R_CompleteLightPoint(ambient, diffuse, diffusenormal, point, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT);
7731                 brightness = (ambient[0] + ambient[1] + ambient[2] + diffuse[0] + diffuse[1] + diffuse[2]) * (1.0f / 3.0f);
7732                 brightness = max(0.0000001f, brightness);
7733                 goal = r_hdr_irisadaptation_multiplier.value / brightness;
7734                 goal = bound(r_hdr_irisadaptation_minvalue.value, goal, r_hdr_irisadaptation_maxvalue.value);
7735                 adjust = r_hdr_irisadaptation_fade.value * cl.realframetime;
7736                 current = r_hdr_irisadaptation_value.value;
7737                 if (current < goal)
7738                         current = min(current + adjust, goal);
7739                 else if (current > goal)
7740                         current = max(current - adjust, goal);
7741                 if (fabs(r_hdr_irisadaptation_value.value - current) > 0.0001f)
7742                         Cvar_SetValueQuick(&r_hdr_irisadaptation_value, current);
7743         }
7744         else if (r_hdr_irisadaptation_value.value != 1.0f)
7745                 Cvar_SetValueQuick(&r_hdr_irisadaptation_value, 1.0f);
7746 }
7747
7748 static void R_View_SetFrustum(const int *scissor)
7749 {
7750         int i;
7751         double fpx = +1, fnx = -1, fpy = +1, fny = -1;
7752         vec3_t forward, left, up, origin, v;
7753
7754         if(scissor)
7755         {
7756                 // flipped x coordinates (because x points left here)
7757                 fpx =  1.0 - 2.0 * (scissor[0]              - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
7758                 fnx =  1.0 - 2.0 * (scissor[0] + scissor[2] - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
7759
7760                 // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
7761                 switch(vid.renderpath)
7762                 {
7763                         case RENDERPATH_D3D9:
7764                         case RENDERPATH_D3D10:
7765                         case RENDERPATH_D3D11:
7766                         case RENDERPATH_SOFT:
7767                                 // non-flipped y coordinates
7768                                 fny = -1.0 + 2.0 * (vid.height - scissor[1] - scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7769                                 fpy = -1.0 + 2.0 * (vid.height - scissor[1]              - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7770                                 break;
7771                         case RENDERPATH_GL11:
7772                         case RENDERPATH_GL13:
7773                         case RENDERPATH_GL20:
7774                         case RENDERPATH_GLES2:
7775                                 // non-flipped y coordinates
7776                                 fny = -1.0 + 2.0 * (scissor[1]              - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7777                                 fpy = -1.0 + 2.0 * (scissor[1] + scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7778                                 break;
7779                 }
7780         }
7781
7782         // we can't trust r_refdef.view.forward and friends in reflected scenes
7783         Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7784
7785 #if 0
7786         r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7787         r_refdef.view.frustum[0].normal[1] = 0 - 0;
7788         r_refdef.view.frustum[0].normal[2] = -1 - 0;
7789         r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7790         r_refdef.view.frustum[1].normal[1] = 0 + 0;
7791         r_refdef.view.frustum[1].normal[2] = -1 + 0;
7792         r_refdef.view.frustum[2].normal[0] = 0 - 0;
7793         r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7794         r_refdef.view.frustum[2].normal[2] = -1 - 0;
7795         r_refdef.view.frustum[3].normal[0] = 0 + 0;
7796         r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7797         r_refdef.view.frustum[3].normal[2] = -1 + 0;
7798 #endif
7799
7800 #if 0
7801         zNear = r_refdef.nearclip;
7802         nudge = 1.0 - 1.0 / (1<<23);
7803         r_refdef.view.frustum[4].normal[0] = 0 - 0;
7804         r_refdef.view.frustum[4].normal[1] = 0 - 0;
7805         r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7806         r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7807         r_refdef.view.frustum[5].normal[0] = 0 + 0;
7808         r_refdef.view.frustum[5].normal[1] = 0 + 0;
7809         r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7810         r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7811 #endif
7812
7813
7814
7815 #if 0
7816         r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7817         r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7818         r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7819         r_refdef.view.frustum[0].dist = m[15] - m[12];
7820
7821         r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7822         r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7823         r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7824         r_refdef.view.frustum[1].dist = m[15] + m[12];
7825
7826         r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7827         r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7828         r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7829         r_refdef.view.frustum[2].dist = m[15] - m[13];
7830
7831         r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7832         r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7833         r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7834         r_refdef.view.frustum[3].dist = m[15] + m[13];
7835
7836         r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7837         r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7838         r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7839         r_refdef.view.frustum[4].dist = m[15] - m[14];
7840
7841         r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7842         r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7843         r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7844         r_refdef.view.frustum[5].dist = m[15] + m[14];
7845 #endif
7846
7847         if (r_refdef.view.useperspective)
7848         {
7849                 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7850                 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]);
7851                 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]);
7852                 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]);
7853                 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]);
7854
7855                 // then the normals from the corners relative to origin
7856                 CrossProduct(r_refdef.view.frustumcorner[2], r_refdef.view.frustumcorner[0], r_refdef.view.frustum[0].normal);
7857                 CrossProduct(r_refdef.view.frustumcorner[1], r_refdef.view.frustumcorner[3], r_refdef.view.frustum[1].normal);
7858                 CrossProduct(r_refdef.view.frustumcorner[0], r_refdef.view.frustumcorner[1], r_refdef.view.frustum[2].normal);
7859                 CrossProduct(r_refdef.view.frustumcorner[3], r_refdef.view.frustumcorner[2], r_refdef.view.frustum[3].normal);
7860
7861                 // in a NORMAL view, forward cross left == up
7862                 // in a REFLECTED view, forward cross left == down
7863                 // so our cross products above need to be adjusted for a left handed coordinate system
7864                 CrossProduct(forward, left, v);
7865                 if(DotProduct(v, up) < 0)
7866                 {
7867                         VectorNegate(r_refdef.view.frustum[0].normal, r_refdef.view.frustum[0].normal);
7868                         VectorNegate(r_refdef.view.frustum[1].normal, r_refdef.view.frustum[1].normal);
7869                         VectorNegate(r_refdef.view.frustum[2].normal, r_refdef.view.frustum[2].normal);
7870                         VectorNegate(r_refdef.view.frustum[3].normal, r_refdef.view.frustum[3].normal);
7871                 }
7872
7873                 // Leaving those out was a mistake, those were in the old code, and they
7874                 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7875                 // I couldn't reproduce it after adding those normalizations. --blub
7876                 VectorNormalize(r_refdef.view.frustum[0].normal);
7877                 VectorNormalize(r_refdef.view.frustum[1].normal);
7878                 VectorNormalize(r_refdef.view.frustum[2].normal);
7879                 VectorNormalize(r_refdef.view.frustum[3].normal);
7880
7881                 // make the corners absolute
7882                 VectorAdd(r_refdef.view.frustumcorner[0], r_refdef.view.origin, r_refdef.view.frustumcorner[0]);
7883                 VectorAdd(r_refdef.view.frustumcorner[1], r_refdef.view.origin, r_refdef.view.frustumcorner[1]);
7884                 VectorAdd(r_refdef.view.frustumcorner[2], r_refdef.view.origin, r_refdef.view.frustumcorner[2]);
7885                 VectorAdd(r_refdef.view.frustumcorner[3], r_refdef.view.origin, r_refdef.view.frustumcorner[3]);
7886
7887                 // one more normal
7888                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7889
7890                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7891                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7892                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7893                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7894                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7895         }
7896         else
7897         {
7898                 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7899                 VectorScale(left,  r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7900                 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7901                 VectorScale(up,  r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7902                 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7903                 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7904                 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7905                 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7906                 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7907                 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7908         }
7909         r_refdef.view.numfrustumplanes = 5;
7910
7911         if (r_refdef.view.useclipplane)
7912         {
7913                 r_refdef.view.numfrustumplanes = 6;
7914                 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7915         }
7916
7917         for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7918                 PlaneClassify(r_refdef.view.frustum + i);
7919
7920         // LordHavoc: note to all quake engine coders, Quake had a special case
7921         // for 90 degrees which assumed a square view (wrong), so I removed it,
7922         // Quake2 has it disabled as well.
7923
7924         // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7925         //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7926         //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7927         //PlaneClassify(&frustum[0]);
7928
7929         // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7930         //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7931         //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7932         //PlaneClassify(&frustum[1]);
7933
7934         // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7935         //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7936         //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7937         //PlaneClassify(&frustum[2]);
7938
7939         // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7940         //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7941         //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7942         //PlaneClassify(&frustum[3]);
7943
7944         // nearclip plane
7945         //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7946         //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7947         //PlaneClassify(&frustum[4]);
7948 }
7949
7950 void R_View_UpdateWithScissor(const int *myscissor)
7951 {
7952         R_Main_ResizeViewCache();
7953         R_View_SetFrustum(myscissor);
7954         R_View_WorldVisibility(r_refdef.view.useclipplane);
7955         R_View_UpdateEntityVisible();
7956         R_View_UpdateEntityLighting();
7957 }
7958
7959 void R_View_Update(void)
7960 {
7961         R_Main_ResizeViewCache();
7962         R_View_SetFrustum(NULL);
7963         R_View_WorldVisibility(r_refdef.view.useclipplane);
7964         R_View_UpdateEntityVisible();
7965         R_View_UpdateEntityLighting();
7966 }
7967
7968 void R_SetupView(qboolean allowwaterclippingplane)
7969 {
7970         const float *customclipplane = NULL;
7971         float plane[4];
7972         if (r_refdef.view.useclipplane && allowwaterclippingplane)
7973         {
7974                 // LordHavoc: couldn't figure out how to make this approach the
7975                 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7976                 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7977                 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7978                         dist = r_refdef.view.clipplane.dist;
7979                 plane[0] = r_refdef.view.clipplane.normal[0];
7980                 plane[1] = r_refdef.view.clipplane.normal[1];
7981                 plane[2] = r_refdef.view.clipplane.normal[2];
7982                 plane[3] = dist;
7983                 customclipplane = plane;
7984         }
7985
7986         if (!r_refdef.view.useperspective)
7987                 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);
7988         else if (vid.stencil && r_useinfinitefarclip.integer)
7989                 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);
7990         else
7991                 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);
7992         R_SetViewport(&r_refdef.view.viewport);
7993 }
7994
7995 void R_EntityMatrix(const matrix4x4_t *matrix)
7996 {
7997         if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7998         {
7999                 gl_modelmatrixchanged = false;
8000                 gl_modelmatrix = *matrix;
8001                 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
8002                 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
8003                 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
8004                 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
8005                 CHECKGLERROR
8006                 switch(vid.renderpath)
8007                 {
8008                 case RENDERPATH_D3D9:
8009 #ifdef SUPPORTD3D
8010                         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
8011                         hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
8012 #endif
8013                         break;
8014                 case RENDERPATH_D3D10:
8015                         Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
8016                         break;
8017                 case RENDERPATH_D3D11:
8018                         Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
8019                         break;
8020                 case RENDERPATH_GL13:
8021                 case RENDERPATH_GL11:
8022                         qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8023                         break;
8024                 case RENDERPATH_SOFT:
8025                         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
8026                         DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
8027                         break;
8028                 case RENDERPATH_GL20:
8029                 case RENDERPATH_GLES2:
8030                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
8031                         if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
8032                         break;
8033                 }
8034         }
8035 }
8036
8037 void R_ResetViewRendering2D(void)
8038 {
8039         r_viewport_t viewport;
8040         DrawQ_Finish();
8041
8042         // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
8043         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);
8044         R_SetViewport(&viewport);
8045         GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
8046         GL_Color(1, 1, 1, 1);
8047         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8048         GL_BlendFunc(GL_ONE, GL_ZERO);
8049         GL_ScissorTest(false);
8050         GL_DepthMask(false);
8051         GL_DepthRange(0, 1);
8052         GL_DepthTest(false);
8053         GL_DepthFunc(GL_LEQUAL);
8054         R_EntityMatrix(&identitymatrix);
8055         R_Mesh_ResetTextureState();
8056         GL_PolygonOffset(0, 0);
8057         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8058         switch(vid.renderpath)
8059         {
8060         case RENDERPATH_GL11:
8061         case RENDERPATH_GL13:
8062         case RENDERPATH_GL20:
8063         case RENDERPATH_GLES2:
8064                 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8065                 break;
8066         case RENDERPATH_D3D9:
8067         case RENDERPATH_D3D10:
8068         case RENDERPATH_D3D11:
8069         case RENDERPATH_SOFT:
8070                 break;
8071         }
8072         GL_CullFace(GL_NONE);
8073 }
8074
8075 void R_ResetViewRendering3D(void)
8076 {
8077         DrawQ_Finish();
8078
8079         R_SetupView(true);
8080         GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8081         GL_Color(1, 1, 1, 1);
8082         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8083         GL_BlendFunc(GL_ONE, GL_ZERO);
8084         GL_ScissorTest(true);
8085         GL_DepthMask(true);
8086         GL_DepthRange(0, 1);
8087         GL_DepthTest(true);
8088         GL_DepthFunc(GL_LEQUAL);
8089         R_EntityMatrix(&identitymatrix);
8090         R_Mesh_ResetTextureState();
8091         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8092         R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8093         switch(vid.renderpath)
8094         {
8095         case RENDERPATH_GL11:
8096         case RENDERPATH_GL13:
8097         case RENDERPATH_GL20:
8098         case RENDERPATH_GLES2:
8099                 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8100                 break;
8101         case RENDERPATH_D3D9:
8102         case RENDERPATH_D3D10:
8103         case RENDERPATH_D3D11:
8104         case RENDERPATH_SOFT:
8105                 break;
8106         }
8107         GL_CullFace(r_refdef.view.cullface_back);
8108 }
8109
8110 /*
8111 ================
8112 R_RenderView_UpdateViewVectors
8113 ================
8114 */
8115 static void R_RenderView_UpdateViewVectors(void)
8116 {
8117         // break apart the view matrix into vectors for various purposes
8118         // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
8119         // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
8120         Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
8121         VectorNegate(r_refdef.view.left, r_refdef.view.right);
8122         // make an inverted copy of the view matrix for tracking sprites
8123         Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
8124 }
8125
8126 void R_RenderScene(void);
8127 void R_RenderWaterPlanes(void);
8128
8129 static void R_Water_StartFrame(void)
8130 {
8131         int i;
8132         int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
8133         r_waterstate_waterplane_t *p;
8134
8135         if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
8136                 return;
8137
8138         switch(vid.renderpath)
8139         {
8140         case RENDERPATH_GL20:
8141         case RENDERPATH_D3D9:
8142         case RENDERPATH_D3D10:
8143         case RENDERPATH_D3D11:
8144         case RENDERPATH_SOFT:
8145         case RENDERPATH_GLES2:
8146                 break;
8147         case RENDERPATH_GL13:
8148         case RENDERPATH_GL11:
8149                 return;
8150         }
8151
8152         // set waterwidth and waterheight to the water resolution that will be
8153         // used (often less than the screen resolution for faster rendering)
8154         waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
8155         waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
8156
8157         // calculate desired texture sizes
8158         // can't use water if the card does not support the texture size
8159         if (!r_water.integer || r_showsurfaces.integer)
8160                 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
8161         else if (vid.support.arb_texture_non_power_of_two)
8162         {
8163                 texturewidth = waterwidth;
8164                 textureheight = waterheight;
8165                 camerawidth = waterwidth;
8166                 cameraheight = waterheight;
8167         }
8168         else
8169         {
8170                 for (texturewidth   = 1;texturewidth   < waterwidth ;texturewidth   *= 2);
8171                 for (textureheight  = 1;textureheight  < waterheight;textureheight  *= 2);
8172                 for (camerawidth    = 1;camerawidth   <= waterwidth; camerawidth    *= 2); camerawidth  /= 2;
8173                 for (cameraheight   = 1;cameraheight  <= waterheight;cameraheight   *= 2); cameraheight /= 2;
8174         }
8175
8176         // allocate textures as needed
8177         if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
8178         {
8179                 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8180                 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
8181                 {
8182                         if (p->texture_refraction)
8183                                 R_FreeTexture(p->texture_refraction);
8184                         p->texture_refraction = NULL;
8185                         if (p->texture_reflection)
8186                                 R_FreeTexture(p->texture_reflection);
8187                         p->texture_reflection = NULL;
8188                         if (p->texture_camera)
8189                                 R_FreeTexture(p->texture_camera);
8190                         p->texture_camera = NULL;
8191                 }
8192                 memset(&r_waterstate, 0, sizeof(r_waterstate));
8193                 r_waterstate.texturewidth = texturewidth;
8194                 r_waterstate.textureheight = textureheight;
8195                 r_waterstate.camerawidth = camerawidth;
8196                 r_waterstate.cameraheight = cameraheight;
8197         }
8198
8199         if (r_waterstate.texturewidth)
8200         {
8201                 r_waterstate.enabled = true;
8202
8203                 // when doing a reduced render (HDR) we want to use a smaller area
8204                 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
8205                 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
8206
8207                 // set up variables that will be used in shader setup
8208                 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8209                 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8210                 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8211                 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8212         }
8213
8214         r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8215         r_waterstate.numwaterplanes = 0;
8216 }
8217
8218 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
8219 {
8220         int triangleindex, planeindex;
8221         const int *e;
8222         vec3_t vert[3];
8223         vec3_t normal;
8224         vec3_t center;
8225         mplane_t plane;
8226         r_waterstate_waterplane_t *p;
8227         texture_t *t = R_GetCurrentTexture(surface->texture);
8228
8229         // just use the first triangle with a valid normal for any decisions
8230         VectorClear(normal);
8231         for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
8232         {
8233                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
8234                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
8235                 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
8236                 TriangleNormal(vert[0], vert[1], vert[2], normal);
8237                 if (VectorLength2(normal) >= 0.001)
8238                         break;
8239         }
8240
8241         VectorCopy(normal, plane.normal);
8242         VectorNormalize(plane.normal);
8243         plane.dist = DotProduct(vert[0], plane.normal);
8244         PlaneClassify(&plane);
8245         if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
8246         {
8247                 // skip backfaces (except if nocullface is set)
8248                 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
8249                         return;
8250                 VectorNegate(plane.normal, plane.normal);
8251                 plane.dist *= -1;
8252                 PlaneClassify(&plane);
8253         }
8254
8255
8256         // find a matching plane if there is one
8257         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8258                 if(p->camera_entity == t->camera_entity)
8259                         if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
8260                                 break;
8261         if (planeindex >= r_waterstate.maxwaterplanes)
8262                 return; // nothing we can do, out of planes
8263
8264         // if this triangle does not fit any known plane rendered this frame, add one
8265         if (planeindex >= r_waterstate.numwaterplanes)
8266         {
8267                 // store the new plane
8268                 r_waterstate.numwaterplanes++;
8269                 p->plane = plane;
8270                 // clear materialflags and pvs
8271                 p->materialflags = 0;
8272                 p->pvsvalid = false;
8273                 p->camera_entity = t->camera_entity;
8274                 VectorCopy(surface->mins, p->mins);
8275                 VectorCopy(surface->maxs, p->maxs);
8276         }
8277         else
8278         {
8279                 // merge mins/maxs
8280                 p->mins[0] = min(p->mins[0], surface->mins[0]);
8281                 p->mins[1] = min(p->mins[1], surface->mins[1]);
8282                 p->mins[2] = min(p->mins[2], surface->mins[2]);
8283                 p->maxs[0] = max(p->maxs[0], surface->maxs[0]);
8284                 p->maxs[1] = max(p->maxs[1], surface->maxs[1]);
8285                 p->maxs[2] = max(p->maxs[2], surface->maxs[2]);
8286         }
8287         // merge this surface's materialflags into the waterplane
8288         p->materialflags |= t->currentmaterialflags;
8289         if(!(p->materialflags & MATERIALFLAG_CAMERA))
8290         {
8291                 // merge this surface's PVS into the waterplane
8292                 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
8293                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
8294                  && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
8295                 {
8296                         r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
8297                         p->pvsvalid = true;
8298                 }
8299         }
8300 }
8301
8302 static void R_Water_ProcessPlanes(void)
8303 {
8304         int myscissor[4];
8305         r_refdef_view_t originalview;
8306         r_refdef_view_t myview;
8307         int planeindex;
8308         r_waterstate_waterplane_t *p;
8309         vec3_t visorigin;
8310
8311         originalview = r_refdef.view;
8312
8313         // make sure enough textures are allocated
8314         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8315         {
8316                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8317                 {
8318                         if (!p->texture_refraction)
8319                                 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8320                         if (!p->texture_refraction)
8321                                 goto error;
8322                 }
8323                 else if (p->materialflags & MATERIALFLAG_CAMERA)
8324                 {
8325                         if (!p->texture_camera)
8326                                 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
8327                         if (!p->texture_camera)
8328                                 goto error;
8329                 }
8330
8331                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8332                 {
8333                         if (!p->texture_reflection)
8334                                 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8335                         if (!p->texture_reflection)
8336                                 goto error;
8337                 }
8338         }
8339
8340         // render views
8341         r_refdef.view = originalview;
8342         r_refdef.view.showdebug = false;
8343         r_refdef.view.width = r_waterstate.waterwidth;
8344         r_refdef.view.height = r_waterstate.waterheight;
8345         r_refdef.view.useclipplane = true;
8346         myview = r_refdef.view;
8347         r_waterstate.renderingscene = true;
8348         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8349         {
8350                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8351                 {
8352                         r_refdef.view = myview;
8353                         if(r_water_scissormode.integer)
8354                         {
8355                                 R_SetupView(true);
8356                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
8357                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
8358                         }
8359
8360                         // render reflected scene and copy into texture
8361                         Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
8362                         // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
8363                         Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
8364                         r_refdef.view.clipplane = p->plane;
8365
8366                         // reverse the cullface settings for this render
8367                         r_refdef.view.cullface_front = GL_FRONT;
8368                         r_refdef.view.cullface_back = GL_BACK;
8369                         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
8370                         {
8371                                 r_refdef.view.usecustompvs = true;
8372                                 if (p->pvsvalid)
8373                                         memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8374                                 else
8375                                         memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8376                         }
8377
8378                         R_ResetViewRendering3D();
8379                         R_ClearScreen(r_refdef.fogenabled);
8380                         if(r_water_scissormode.integer & 2)
8381                                 R_View_UpdateWithScissor(myscissor);
8382                         else
8383                                 R_View_Update();
8384                         if(r_water_scissormode.integer & 1)
8385                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
8386                         R_RenderScene();
8387
8388                         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);
8389                 }
8390
8391                 // render the normal view scene and copy into texture
8392                 // (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)
8393                 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8394                 {
8395                         r_refdef.view = myview;
8396                         if(r_water_scissormode.integer)
8397                         {
8398                                 R_SetupView(true);
8399                                 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
8400                                         continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
8401                         }
8402
8403                         r_waterstate.renderingrefraction = true;
8404
8405                         r_refdef.view.clipplane = p->plane;
8406                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8407                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8408
8409                         if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
8410                         {
8411                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8412                                 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
8413                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8414                                 R_RenderView_UpdateViewVectors();
8415                                 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
8416                                 {
8417                                         r_refdef.view.usecustompvs = true;
8418                                         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);
8419                                 }
8420                         }
8421
8422                         PlaneClassify(&r_refdef.view.clipplane);
8423
8424                         R_ResetViewRendering3D();
8425                         R_ClearScreen(r_refdef.fogenabled);
8426                         if(r_water_scissormode.integer & 2)
8427                                 R_View_UpdateWithScissor(myscissor);
8428                         else
8429                                 R_View_Update();
8430                         if(r_water_scissormode.integer & 1)
8431                                 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
8432                         R_RenderScene();
8433
8434                         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);
8435                         r_waterstate.renderingrefraction = false;
8436                 }
8437                 else if (p->materialflags & MATERIALFLAG_CAMERA)
8438                 {
8439                         r_refdef.view = myview;
8440
8441                         r_refdef.view.clipplane = p->plane;
8442                         VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8443                         r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8444
8445                         r_refdef.view.width = r_waterstate.camerawidth;
8446                         r_refdef.view.height = r_waterstate.cameraheight;
8447                         r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
8448                         r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
8449
8450                         if(p->camera_entity)
8451                         {
8452                                 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8453                                 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8454                         }
8455
8456                         // note: all of the view is used for displaying... so
8457                         // there is no use in scissoring
8458
8459                         // reverse the cullface settings for this render
8460                         r_refdef.view.cullface_front = GL_FRONT;
8461                         r_refdef.view.cullface_back = GL_BACK;
8462                         // also reverse the view matrix
8463                         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
8464                         R_RenderView_UpdateViewVectors();
8465                         if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
8466                         {
8467                                 r_refdef.view.usecustompvs = true;
8468                                 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);
8469                         }
8470                         
8471                         // camera needs no clipplane
8472                         r_refdef.view.useclipplane = false;
8473
8474                         PlaneClassify(&r_refdef.view.clipplane);
8475
8476                         R_ResetViewRendering3D();
8477                         R_ClearScreen(r_refdef.fogenabled);
8478                         R_View_Update();
8479                         R_RenderScene();
8480
8481                         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);
8482                         r_waterstate.renderingrefraction = false;
8483                 }
8484
8485         }
8486         r_waterstate.renderingscene = false;
8487         r_refdef.view = originalview;
8488         R_ResetViewRendering3D();
8489         R_ClearScreen(r_refdef.fogenabled);
8490         R_View_Update();
8491         return;
8492 error:
8493         r_refdef.view = originalview;
8494         r_waterstate.renderingscene = false;
8495         Cvar_SetValueQuick(&r_water, 0);
8496         Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed!  Turned off r_water.\n");
8497         return;
8498 }
8499
8500 void R_Bloom_StartFrame(void)
8501 {
8502         int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8503
8504         switch(vid.renderpath)
8505         {
8506         case RENDERPATH_GL20:
8507         case RENDERPATH_D3D9:
8508         case RENDERPATH_D3D10:
8509         case RENDERPATH_D3D11:
8510         case RENDERPATH_SOFT:
8511         case RENDERPATH_GLES2:
8512                 break;
8513         case RENDERPATH_GL13:
8514         case RENDERPATH_GL11:
8515                 return;
8516         }
8517
8518         // set bloomwidth and bloomheight to the bloom resolution that will be
8519         // used (often less than the screen resolution for faster rendering)
8520         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8521         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8522         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8523         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8524         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8525
8526         // calculate desired texture sizes
8527         if (vid.support.arb_texture_non_power_of_two)
8528         {
8529                 screentexturewidth = r_refdef.view.width;
8530                 screentextureheight = r_refdef.view.height;
8531                 bloomtexturewidth = r_bloomstate.bloomwidth;
8532                 bloomtextureheight = r_bloomstate.bloomheight;
8533         }
8534         else
8535         {
8536                 for (screentexturewidth  = 1;screentexturewidth  < vid.width               ;screentexturewidth  *= 2);
8537                 for (screentextureheight = 1;screentextureheight < vid.height              ;screentextureheight *= 2);
8538                 for (bloomtexturewidth   = 1;bloomtexturewidth   < r_bloomstate.bloomwidth ;bloomtexturewidth   *= 2);
8539                 for (bloomtextureheight  = 1;bloomtextureheight  < r_bloomstate.bloomheight;bloomtextureheight  *= 2);
8540         }
8541
8542         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))
8543         {
8544                 Cvar_SetValueQuick(&r_hdr, 0);
8545                 Cvar_SetValueQuick(&r_bloom, 0);
8546                 Cvar_SetValueQuick(&r_motionblur, 0);
8547                 Cvar_SetValueQuick(&r_damageblur, 0);
8548         }
8549
8550         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)))
8551                 screentexturewidth = screentextureheight = 0;
8552         if (!r_hdr.integer && !r_bloom.integer)
8553                 bloomtexturewidth = bloomtextureheight = 0;
8554
8555         // allocate textures as needed
8556         if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8557         {
8558                 if (r_bloomstate.texture_screen)
8559                         R_FreeTexture(r_bloomstate.texture_screen);
8560                 r_bloomstate.texture_screen = NULL;
8561                 r_bloomstate.screentexturewidth = screentexturewidth;
8562                 r_bloomstate.screentextureheight = screentextureheight;
8563                 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8564                         r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
8565         }
8566         if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8567         {
8568                 if (r_bloomstate.texture_bloom)
8569                         R_FreeTexture(r_bloomstate.texture_bloom);
8570                 r_bloomstate.texture_bloom = NULL;
8571                 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8572                 r_bloomstate.bloomtextureheight = bloomtextureheight;
8573                 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8574                         r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8575         }
8576
8577         // when doing a reduced render (HDR) we want to use a smaller area
8578         r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8579         r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8580         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8581         r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8582         r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8583
8584         // set up a texcoord array for the full resolution screen image
8585         // (we have to keep this around to copy back during final render)
8586         r_bloomstate.screentexcoord2f[0] = 0;
8587         r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8588         r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8589         r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height    / (float)r_bloomstate.screentextureheight;
8590         r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width     / (float)r_bloomstate.screentexturewidth;
8591         r_bloomstate.screentexcoord2f[5] = 0;
8592         r_bloomstate.screentexcoord2f[6] = 0;
8593         r_bloomstate.screentexcoord2f[7] = 0;
8594
8595         // set up a texcoord array for the reduced resolution bloom image
8596         // (which will be additive blended over the screen image)
8597         r_bloomstate.bloomtexcoord2f[0] = 0;
8598         r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8599         r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8600         r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8601         r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth  / (float)r_bloomstate.bloomtexturewidth;
8602         r_bloomstate.bloomtexcoord2f[5] = 0;
8603         r_bloomstate.bloomtexcoord2f[6] = 0;
8604         r_bloomstate.bloomtexcoord2f[7] = 0;
8605
8606         switch(vid.renderpath)
8607         {
8608         case RENDERPATH_GL11:
8609         case RENDERPATH_GL13:
8610         case RENDERPATH_GL20:
8611         case RENDERPATH_SOFT:
8612         case RENDERPATH_GLES2:
8613                 break;
8614         case RENDERPATH_D3D9:
8615         case RENDERPATH_D3D10:
8616         case RENDERPATH_D3D11:
8617                 {
8618                         int i;
8619                         for (i = 0;i < 4;i++)
8620                         {
8621                                 r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
8622                                 r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
8623                                 r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
8624                                 r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
8625                         }
8626                 }
8627                 break;
8628         }
8629
8630         if (r_hdr.integer || r_bloom.integer)
8631         {
8632                 r_bloomstate.enabled = true;
8633                 r_bloomstate.hdr = r_hdr.integer != 0;
8634         }
8635
8636         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);
8637 }
8638
8639 void R_Bloom_CopyBloomTexture(float colorscale)
8640 {
8641         r_refdef.stats.bloom++;
8642
8643         // scale down screen texture to the bloom texture size
8644         CHECKGLERROR
8645         R_SetViewport(&r_bloomstate.viewport);
8646         GL_BlendFunc(GL_ONE, GL_ZERO);
8647         GL_Color(colorscale, colorscale, colorscale, 1);
8648         // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8649         switch(vid.renderpath)
8650         {
8651         case RENDERPATH_GL11:
8652         case RENDERPATH_GL13:
8653         case RENDERPATH_GL20:
8654         case RENDERPATH_SOFT:
8655         case RENDERPATH_GLES2:
8656                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8657                 break;
8658         case RENDERPATH_D3D9:
8659         case RENDERPATH_D3D10:
8660         case RENDERPATH_D3D11:
8661                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8662                 break;
8663         }
8664         // TODO: do boxfilter scale-down in shader?
8665         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8666         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8667         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8668
8669         // we now have a bloom image in the framebuffer
8670         // copy it into the bloom image texture for later processing
8671         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);
8672         r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8673 }
8674
8675 void R_Bloom_CopyHDRTexture(void)
8676 {
8677         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);
8678         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8679 }
8680
8681 void R_Bloom_MakeTexture(void)
8682 {
8683         int x, range, dir;
8684         float xoffset, yoffset, r, brighten;
8685
8686         r_refdef.stats.bloom++;
8687
8688         R_ResetViewRendering2D();
8689
8690         // we have a bloom image in the framebuffer
8691         CHECKGLERROR
8692         R_SetViewport(&r_bloomstate.viewport);
8693
8694         for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8695         {
8696                 x *= 2;
8697                 r = bound(0, r_bloom_colorexponent.value / x, 1);
8698                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8699                 GL_Color(r,r,r,1);
8700                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8701                 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8702                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8703                 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8704
8705                 // copy the vertically blurred bloom view to a texture
8706                 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);
8707                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8708         }
8709
8710         range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8711         brighten = r_bloom_brighten.value;
8712         if (r_hdr.integer)
8713                 brighten *= r_hdr_range.value;
8714         brighten = sqrt(brighten);
8715         if(range >= 1)
8716                 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8717         R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8718
8719         for (dir = 0;dir < 2;dir++)
8720         {
8721                 // blend on at multiple vertical offsets to achieve a vertical blur
8722                 // TODO: do offset blends using GLSL
8723                 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8724                 GL_BlendFunc(GL_ONE, GL_ZERO);
8725                 for (x = -range;x <= range;x++)
8726                 {
8727                         if (!dir){xoffset = 0;yoffset = x;}
8728                         else {xoffset = x;yoffset = 0;}
8729                         xoffset /= (float)r_bloomstate.bloomtexturewidth;
8730                         yoffset /= (float)r_bloomstate.bloomtextureheight;
8731                         // compute a texcoord array with the specified x and y offset
8732                         r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8733                         r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8734                         r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8735                         r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8736                         r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8737                         r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8738                         r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8739                         r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8740                         // this r value looks like a 'dot' particle, fading sharply to
8741                         // black at the edges
8742                         // (probably not realistic but looks good enough)
8743                         //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8744                         //r = brighten/(range*2+1);
8745                         r = brighten / (range * 2 + 1);
8746                         if(range >= 1)
8747                                 r *= (1 - x*x/(float)(range*range));
8748                         GL_Color(r, r, r, 1);
8749                         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8750                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8751                         r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8752                         GL_BlendFunc(GL_ONE, GL_ONE);
8753                 }
8754
8755                 // copy the vertically blurred bloom view to a texture
8756                 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);
8757                 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8758         }
8759 }
8760
8761 void R_HDR_RenderBloomTexture(void)
8762 {
8763         int oldwidth, oldheight;
8764         float oldcolorscale;
8765         qboolean oldwaterstate;
8766
8767         oldwaterstate = r_waterstate.enabled;
8768         oldcolorscale = r_refdef.view.colorscale;
8769         oldwidth = r_refdef.view.width;
8770         oldheight = r_refdef.view.height;
8771         r_refdef.view.width = r_bloomstate.bloomwidth;
8772         r_refdef.view.height = r_bloomstate.bloomheight;
8773
8774         if(r_hdr.integer < 2)
8775                 r_waterstate.enabled = false;
8776
8777         // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer?  it might improve SLI performance.
8778         // TODO: add exposure compensation features
8779         // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8780
8781         r_refdef.view.showdebug = false;
8782         r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8783
8784         R_ResetViewRendering3D();
8785
8786         R_ClearScreen(r_refdef.fogenabled);
8787         if (r_timereport_active)
8788                 R_TimeReport("HDRclear");
8789
8790         R_View_Update();
8791         if (r_timereport_active)
8792                 R_TimeReport("visibility");
8793
8794         // only do secondary renders with HDR if r_hdr is 2 or higher
8795         r_waterstate.numwaterplanes = 0;
8796         if (r_waterstate.enabled)
8797                 R_RenderWaterPlanes();
8798
8799         r_refdef.view.showdebug = true;
8800         R_RenderScene();
8801         r_waterstate.numwaterplanes = 0;
8802
8803         R_ResetViewRendering2D();
8804
8805         R_Bloom_CopyHDRTexture();
8806         R_Bloom_MakeTexture();
8807
8808         // restore the view settings
8809         r_waterstate.enabled = oldwaterstate;
8810         r_refdef.view.width = oldwidth;
8811         r_refdef.view.height = oldheight;
8812         r_refdef.view.colorscale = oldcolorscale;
8813
8814         R_ResetViewRendering3D();
8815
8816         R_ClearScreen(r_refdef.fogenabled);
8817         if (r_timereport_active)
8818                 R_TimeReport("viewclear");
8819 }
8820
8821 static void R_BlendView(void)
8822 {
8823         unsigned int permutation;
8824         float uservecs[4][4];
8825
8826         switch (vid.renderpath)
8827         {
8828         case RENDERPATH_GL20:
8829         case RENDERPATH_D3D9:
8830         case RENDERPATH_D3D10:
8831         case RENDERPATH_D3D11:
8832         case RENDERPATH_SOFT:
8833         case RENDERPATH_GLES2:
8834                 permutation =
8835                           (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8836                         | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8837                         | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8838                         | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8839                         | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8840
8841                 if (r_bloomstate.texture_screen)
8842                 {
8843                         // make sure the buffer is available
8844                         if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8845
8846                         R_ResetViewRendering2D();
8847
8848                         if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8849                         {
8850                                 // declare variables
8851                                 float speed;
8852                                 static float avgspeed;
8853
8854                                 speed = VectorLength(cl.movement_velocity);
8855
8856                                 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8857                                 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8858
8859                                 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8860                                 speed = bound(0, speed, 1);
8861                                 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8862
8863                                 // calculate values into a standard alpha
8864                                 cl.motionbluralpha = 1 - exp(-
8865                                                 (
8866                                                  (r_motionblur.value * speed / 80)
8867                                                  +
8868                                                  (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8869                                                 )
8870                                                 /
8871                                                 max(0.0001, cl.time - cl.oldtime) // fps independent
8872                                            );
8873
8874                                 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8875                                 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8876                                 // apply the blur
8877                                 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8878                                 {
8879                                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8880                                         GL_Color(1, 1, 1, cl.motionbluralpha);
8881                                         switch(vid.renderpath)
8882                                         {
8883                                         case RENDERPATH_GL11:
8884                                         case RENDERPATH_GL13:
8885                                         case RENDERPATH_GL20:
8886                                         case RENDERPATH_SOFT:
8887                                         case RENDERPATH_GLES2:
8888                                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8889                                                 break;
8890                                         case RENDERPATH_D3D9:
8891                                         case RENDERPATH_D3D10:
8892                                         case RENDERPATH_D3D11:
8893                                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8894                                                 break;
8895                                         }
8896                                         R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8897                                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8898                                         r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8899                                 }
8900                         }
8901
8902                         // copy view into the screen texture
8903                         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);
8904                         r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8905                 }
8906                 else if (!r_bloomstate.texture_bloom)
8907                 {
8908                         // we may still have to do view tint...
8909                         if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8910                         {
8911                                 // apply a color tint to the whole view
8912                                 R_ResetViewRendering2D();
8913                                 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8914                                 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8915                                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8916                                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8917                                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8918                         }
8919                         break; // no screen processing, no bloom, skip it
8920                 }
8921
8922                 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8923                 {
8924                         // render simple bloom effect
8925                         // copy the screen and shrink it and darken it for the bloom process
8926                         R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8927                         // make the bloom texture
8928                         R_Bloom_MakeTexture();
8929                 }
8930
8931 #if _MSC_VER >= 1400
8932 #define sscanf sscanf_s
8933 #endif
8934                 memset(uservecs, 0, sizeof(uservecs));
8935                 if (r_glsl_postprocess_uservec1_enable.integer)
8936                         sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8937                 if (r_glsl_postprocess_uservec2_enable.integer)
8938                         sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8939                 if (r_glsl_postprocess_uservec3_enable.integer)
8940                         sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8941                 if (r_glsl_postprocess_uservec4_enable.integer)
8942                         sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8943
8944                 R_ResetViewRendering2D();
8945                 GL_Color(1, 1, 1, 1);
8946                 GL_BlendFunc(GL_ONE, GL_ZERO);
8947
8948                 switch(vid.renderpath)
8949                 {
8950                 case RENDERPATH_GL20:
8951                 case RENDERPATH_GLES2:
8952                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8953                         R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8954                         if (r_glsl_permutation->tex_Texture_First           >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First     , r_bloomstate.texture_screen);
8955                         if (r_glsl_permutation->tex_Texture_Second          >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second    , r_bloomstate.texture_bloom );
8956                         if (r_glsl_permutation->tex_Texture_GammaRamps      >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps       );
8957                         if (r_glsl_permutation->loc_ViewTintColor           >= 0) qglUniform4f(r_glsl_permutation->loc_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8958                         if (r_glsl_permutation->loc_PixelSize               >= 0) qglUniform2f(r_glsl_permutation->loc_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8959                         if (r_glsl_permutation->loc_UserVec1                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8960                         if (r_glsl_permutation->loc_UserVec2                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8961                         if (r_glsl_permutation->loc_UserVec3                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8962                         if (r_glsl_permutation->loc_UserVec4                >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8963                         if (r_glsl_permutation->loc_Saturation              >= 0) qglUniform1f(r_glsl_permutation->loc_Saturation        , r_glsl_saturation.value);
8964                         if (r_glsl_permutation->loc_PixelToScreenTexCoord   >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8965                         if (r_glsl_permutation->loc_BloomColorSubtract      >= 0) qglUniform4f(r_glsl_permutation->loc_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
8966                         break;
8967                 case RENDERPATH_D3D9:
8968 #ifdef SUPPORTD3D
8969                         // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8970                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8971                         R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
8972                         R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
8973                         R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
8974                         R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
8975                         hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor        , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8976                         hlslPSSetParameter2f(D3DPSREGISTER_PixelSize            , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8977                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec1             , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8978                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec2             , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8979                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec3             , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8980                         hlslPSSetParameter4f(D3DPSREGISTER_UserVec4             , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8981                         hlslPSSetParameter1f(D3DPSREGISTER_Saturation           , r_glsl_saturation.value);
8982                         hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
8983                         hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
8984 #endif
8985                         break;
8986                 case RENDERPATH_D3D10:
8987                         Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
8988                         break;
8989                 case RENDERPATH_D3D11:
8990                         Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
8991                         break;
8992                 case RENDERPATH_SOFT:
8993                         R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8994                         R_SetupShader_SetPermutationSoft(SHADERMODE_POSTPROCESS, permutation);
8995                         R_Mesh_TexBind(GL20TU_FIRST     , r_bloomstate.texture_screen);
8996                         R_Mesh_TexBind(GL20TU_SECOND    , r_bloomstate.texture_bloom );
8997                         R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps       );
8998                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ViewTintColor     , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8999                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelSize         , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9000                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec1          , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
9001                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec2          , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
9002                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec3          , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
9003                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec4          , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
9004                         DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Saturation        , r_glsl_saturation.value);
9005                         DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
9006                         DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_BloomColorSubtract   , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9007                         break;
9008                 default:
9009                         break;
9010                 }
9011                 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9012                 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9013                 break;
9014         case RENDERPATH_GL13:
9015         case RENDERPATH_GL11:
9016                 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9017                 {
9018                         // apply a color tint to the whole view
9019                         R_ResetViewRendering2D();
9020                         GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9021                         R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9022                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9023                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9024                         R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9025                 }
9026                 break;
9027         }
9028 }
9029
9030 matrix4x4_t r_waterscrollmatrix;
9031
9032 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
9033 {
9034         if (r_refdef.fog_density)
9035         {
9036                 r_refdef.fogcolor[0] = r_refdef.fog_red;
9037                 r_refdef.fogcolor[1] = r_refdef.fog_green;
9038                 r_refdef.fogcolor[2] = r_refdef.fog_blue;
9039
9040                 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
9041                 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
9042                 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
9043                 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
9044
9045                 {
9046                         vec3_t fogvec;
9047                         VectorCopy(r_refdef.fogcolor, fogvec);
9048                         //   color.rgb *= ContrastBoost * SceneBrightness;
9049                         VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
9050                         r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
9051                         r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
9052                         r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
9053                 }
9054         }
9055 }
9056
9057 void R_UpdateVariables(void)
9058 {
9059         R_Textures_Frame();
9060
9061         r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
9062
9063         r_refdef.farclip = r_farclip_base.value;
9064         if (r_refdef.scene.worldmodel)
9065                 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
9066         r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
9067
9068         if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
9069                 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
9070         r_refdef.polygonfactor = 0;
9071         r_refdef.polygonoffset = 0;
9072         r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9073         r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9074
9075         r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
9076         r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
9077         r_refdef.scene.rtdlight = r_shadow_realtime_dlight.integer != 0 && !gl_flashblend.integer && r_dynamic.integer;
9078         r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
9079         r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
9080         if (FAKELIGHT_ENABLED)
9081         {
9082                 r_refdef.lightmapintensity *= r_fakelight_intensity.value;
9083         }
9084         if (r_showsurfaces.integer)
9085         {
9086                 r_refdef.scene.rtworld = false;
9087                 r_refdef.scene.rtworldshadows = false;
9088                 r_refdef.scene.rtdlight = false;
9089                 r_refdef.scene.rtdlightshadows = false;
9090                 r_refdef.lightmapintensity = 0;
9091         }
9092
9093         if (gamemode == GAME_NEHAHRA)
9094         {
9095                 if (gl_fogenable.integer)
9096                 {
9097                         r_refdef.oldgl_fogenable = true;
9098                         r_refdef.fog_density = gl_fogdensity.value;
9099                         r_refdef.fog_red = gl_fogred.value;
9100                         r_refdef.fog_green = gl_foggreen.value;
9101                         r_refdef.fog_blue = gl_fogblue.value;
9102                         r_refdef.fog_alpha = 1;
9103                         r_refdef.fog_start = 0;
9104                         r_refdef.fog_end = gl_skyclip.value;
9105                         r_refdef.fog_height = 1<<30;
9106                         r_refdef.fog_fadedepth = 128;
9107                 }
9108                 else if (r_refdef.oldgl_fogenable)
9109                 {
9110                         r_refdef.oldgl_fogenable = false;
9111                         r_refdef.fog_density = 0;
9112                         r_refdef.fog_red = 0;
9113                         r_refdef.fog_green = 0;
9114                         r_refdef.fog_blue = 0;
9115                         r_refdef.fog_alpha = 0;
9116                         r_refdef.fog_start = 0;
9117                         r_refdef.fog_end = 0;
9118                         r_refdef.fog_height = 1<<30;
9119                         r_refdef.fog_fadedepth = 128;
9120                 }
9121         }
9122
9123         r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
9124         r_refdef.fog_start = max(0, r_refdef.fog_start);
9125         r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
9126
9127         // R_UpdateFogColor(); // why? R_RenderScene does it anyway
9128
9129         if (r_refdef.fog_density && r_drawfog.integer)
9130         {
9131                 r_refdef.fogenabled = true;
9132                 // this is the point where the fog reaches 0.9986 alpha, which we
9133                 // consider a good enough cutoff point for the texture
9134                 // (0.9986 * 256 == 255.6)
9135                 if (r_fog_exp2.integer)
9136                         r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
9137                 else
9138                         r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
9139                 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
9140                 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
9141                 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
9142                 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
9143                         R_BuildFogHeightTexture();
9144                 // fog color was already set
9145                 // update the fog texture
9146                 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)
9147                         R_BuildFogTexture();
9148                 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
9149                 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
9150         }
9151         else
9152                 r_refdef.fogenabled = false;
9153
9154         switch(vid.renderpath)
9155         {
9156         case RENDERPATH_GL20:
9157         case RENDERPATH_D3D9:
9158         case RENDERPATH_D3D10:
9159         case RENDERPATH_D3D11:
9160         case RENDERPATH_SOFT:
9161         case RENDERPATH_GLES2:
9162                 if(v_glslgamma.integer && !vid_gammatables_trivial)
9163                 {
9164                         if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
9165                         {
9166                                 // build GLSL gamma texture
9167 #define RAMPWIDTH 256
9168                                 unsigned short ramp[RAMPWIDTH * 3];
9169                                 unsigned char rampbgr[RAMPWIDTH][4];
9170                                 int i;
9171
9172                                 r_texture_gammaramps_serial = vid_gammatables_serial;
9173
9174                                 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
9175                                 for(i = 0; i < RAMPWIDTH; ++i)
9176                                 {
9177                                         rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9178                                         rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9179                                         rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
9180                                         rampbgr[i][3] = 0;
9181                                 }
9182                                 if (r_texture_gammaramps)
9183                                 {
9184                                         R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, 0, RAMPWIDTH, 1, 1);
9185                                 }
9186                                 else
9187                                 {
9188                                         r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
9189                                 }
9190                         }
9191                 }
9192                 else
9193                 {
9194                         // remove GLSL gamma texture
9195                 }
9196                 break;
9197         case RENDERPATH_GL13:
9198         case RENDERPATH_GL11:
9199                 break;
9200         }
9201 }
9202
9203 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
9204 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
9205 /*
9206 ================
9207 R_SelectScene
9208 ================
9209 */
9210 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
9211         if( scenetype != r_currentscenetype ) {
9212                 // store the old scenetype
9213                 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
9214                 r_currentscenetype = scenetype;
9215                 // move in the new scene
9216                 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
9217         }
9218 }
9219
9220 /*
9221 ================
9222 R_GetScenePointer
9223 ================
9224 */
9225 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
9226 {
9227         // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
9228         if( scenetype == r_currentscenetype ) {
9229                 return &r_refdef.scene;
9230         } else {
9231                 return &r_scenes_store[ scenetype ];
9232         }
9233 }
9234
9235 /*
9236 ================
9237 R_RenderView
9238 ================
9239 */
9240 int dpsoftrast_test;
9241 void R_RenderView(void)
9242 {
9243         matrix4x4_t originalmatrix = r_refdef.view.matrix, offsetmatrix;
9244
9245         dpsoftrast_test = r_test.integer;
9246
9247         if (r_timereport_active)
9248                 R_TimeReport("start");
9249         r_textureframe++; // used only by R_GetCurrentTexture
9250         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
9251
9252         if(R_CompileShader_CheckStaticParms())
9253                 R_GLSL_Restart_f();
9254
9255         if (!r_drawentities.integer)
9256                 r_refdef.scene.numentities = 0;
9257
9258         R_AnimCache_ClearCache();
9259         R_FrameData_NewFrame();
9260
9261         /* adjust for stereo display */
9262         if(R_Stereo_Active())
9263         {
9264                 Matrix4x4_CreateFromQuakeEntity(&offsetmatrix, 0, r_stereo_separation.value * (0.5f - r_stereo_side), 0, 0, r_stereo_angle.value * (0.5f - r_stereo_side), 0, 1);
9265                 Matrix4x4_Concat(&r_refdef.view.matrix, &originalmatrix, &offsetmatrix);
9266         }
9267
9268         if (r_refdef.view.isoverlay)
9269         {
9270                 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
9271                 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
9272                 R_TimeReport("depthclear");
9273
9274                 r_refdef.view.showdebug = false;
9275
9276                 r_waterstate.enabled = false;
9277                 r_waterstate.numwaterplanes = 0;
9278
9279                 R_RenderScene();
9280
9281                 r_refdef.view.matrix = originalmatrix;
9282
9283                 CHECKGLERROR
9284                 return;
9285         }
9286
9287         if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
9288         {
9289                 r_refdef.view.matrix = originalmatrix;
9290                 return; //Host_Error ("R_RenderView: NULL worldmodel");
9291         }
9292
9293         r_refdef.view.colorscale = r_hdr_scenebrightness.value * r_hdr_irisadaptation_value.value;
9294
9295         R_RenderView_UpdateViewVectors();
9296
9297         R_Shadow_UpdateWorldLightSelection();
9298
9299         R_Bloom_StartFrame();
9300         R_Water_StartFrame();
9301
9302         CHECKGLERROR
9303         if (r_timereport_active)
9304                 R_TimeReport("viewsetup");
9305
9306         R_ResetViewRendering3D();
9307
9308         if (r_refdef.view.clear || r_refdef.fogenabled)
9309         {
9310                 R_ClearScreen(r_refdef.fogenabled);
9311                 if (r_timereport_active)
9312                         R_TimeReport("viewclear");
9313         }
9314         r_refdef.view.clear = true;
9315
9316         // this produces a bloom texture to be used in R_BlendView() later
9317         if (r_hdr.integer && r_bloomstate.bloomwidth)
9318         {
9319                 R_HDR_RenderBloomTexture();
9320                 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
9321                 r_textureframe++; // used only by R_GetCurrentTexture
9322         }
9323
9324         r_refdef.view.showdebug = true;
9325
9326         R_View_Update();
9327         if (r_timereport_active)
9328                 R_TimeReport("visibility");
9329
9330         r_waterstate.numwaterplanes = 0;
9331         if (r_waterstate.enabled)
9332                 R_RenderWaterPlanes();
9333
9334         R_RenderScene();
9335         r_waterstate.numwaterplanes = 0;
9336
9337         R_BlendView();
9338         if (r_timereport_active)
9339                 R_TimeReport("blendview");
9340
9341         GL_Scissor(0, 0, vid.width, vid.height);
9342         GL_ScissorTest(false);
9343
9344         r_refdef.view.matrix = originalmatrix;
9345
9346         CHECKGLERROR
9347 }
9348
9349 void R_RenderWaterPlanes(void)
9350 {
9351         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
9352         {
9353                 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
9354                 if (r_timereport_active)
9355                         R_TimeReport("waterworld");
9356         }
9357
9358         // don't let sound skip if going slow
9359         if (r_refdef.scene.extraupdate)
9360                 S_ExtraUpdate ();
9361
9362         R_DrawModelsAddWaterPlanes();
9363         if (r_timereport_active)
9364                 R_TimeReport("watermodels");
9365
9366         if (r_waterstate.numwaterplanes)
9367         {
9368                 R_Water_ProcessPlanes();
9369                 if (r_timereport_active)
9370                         R_TimeReport("waterscenes");
9371         }
9372 }
9373
9374 extern void R_DrawLightningBeams (void);
9375 extern void VM_CL_AddPolygonsToMeshQueue (void);
9376 extern void R_DrawPortals (void);
9377 extern cvar_t cl_locs_show;
9378 static void R_DrawLocs(void);
9379 static void R_DrawEntityBBoxes(void);
9380 static void R_DrawModelDecals(void);
9381 extern void R_DrawModelShadows(void);
9382 extern void R_DrawModelShadowMaps(void);
9383 extern cvar_t cl_decals_newsystem;
9384 extern qboolean r_shadow_usingdeferredprepass;
9385 void R_RenderScene(void)
9386 {
9387         qboolean shadowmapping = false;
9388
9389         if (r_timereport_active)
9390                 R_TimeReport("beginscene");
9391
9392         r_refdef.stats.renders++;
9393
9394         R_UpdateFogColor();
9395
9396         // don't let sound skip if going slow
9397         if (r_refdef.scene.extraupdate)
9398                 S_ExtraUpdate ();
9399
9400         R_MeshQueue_BeginScene();
9401
9402         R_SkyStartFrame();
9403
9404         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);
9405
9406         if (r_timereport_active)
9407                 R_TimeReport("skystartframe");
9408
9409         if (cl.csqc_vidvars.drawworld)
9410         {
9411                 // don't let sound skip if going slow
9412                 if (r_refdef.scene.extraupdate)
9413                         S_ExtraUpdate ();
9414
9415                 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
9416                 {
9417                         r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
9418                         if (r_timereport_active)
9419                                 R_TimeReport("worldsky");
9420                 }
9421
9422                 if (R_DrawBrushModelsSky() && r_timereport_active)
9423                         R_TimeReport("bmodelsky");
9424
9425                 if (skyrendermasked && skyrenderlater)
9426                 {
9427                         // we have to force off the water clipping plane while rendering sky
9428                         R_SetupView(false);
9429                         R_Sky();
9430                         R_SetupView(true);
9431                         if (r_timereport_active)
9432                                 R_TimeReport("sky");
9433                 }
9434         }
9435
9436         R_AnimCache_CacheVisibleEntities();
9437         if (r_timereport_active)
9438                 R_TimeReport("animation");
9439
9440         R_Shadow_PrepareLights();
9441         if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
9442                 R_Shadow_PrepareModelShadows();
9443         if (r_timereport_active)
9444                 R_TimeReport("preparelights");
9445
9446         if (R_Shadow_ShadowMappingEnabled())
9447                 shadowmapping = true;
9448
9449         if (r_shadow_usingdeferredprepass)
9450                 R_Shadow_DrawPrepass();
9451
9452         if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
9453         {
9454                 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
9455                 if (r_timereport_active)
9456                         R_TimeReport("worlddepth");
9457         }
9458         if (r_depthfirst.integer >= 2)
9459         {
9460                 R_DrawModelsDepth();
9461                 if (r_timereport_active)
9462                         R_TimeReport("modeldepth");
9463         }
9464
9465         if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
9466         {
9467                 R_DrawModelShadowMaps();
9468                 R_ResetViewRendering3D();
9469                 // don't let sound skip if going slow
9470                 if (r_refdef.scene.extraupdate)
9471                         S_ExtraUpdate ();
9472         }
9473
9474         if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
9475         {
9476                 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
9477                 if (r_timereport_active)
9478                         R_TimeReport("world");
9479         }
9480
9481         // don't let sound skip if going slow
9482         if (r_refdef.scene.extraupdate)
9483                 S_ExtraUpdate ();
9484
9485         R_DrawModels();
9486         if (r_timereport_active)
9487                 R_TimeReport("models");
9488
9489         // don't let sound skip if going slow
9490         if (r_refdef.scene.extraupdate)
9491                 S_ExtraUpdate ();
9492
9493         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9494         {
9495                 R_DrawModelShadows();
9496                 R_ResetViewRendering3D();
9497                 // don't let sound skip if going slow
9498                 if (r_refdef.scene.extraupdate)
9499                         S_ExtraUpdate ();
9500         }
9501
9502         if (!r_shadow_usingdeferredprepass)
9503         {
9504                 R_Shadow_DrawLights();
9505                 if (r_timereport_active)
9506                         R_TimeReport("rtlights");
9507         }
9508
9509         // don't let sound skip if going slow
9510         if (r_refdef.scene.extraupdate)
9511                 S_ExtraUpdate ();
9512
9513         if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9514         {
9515                 R_DrawModelShadows();
9516                 R_ResetViewRendering3D();
9517                 // don't let sound skip if going slow
9518                 if (r_refdef.scene.extraupdate)
9519                         S_ExtraUpdate ();
9520         }
9521
9522         if (cl.csqc_vidvars.drawworld)
9523         {
9524                 if (cl_decals_newsystem.integer)
9525                 {
9526                         R_DrawModelDecals();
9527                         if (r_timereport_active)
9528                                 R_TimeReport("modeldecals");
9529                 }
9530                 else
9531                 {
9532                         R_DrawDecals();
9533                         if (r_timereport_active)
9534                                 R_TimeReport("decals");
9535                 }
9536
9537                 R_DrawParticles();
9538                 if (r_timereport_active)
9539                         R_TimeReport("particles");
9540
9541                 R_DrawExplosions();
9542                 if (r_timereport_active)
9543                         R_TimeReport("explosions");
9544
9545                 R_DrawLightningBeams();
9546                 if (r_timereport_active)
9547                         R_TimeReport("lightning");
9548         }
9549
9550         VM_CL_AddPolygonsToMeshQueue();
9551
9552         if (r_refdef.view.showdebug)
9553         {
9554                 if (cl_locs_show.integer)
9555                 {
9556                         R_DrawLocs();
9557                         if (r_timereport_active)
9558                                 R_TimeReport("showlocs");
9559                 }
9560
9561                 if (r_drawportals.integer)
9562                 {
9563                         R_DrawPortals();
9564                         if (r_timereport_active)
9565                                 R_TimeReport("portals");
9566                 }
9567
9568                 if (r_showbboxes.value > 0)
9569                 {
9570                         R_DrawEntityBBoxes();
9571                         if (r_timereport_active)
9572                                 R_TimeReport("bboxes");
9573                 }
9574         }
9575
9576         R_MeshQueue_RenderTransparent();
9577         if (r_timereport_active)
9578                 R_TimeReport("drawtrans");
9579
9580         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))
9581         {
9582                 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9583                 if (r_timereport_active)
9584                         R_TimeReport("worlddebug");
9585                 R_DrawModelsDebug();
9586                 if (r_timereport_active)
9587                         R_TimeReport("modeldebug");
9588         }
9589
9590         if (cl.csqc_vidvars.drawworld)
9591         {
9592                 R_Shadow_DrawCoronas();
9593                 if (r_timereport_active)
9594                         R_TimeReport("coronas");
9595         }
9596
9597 #if 0
9598         {
9599                 GL_DepthTest(false);
9600                 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
9601                 GL_Color(1, 1, 1, 1);
9602                 qglBegin(GL_POLYGON);
9603                 qglVertex3f(r_refdef.view.frustumcorner[0][0], r_refdef.view.frustumcorner[0][1], r_refdef.view.frustumcorner[0][2]);
9604                 qglVertex3f(r_refdef.view.frustumcorner[1][0], r_refdef.view.frustumcorner[1][1], r_refdef.view.frustumcorner[1][2]);
9605                 qglVertex3f(r_refdef.view.frustumcorner[3][0], r_refdef.view.frustumcorner[3][1], r_refdef.view.frustumcorner[3][2]);
9606                 qglVertex3f(r_refdef.view.frustumcorner[2][0], r_refdef.view.frustumcorner[2][1], r_refdef.view.frustumcorner[2][2]);
9607                 qglEnd();
9608                 qglBegin(GL_POLYGON);
9609                 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]);
9610                 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]);
9611                 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]);
9612                 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]);
9613                 qglEnd();
9614                 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
9615         }
9616 #endif
9617
9618         // don't let sound skip if going slow
9619         if (r_refdef.scene.extraupdate)
9620                 S_ExtraUpdate ();
9621
9622         R_ResetViewRendering2D();
9623 }
9624
9625 static const unsigned short bboxelements[36] =
9626 {
9627         5, 1, 3, 5, 3, 7,
9628         6, 2, 0, 6, 0, 4,
9629         7, 3, 2, 7, 2, 6,
9630         4, 0, 1, 4, 1, 5,
9631         4, 5, 7, 4, 7, 6,
9632         1, 0, 2, 1, 2, 3,
9633 };
9634
9635 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9636 {
9637         int i;
9638         float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9639
9640         RSurf_ActiveWorldEntity();
9641
9642         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9643         GL_DepthMask(false);
9644         GL_DepthRange(0, 1);
9645         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9646 //      R_Mesh_ResetTextureState();
9647
9648         vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9649         vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9650         vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9651         vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9652         vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9653         vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9654         vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9655         vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9656         R_FillColors(color4f, 8, cr, cg, cb, ca);
9657         if (r_refdef.fogenabled)
9658         {
9659                 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9660                 {
9661                         f1 = RSurf_FogVertex(v);
9662                         f2 = 1 - f1;
9663                         c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9664                         c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9665                         c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9666                 }
9667         }
9668         R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
9669         R_Mesh_ResetTextureState();
9670         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9671         R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
9672 }
9673
9674 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9675 {
9676         int i;
9677         float color[4];
9678         prvm_edict_t *edict;
9679         prvm_prog_t *prog_save = prog;
9680
9681         // this function draws bounding boxes of server entities
9682         if (!sv.active)
9683                 return;
9684
9685         GL_CullFace(GL_NONE);
9686         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9687
9688         prog = 0;
9689         SV_VM_Begin();
9690         for (i = 0;i < numsurfaces;i++)
9691         {
9692                 edict = PRVM_EDICT_NUM(surfacelist[i]);
9693                 switch ((int)edict->fields.server->solid)
9694                 {
9695                         case SOLID_NOT:      Vector4Set(color, 1, 1, 1, 0.05);break;
9696                         case SOLID_TRIGGER:  Vector4Set(color, 1, 0, 1, 0.10);break;
9697                         case SOLID_BBOX:     Vector4Set(color, 0, 1, 0, 0.10);break;
9698                         case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9699                         case SOLID_BSP:      Vector4Set(color, 0, 0, 1, 0.05);break;
9700                         default:             Vector4Set(color, 0, 0, 0, 0.50);break;
9701                 }
9702                 color[3] *= r_showbboxes.value;
9703                 color[3] = bound(0, color[3], 1);
9704                 GL_DepthTest(!r_showdisabledepthtest.integer);
9705                 GL_CullFace(r_refdef.view.cullface_front);
9706                 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9707         }
9708         SV_VM_End();
9709         prog = prog_save;
9710 }
9711
9712 static void R_DrawEntityBBoxes(void)
9713 {
9714         int i;
9715         prvm_edict_t *edict;
9716         vec3_t center;
9717         prvm_prog_t *prog_save = prog;
9718
9719         // this function draws bounding boxes of server entities
9720         if (!sv.active)
9721                 return;
9722
9723         prog = 0;
9724         SV_VM_Begin();
9725         for (i = 0;i < prog->num_edicts;i++)
9726         {
9727                 edict = PRVM_EDICT_NUM(i);
9728                 if (edict->priv.server->free)
9729                         continue;
9730                 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9731                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9732                         continue;
9733                 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9734                         continue;
9735                 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9736                 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9737         }
9738         SV_VM_End();
9739         prog = prog_save;
9740 }
9741
9742 static const int nomodelelement3i[24] =
9743 {
9744         5, 2, 0,
9745         5, 1, 2,
9746         5, 0, 3,
9747         5, 3, 1,
9748         0, 2, 4,
9749         2, 1, 4,
9750         3, 0, 4,
9751         1, 3, 4
9752 };
9753
9754 static const unsigned short nomodelelement3s[24] =
9755 {
9756         5, 2, 0,
9757         5, 1, 2,
9758         5, 0, 3,
9759         5, 3, 1,
9760         0, 2, 4,
9761         2, 1, 4,
9762         3, 0, 4,
9763         1, 3, 4
9764 };
9765
9766 static const float nomodelvertex3f[6*3] =
9767 {
9768         -16,   0,   0,
9769          16,   0,   0,
9770           0, -16,   0,
9771           0,  16,   0,
9772           0,   0, -16,
9773           0,   0,  16
9774 };
9775
9776 static const float nomodelcolor4f[6*4] =
9777 {
9778         0.0f, 0.0f, 0.5f, 1.0f,
9779         0.0f, 0.0f, 0.5f, 1.0f,
9780         0.0f, 0.5f, 0.0f, 1.0f,
9781         0.0f, 0.5f, 0.0f, 1.0f,
9782         0.5f, 0.0f, 0.0f, 1.0f,
9783         0.5f, 0.0f, 0.0f, 1.0f
9784 };
9785
9786 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9787 {
9788         int i;
9789         float f1, f2, *c;
9790         float color4f[6*4];
9791
9792         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);
9793
9794         // this is only called once per entity so numsurfaces is always 1, and
9795         // surfacelist is always {0}, so this code does not handle batches
9796
9797         if (rsurface.ent_flags & RENDER_ADDITIVE)
9798         {
9799                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9800                 GL_DepthMask(false);
9801         }
9802         else if (rsurface.colormod[3] < 1)
9803         {
9804                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9805                 GL_DepthMask(false);
9806         }
9807         else
9808         {
9809                 GL_BlendFunc(GL_ONE, GL_ZERO);
9810                 GL_DepthMask(true);
9811         }
9812         GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9813         GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9814         GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9815         GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9816         memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9817         for (i = 0, c = color4f;i < 6;i++, c += 4)
9818         {
9819                 c[0] *= rsurface.colormod[0];
9820                 c[1] *= rsurface.colormod[1];
9821                 c[2] *= rsurface.colormod[2];
9822                 c[3] *= rsurface.colormod[3];
9823         }
9824         if (r_refdef.fogenabled)
9825         {
9826                 for (i = 0, c = color4f;i < 6;i++, c += 4)
9827                 {
9828                         f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
9829                         f2 = 1 - f1;
9830                         c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9831                         c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9832                         c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9833                 }
9834         }
9835 //      R_Mesh_ResetTextureState();
9836         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9837         R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
9838         R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
9839 }
9840
9841 void R_DrawNoModel(entity_render_t *ent)
9842 {
9843         vec3_t org;
9844         Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9845         if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9846                 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9847         else
9848                 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9849 }
9850
9851 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9852 {
9853         vec3_t right1, right2, diff, normal;
9854
9855         VectorSubtract (org2, org1, normal);
9856
9857         // calculate 'right' vector for start
9858         VectorSubtract (r_refdef.view.origin, org1, diff);
9859         CrossProduct (normal, diff, right1);
9860         VectorNormalize (right1);
9861
9862         // calculate 'right' vector for end
9863         VectorSubtract (r_refdef.view.origin, org2, diff);
9864         CrossProduct (normal, diff, right2);
9865         VectorNormalize (right2);
9866
9867         vert[ 0] = org1[0] + width * right1[0];
9868         vert[ 1] = org1[1] + width * right1[1];
9869         vert[ 2] = org1[2] + width * right1[2];
9870         vert[ 3] = org1[0] - width * right1[0];
9871         vert[ 4] = org1[1] - width * right1[1];
9872         vert[ 5] = org1[2] - width * right1[2];
9873         vert[ 6] = org2[0] - width * right2[0];
9874         vert[ 7] = org2[1] - width * right2[1];
9875         vert[ 8] = org2[2] - width * right2[2];
9876         vert[ 9] = org2[0] + width * right2[0];
9877         vert[10] = org2[1] + width * right2[1];
9878         vert[11] = org2[2] + width * right2[2];
9879 }
9880
9881 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)
9882 {
9883         vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9884         vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9885         vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9886         vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9887         vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9888         vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9889         vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9890         vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9891         vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9892         vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9893         vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9894         vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9895 }
9896
9897 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9898 {
9899         int i;
9900         float *vertex3f;
9901         float v[3];
9902         VectorSet(v, x, y, z);
9903         for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9904                 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9905                         break;
9906         if (i == mesh->numvertices)
9907         {
9908                 if (mesh->numvertices < mesh->maxvertices)
9909                 {
9910                         VectorCopy(v, vertex3f);
9911                         mesh->numvertices++;
9912                 }
9913                 return mesh->numvertices;
9914         }
9915         else
9916                 return i;
9917 }
9918
9919 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9920 {
9921         int i;
9922         int *e, element[3];
9923         element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9924         element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9925         e = mesh->element3i + mesh->numtriangles * 3;
9926         for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9927         {
9928                 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9929                 if (mesh->numtriangles < mesh->maxtriangles)
9930                 {
9931                         *e++ = element[0];
9932                         *e++ = element[1];
9933                         *e++ = element[2];
9934                         mesh->numtriangles++;
9935                 }
9936                 element[1] = element[2];
9937         }
9938 }
9939
9940 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9941 {
9942         int i;
9943         int *e, element[3];
9944         element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9945         element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9946         e = mesh->element3i + mesh->numtriangles * 3;
9947         for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9948         {
9949                 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9950                 if (mesh->numtriangles < mesh->maxtriangles)
9951                 {
9952                         *e++ = element[0];
9953                         *e++ = element[1];
9954                         *e++ = element[2];
9955                         mesh->numtriangles++;
9956                 }
9957                 element[1] = element[2];
9958         }
9959 }
9960
9961 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9962 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9963 {
9964         int planenum, planenum2;
9965         int w;
9966         int tempnumpoints;
9967         mplane_t *plane, *plane2;
9968         double maxdist;
9969         double temppoints[2][256*3];
9970         // figure out how large a bounding box we need to properly compute this brush
9971         maxdist = 0;
9972         for (w = 0;w < numplanes;w++)
9973                 maxdist = max(maxdist, fabs(planes[w].dist));
9974         // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9975         maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9976         for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9977         {
9978                 w = 0;
9979                 tempnumpoints = 4;
9980                 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9981                 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9982                 {
9983                         if (planenum2 == planenum)
9984                                 continue;
9985                         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);
9986                         w = !w;
9987                 }
9988                 if (tempnumpoints < 3)
9989                         continue;
9990                 // generate elements forming a triangle fan for this polygon
9991                 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9992         }
9993 }
9994
9995 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)
9996 {
9997         texturelayer_t *layer;
9998         layer = t->currentlayers + t->currentnumlayers++;
9999         layer->type = type;
10000         layer->depthmask = depthmask;
10001         layer->blendfunc1 = blendfunc1;
10002         layer->blendfunc2 = blendfunc2;
10003         layer->texture = texture;
10004         layer->texmatrix = *matrix;
10005         layer->color[0] = r;
10006         layer->color[1] = g;
10007         layer->color[2] = b;
10008         layer->color[3] = a;
10009 }
10010
10011 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
10012 {
10013         if(parms[0] == 0 && parms[1] == 0)
10014                 return false;
10015         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10016                 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
10017                         return false;
10018         return true;
10019 }
10020
10021 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
10022 {
10023         double index, f;
10024         index = parms[2] + r_refdef.scene.time * parms[3];
10025         index -= floor(index);
10026         switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
10027         {
10028         default:
10029         case Q3WAVEFUNC_NONE:
10030         case Q3WAVEFUNC_NOISE:
10031         case Q3WAVEFUNC_COUNT:
10032                 f = 0;
10033                 break;
10034         case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
10035         case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
10036         case Q3WAVEFUNC_SAWTOOTH: f = index;break;
10037         case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
10038         case Q3WAVEFUNC_TRIANGLE:
10039                 index *= 4;
10040                 f = index - floor(index);
10041                 if (index < 1)
10042                         f = f;
10043                 else if (index < 2)
10044                         f = 1 - f;
10045                 else if (index < 3)
10046                         f = -f;
10047                 else
10048                         f = -(1 - f);
10049                 break;
10050         }
10051         f = parms[0] + parms[1] * f;
10052         if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10053                 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
10054         return (float) f;
10055 }
10056
10057 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
10058 {
10059         int w, h, idx;
10060         float f;
10061         float tcmat[12];
10062         matrix4x4_t matrix, temp;
10063         switch(tcmod->tcmod)
10064         {
10065                 case Q3TCMOD_COUNT:
10066                 case Q3TCMOD_NONE:
10067                         if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10068                                 matrix = r_waterscrollmatrix;
10069                         else
10070                                 matrix = identitymatrix;
10071                         break;
10072                 case Q3TCMOD_ENTITYTRANSLATE:
10073                         // this is used in Q3 to allow the gamecode to control texcoord
10074                         // scrolling on the entity, which is not supported in darkplaces yet.
10075                         Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
10076                         break;
10077                 case Q3TCMOD_ROTATE:
10078                         Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
10079                         Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
10080                         Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
10081                         break;
10082                 case Q3TCMOD_SCALE:
10083                         Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
10084                         break;
10085                 case Q3TCMOD_SCROLL:
10086                         Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
10087                         break;
10088                 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
10089                         w = (int) tcmod->parms[0];
10090                         h = (int) tcmod->parms[1];
10091                         f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
10092                         f = f - floor(f);
10093                         idx = (int) floor(f * w * h);
10094                         Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
10095                         break;
10096                 case Q3TCMOD_STRETCH:
10097                         f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
10098                         Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
10099                         break;
10100                 case Q3TCMOD_TRANSFORM:
10101                         VectorSet(tcmat +  0, tcmod->parms[0], tcmod->parms[1], 0);
10102                         VectorSet(tcmat +  3, tcmod->parms[2], tcmod->parms[3], 0);
10103                         VectorSet(tcmat +  6, 0                   , 0                , 1);
10104                         VectorSet(tcmat +  9, tcmod->parms[4], tcmod->parms[5], 0);
10105                         Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
10106                         break;
10107                 case Q3TCMOD_TURBULENT:
10108                         // this is handled in the RSurf_PrepareVertices function
10109                         matrix = identitymatrix;
10110                         break;
10111         }
10112         temp = *texmatrix;
10113         Matrix4x4_Concat(texmatrix, &matrix, &temp);
10114 }
10115
10116 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
10117 {
10118         int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
10119         char name[MAX_QPATH];
10120         skinframe_t *skinframe;
10121         unsigned char pixels[296*194];
10122         strlcpy(cache->name, skinname, sizeof(cache->name));
10123         dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
10124         if (developer_loading.integer)
10125                 Con_Printf("loading %s\n", name);
10126         skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
10127         if (!skinframe || !skinframe->base)
10128         {
10129                 unsigned char *f;
10130                 fs_offset_t filesize;
10131                 skinframe = NULL;
10132                 f = FS_LoadFile(name, tempmempool, true, &filesize);
10133                 if (f)
10134                 {
10135                         if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
10136                                 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
10137                         Mem_Free(f);
10138                 }
10139         }
10140         cache->skinframe = skinframe;
10141 }
10142
10143 texture_t *R_GetCurrentTexture(texture_t *t)
10144 {
10145         int i;
10146         const entity_render_t *ent = rsurface.entity;
10147         dp_model_t *model = ent->model;
10148         q3shaderinfo_layer_tcmod_t *tcmod;
10149
10150         if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
10151                 return t->currentframe;
10152         t->update_lastrenderframe = r_textureframe;
10153         t->update_lastrenderentity = (void *)ent;
10154
10155         if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
10156                 t->camera_entity = ent->entitynumber;
10157         else
10158                 t->camera_entity = 0;
10159
10160         // switch to an alternate material if this is a q1bsp animated material
10161         {
10162                 texture_t *texture = t;
10163                 int s = rsurface.ent_skinnum;
10164                 if ((unsigned int)s >= (unsigned int)model->numskins)
10165                         s = 0;
10166                 if (model->skinscenes)
10167                 {
10168                         if (model->skinscenes[s].framecount > 1)
10169                                 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
10170                         else
10171                                 s = model->skinscenes[s].firstframe;
10172                 }
10173                 if (s > 0)
10174                         t = t + s * model->num_surfaces;
10175                 if (t->animated)
10176                 {
10177                         // use an alternate animation if the entity's frame is not 0,
10178                         // and only if the texture has an alternate animation
10179                         if (rsurface.ent_alttextures && t->anim_total[1])
10180                                 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
10181                         else
10182                                 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
10183                 }
10184                 texture->currentframe = t;
10185         }
10186
10187         // update currentskinframe to be a qw skin or animation frame
10188         if (rsurface.ent_qwskin >= 0)
10189         {
10190                 i = rsurface.ent_qwskin;
10191                 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
10192                 {
10193                         r_qwskincache_size = cl.maxclients;
10194                         if (r_qwskincache)
10195                                 Mem_Free(r_qwskincache);
10196                         r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
10197                 }
10198                 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
10199                         R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
10200                 t->currentskinframe = r_qwskincache[i].skinframe;
10201                 if (t->currentskinframe == NULL)
10202                         t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10203         }
10204         else if (t->numskinframes >= 2)
10205                 t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10206         if (t->backgroundnumskinframes >= 2)
10207                 t->backgroundcurrentskinframe = t->backgroundskinframes[(unsigned int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
10208
10209         t->currentmaterialflags = t->basematerialflags;
10210         t->currentalpha = rsurface.colormod[3];
10211         if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
10212                 t->currentalpha *= r_wateralpha.value;
10213         if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
10214                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW; // we apply wateralpha later
10215         if(!r_waterstate.enabled || r_refdef.view.isoverlay)
10216                 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
10217         if (!(rsurface.ent_flags & RENDER_LIGHT))
10218                 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
10219         else if (FAKELIGHT_ENABLED)
10220         {
10221                         // no modellight if using fakelight for the map
10222         }
10223         else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
10224         {
10225                 // pick a model lighting mode
10226                 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
10227                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
10228                 else
10229                         t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
10230         }
10231         if (rsurface.ent_flags & RENDER_ADDITIVE)
10232                 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10233         else if (t->currentalpha < 1)
10234                 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10235         if (rsurface.ent_flags & RENDER_DOUBLESIDED)
10236                 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
10237         if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
10238                 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
10239         if (t->backgroundnumskinframes)
10240                 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
10241         if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
10242         {
10243                 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
10244                         t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
10245         }
10246         else
10247                 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
10248         if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
10249                 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
10250
10251         // there is no tcmod
10252         if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10253         {
10254                 t->currenttexmatrix = r_waterscrollmatrix;
10255                 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
10256         }
10257         else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
10258         {
10259                 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
10260                 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
10261         }
10262
10263         for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10264                 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
10265         for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10266                 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
10267
10268         t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
10269         if (t->currentskinframe->qpixels)
10270                 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
10271         t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
10272         if (!t->basetexture)
10273                 t->basetexture = r_texture_notexture;
10274         t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
10275         t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
10276         t->nmaptexture = t->currentskinframe->nmap;
10277         if (!t->nmaptexture)
10278                 t->nmaptexture = r_texture_blanknormalmap;
10279         t->glosstexture = r_texture_black;
10280         t->glowtexture = t->currentskinframe->glow;
10281         t->fogtexture = t->currentskinframe->fog;
10282         t->reflectmasktexture = t->currentskinframe->reflect;
10283         if (t->backgroundnumskinframes)
10284         {
10285                 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
10286                 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
10287                 t->backgroundglosstexture = r_texture_black;
10288                 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
10289                 if (!t->backgroundnmaptexture)
10290                         t->backgroundnmaptexture = r_texture_blanknormalmap;
10291         }
10292         else
10293         {
10294                 t->backgroundbasetexture = r_texture_white;
10295                 t->backgroundnmaptexture = r_texture_blanknormalmap;
10296                 t->backgroundglosstexture = r_texture_black;
10297                 t->backgroundglowtexture = NULL;
10298         }
10299         t->specularpower = r_shadow_glossexponent.value;
10300         // TODO: store reference values for these in the texture?
10301         t->specularscale = 0;
10302         if (r_shadow_gloss.integer > 0)
10303         {
10304                 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
10305                 {
10306                         if (r_shadow_glossintensity.value > 0)
10307                         {
10308                                 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
10309                                 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
10310                                 t->specularscale = r_shadow_glossintensity.value;
10311                         }
10312                 }
10313                 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
10314                 {
10315                         t->glosstexture = r_texture_white;
10316                         t->backgroundglosstexture = r_texture_white;
10317                         t->specularscale = r_shadow_gloss2intensity.value;
10318                         t->specularpower = r_shadow_gloss2exponent.value;
10319                 }
10320         }
10321         t->specularscale *= t->specularscalemod;
10322         t->specularpower *= t->specularpowermod;
10323
10324         // lightmaps mode looks bad with dlights using actual texturing, so turn
10325         // off the colormap and glossmap, but leave the normalmap on as it still
10326         // accurately represents the shading involved
10327         if (gl_lightmaps.integer)
10328         {
10329                 t->basetexture = r_texture_grey128;
10330                 t->pantstexture = r_texture_black;
10331                 t->shirttexture = r_texture_black;
10332                 t->nmaptexture = r_texture_blanknormalmap;
10333                 t->glosstexture = r_texture_black;
10334                 t->glowtexture = NULL;
10335                 t->fogtexture = NULL;
10336                 t->reflectmasktexture = NULL;
10337                 t->backgroundbasetexture = NULL;
10338                 t->backgroundnmaptexture = r_texture_blanknormalmap;
10339                 t->backgroundglosstexture = r_texture_black;
10340                 t->backgroundglowtexture = NULL;
10341                 t->specularscale = 0;
10342                 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
10343         }
10344
10345         Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
10346         VectorClear(t->dlightcolor);
10347         t->currentnumlayers = 0;
10348         if (t->currentmaterialflags & MATERIALFLAG_WALL)
10349         {
10350                 int blendfunc1, blendfunc2;
10351                 qboolean depthmask;
10352                 if (t->currentmaterialflags & MATERIALFLAG_ADD)
10353                 {
10354                         blendfunc1 = GL_SRC_ALPHA;
10355                         blendfunc2 = GL_ONE;
10356                 }
10357                 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
10358                 {
10359                         blendfunc1 = GL_SRC_ALPHA;
10360                         blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
10361                 }
10362                 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10363                 {
10364                         blendfunc1 = t->customblendfunc[0];
10365                         blendfunc2 = t->customblendfunc[1];
10366                 }
10367                 else
10368                 {
10369                         blendfunc1 = GL_ONE;
10370                         blendfunc2 = GL_ZERO;
10371                 }
10372                 // don't colormod evilblend textures
10373                 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
10374                         VectorSet(t->lightmapcolor, 1, 1, 1);
10375                 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
10376                 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
10377                 {
10378                         // fullbright is not affected by r_refdef.lightmapintensity
10379                         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]);
10380                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10381                                 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]);
10382                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10383                                 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]);
10384                 }
10385                 else
10386                 {
10387                         vec3_t ambientcolor;
10388                         float colorscale;
10389                         // set the color tint used for lights affecting this surface
10390                         VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
10391                         colorscale = 2;
10392                         // q3bsp has no lightmap updates, so the lightstylevalue that
10393                         // would normally be baked into the lightmap must be
10394                         // applied to the color
10395                         // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
10396                         if (model->type == mod_brushq3)
10397                                 colorscale *= r_refdef.scene.rtlightstylevalue[0];
10398                         colorscale *= r_refdef.lightmapintensity;
10399                         VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
10400                         VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
10401                         // basic lit geometry
10402                         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]);
10403                         // add pants/shirt if needed
10404                         if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10405                                 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]);
10406                         if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10407                                 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]);
10408                         // now add ambient passes if needed
10409                         if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
10410                         {
10411                                 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]);
10412                                 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10413                                         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]);
10414                                 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10415                                         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]);
10416                         }
10417                 }
10418                 if (t->glowtexture != NULL && !gl_lightmaps.integer)
10419                         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]);
10420                 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
10421                 {
10422                         // if this is opaque use alpha blend which will darken the earlier
10423                         // passes cheaply.
10424                         //
10425                         // if this is an alpha blended material, all the earlier passes
10426                         // were darkened by fog already, so we only need to add the fog
10427                         // color ontop through the fog mask texture
10428                         //
10429                         // if this is an additive blended material, all the earlier passes
10430                         // were darkened by fog already, and we should not add fog color
10431                         // (because the background was not darkened, there is no fog color
10432                         // that was lost behind it).
10433                         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]);
10434                 }
10435         }
10436
10437         return t->currentframe;
10438 }
10439
10440 rsurfacestate_t rsurface;
10441
10442 void RSurf_ActiveWorldEntity(void)
10443 {
10444         dp_model_t *model = r_refdef.scene.worldmodel;
10445         //if (rsurface.entity == r_refdef.scene.worldentity)
10446         //      return;
10447         rsurface.entity = r_refdef.scene.worldentity;
10448         rsurface.skeleton = NULL;
10449         memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
10450         rsurface.ent_skinnum = 0;
10451         rsurface.ent_qwskin = -1;
10452         rsurface.ent_shadertime = 0;
10453         rsurface.ent_flags = r_refdef.scene.worldentity->flags;
10454         rsurface.matrix = identitymatrix;
10455         rsurface.inversematrix = identitymatrix;
10456         rsurface.matrixscale = 1;
10457         rsurface.inversematrixscale = 1;
10458         R_EntityMatrix(&identitymatrix);
10459         VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
10460         Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
10461         rsurface.fograngerecip = r_refdef.fograngerecip;
10462         rsurface.fogheightfade = r_refdef.fogheightfade;
10463         rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
10464         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10465         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10466         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10467         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10468         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10469         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10470         VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
10471         rsurface.colormod[3] = 1;
10472         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);
10473         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10474         rsurface.frameblend[0].lerp = 1;
10475         rsurface.ent_alttextures = false;
10476         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10477         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10478         rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
10479         rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10480         rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10481         rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10482         rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10483         rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10484         rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10485         rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10486         rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10487         rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
10488         rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10489         rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10490         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
10491         rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10492         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10493         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
10494         rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10495         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10496         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
10497         rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10498         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10499         rsurface.modelelement3i = model->surfmesh.data_element3i;
10500         rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10501         rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10502         rsurface.modelelement3s = model->surfmesh.data_element3s;
10503         rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10504         rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10505         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10506         rsurface.modelnumvertices = model->surfmesh.num_vertices;
10507         rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10508         rsurface.modelsurfaces = model->data_surfaces;
10509         rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10510         rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10511         rsurface.modelvertex3fbuffer = model->surfmesh.vertex3fbuffer;
10512         rsurface.modelgeneratedvertex = false;
10513         rsurface.batchgeneratedvertex = false;
10514         rsurface.batchfirstvertex = 0;
10515         rsurface.batchnumvertices = 0;
10516         rsurface.batchfirsttriangle = 0;
10517         rsurface.batchnumtriangles = 0;
10518         rsurface.batchvertex3f  = NULL;
10519         rsurface.batchvertex3f_vertexbuffer = NULL;
10520         rsurface.batchvertex3f_bufferoffset = 0;
10521         rsurface.batchsvector3f = NULL;
10522         rsurface.batchsvector3f_vertexbuffer = NULL;
10523         rsurface.batchsvector3f_bufferoffset = 0;
10524         rsurface.batchtvector3f = NULL;
10525         rsurface.batchtvector3f_vertexbuffer = NULL;
10526         rsurface.batchtvector3f_bufferoffset = 0;
10527         rsurface.batchnormal3f  = NULL;
10528         rsurface.batchnormal3f_vertexbuffer = NULL;
10529         rsurface.batchnormal3f_bufferoffset = 0;
10530         rsurface.batchlightmapcolor4f = NULL;
10531         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10532         rsurface.batchlightmapcolor4f_bufferoffset = 0;
10533         rsurface.batchtexcoordtexture2f = NULL;
10534         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10535         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10536         rsurface.batchtexcoordlightmap2f = NULL;
10537         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10538         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10539         rsurface.batchvertexmesh = NULL;
10540         rsurface.batchvertexmeshbuffer = NULL;
10541         rsurface.batchvertex3fbuffer = NULL;
10542         rsurface.batchelement3i = NULL;
10543         rsurface.batchelement3i_indexbuffer = NULL;
10544         rsurface.batchelement3i_bufferoffset = 0;
10545         rsurface.batchelement3s = NULL;
10546         rsurface.batchelement3s_indexbuffer = NULL;
10547         rsurface.batchelement3s_bufferoffset = 0;
10548         rsurface.passcolor4f = NULL;
10549         rsurface.passcolor4f_vertexbuffer = NULL;
10550         rsurface.passcolor4f_bufferoffset = 0;
10551 }
10552
10553 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
10554 {
10555         dp_model_t *model = ent->model;
10556         //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
10557         //      return;
10558         rsurface.entity = (entity_render_t *)ent;
10559         rsurface.skeleton = ent->skeleton;
10560         memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
10561         rsurface.ent_skinnum = ent->skinnum;
10562         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;
10563         rsurface.ent_shadertime = ent->shadertime;
10564         rsurface.ent_flags = ent->flags;
10565         rsurface.matrix = ent->matrix;
10566         rsurface.inversematrix = ent->inversematrix;
10567         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10568         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10569         R_EntityMatrix(&rsurface.matrix);
10570         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10571         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10572         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10573         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10574         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10575         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10576         VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10577         VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10578         VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10579         VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10580         VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10581         VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10582         rsurface.colormod[3] = ent->alpha;
10583         VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10584         memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10585         rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10586         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10587         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10588         if (ent->model->brush.submodel && !prepass)
10589         {
10590                 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10591                 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10592         }
10593         if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10594         {
10595                 if (ent->animcache_vertex3f)
10596                 {
10597                         rsurface.modelvertex3f = ent->animcache_vertex3f;
10598                         rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10599                         rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10600                         rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10601                         rsurface.modelvertexmesh = ent->animcache_vertexmesh;
10602                         rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
10603                         rsurface.modelvertex3fbuffer = ent->animcache_vertex3fbuffer;
10604                 }
10605                 else if (wanttangents)
10606                 {
10607                         rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10608                         rsurface.modelsvector3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10609                         rsurface.modeltvector3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10610                         rsurface.modelnormal3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10611                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, rsurface.modelnormal3f, rsurface.modelsvector3f, rsurface.modeltvector3f);
10612                         rsurface.modelvertexmesh = NULL;
10613                         rsurface.modelvertexmeshbuffer = NULL;
10614                         rsurface.modelvertex3fbuffer = NULL;
10615                 }
10616                 else if (wantnormals)
10617                 {
10618                         rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10619                         rsurface.modelsvector3f = NULL;
10620                         rsurface.modeltvector3f = NULL;
10621                         rsurface.modelnormal3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10622                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, rsurface.modelnormal3f, NULL, NULL);
10623                         rsurface.modelvertexmesh = NULL;
10624                         rsurface.modelvertexmeshbuffer = NULL;
10625                         rsurface.modelvertex3fbuffer = NULL;
10626                 }
10627                 else
10628                 {
10629                         rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10630                         rsurface.modelsvector3f = NULL;
10631                         rsurface.modeltvector3f = NULL;
10632                         rsurface.modelnormal3f = NULL;
10633                         model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, NULL, NULL, NULL);
10634                         rsurface.modelvertexmesh = NULL;
10635                         rsurface.modelvertexmeshbuffer = NULL;
10636                         rsurface.modelvertex3fbuffer = NULL;
10637                 }
10638                 rsurface.modelvertex3f_vertexbuffer = 0;
10639                 rsurface.modelvertex3f_bufferoffset = 0;
10640                 rsurface.modelsvector3f_vertexbuffer = 0;
10641                 rsurface.modelsvector3f_bufferoffset = 0;
10642                 rsurface.modeltvector3f_vertexbuffer = 0;
10643                 rsurface.modeltvector3f_bufferoffset = 0;
10644                 rsurface.modelnormal3f_vertexbuffer = 0;
10645                 rsurface.modelnormal3f_bufferoffset = 0;
10646                 rsurface.modelgeneratedvertex = true;
10647         }
10648         else
10649         {
10650                 rsurface.modelvertex3f  = model->surfmesh.data_vertex3f;
10651                 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10652                 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10653                 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10654                 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10655                 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10656                 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10657                 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10658                 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10659                 rsurface.modelnormal3f  = model->surfmesh.data_normal3f;
10660                 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10661                 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10662                 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10663                 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10664                 rsurface.modelvertex3fbuffer = model->surfmesh.vertex3fbuffer;
10665                 rsurface.modelgeneratedvertex = false;
10666         }
10667         rsurface.modellightmapcolor4f  = model->surfmesh.data_lightmapcolor4f;
10668         rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10669         rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10670         rsurface.modeltexcoordtexture2f  = model->surfmesh.data_texcoordtexture2f;
10671         rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10672         rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10673         rsurface.modeltexcoordlightmap2f  = model->surfmesh.data_texcoordlightmap2f;
10674         rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10675         rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10676         rsurface.modelelement3i = model->surfmesh.data_element3i;
10677         rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10678         rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10679         rsurface.modelelement3s = model->surfmesh.data_element3s;
10680         rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10681         rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10682         rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10683         rsurface.modelnumvertices = model->surfmesh.num_vertices;
10684         rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10685         rsurface.modelsurfaces = model->data_surfaces;
10686         rsurface.batchgeneratedvertex = false;
10687         rsurface.batchfirstvertex = 0;
10688         rsurface.batchnumvertices = 0;
10689         rsurface.batchfirsttriangle = 0;
10690         rsurface.batchnumtriangles = 0;
10691         rsurface.batchvertex3f  = NULL;
10692         rsurface.batchvertex3f_vertexbuffer = NULL;
10693         rsurface.batchvertex3f_bufferoffset = 0;
10694         rsurface.batchsvector3f = NULL;
10695         rsurface.batchsvector3f_vertexbuffer = NULL;
10696         rsurface.batchsvector3f_bufferoffset = 0;
10697         rsurface.batchtvector3f = NULL;
10698         rsurface.batchtvector3f_vertexbuffer = NULL;
10699         rsurface.batchtvector3f_bufferoffset = 0;
10700         rsurface.batchnormal3f  = NULL;
10701         rsurface.batchnormal3f_vertexbuffer = NULL;
10702         rsurface.batchnormal3f_bufferoffset = 0;
10703         rsurface.batchlightmapcolor4f = NULL;
10704         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10705         rsurface.batchlightmapcolor4f_bufferoffset = 0;
10706         rsurface.batchtexcoordtexture2f = NULL;
10707         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10708         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10709         rsurface.batchtexcoordlightmap2f = NULL;
10710         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10711         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10712         rsurface.batchvertexmesh = NULL;
10713         rsurface.batchvertexmeshbuffer = NULL;
10714         rsurface.batchvertex3fbuffer = NULL;
10715         rsurface.batchelement3i = NULL;
10716         rsurface.batchelement3i_indexbuffer = NULL;
10717         rsurface.batchelement3i_bufferoffset = 0;
10718         rsurface.batchelement3s = NULL;
10719         rsurface.batchelement3s_indexbuffer = NULL;
10720         rsurface.batchelement3s_bufferoffset = 0;
10721         rsurface.passcolor4f = NULL;
10722         rsurface.passcolor4f_vertexbuffer = NULL;
10723         rsurface.passcolor4f_bufferoffset = 0;
10724 }
10725
10726 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)
10727 {
10728         rsurface.entity = r_refdef.scene.worldentity;
10729         rsurface.skeleton = NULL;
10730         rsurface.ent_skinnum = 0;
10731         rsurface.ent_qwskin = -1;
10732         rsurface.ent_shadertime = shadertime;
10733         rsurface.ent_flags = entflags;
10734         rsurface.modelnumvertices = numvertices;
10735         rsurface.modelnumtriangles = numtriangles;
10736         rsurface.matrix = *matrix;
10737         rsurface.inversematrix = *inversematrix;
10738         rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10739         rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10740         R_EntityMatrix(&rsurface.matrix);
10741         Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10742         Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10743         rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10744         rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10745         rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10746         rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10747         VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10748         VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10749         VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10750         VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10751         VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10752         Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10753         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);
10754         memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10755         rsurface.frameblend[0].lerp = 1;
10756         rsurface.ent_alttextures = false;
10757         rsurface.basepolygonfactor = r_refdef.polygonfactor;
10758         rsurface.basepolygonoffset = r_refdef.polygonoffset;
10759         if (wanttangents)
10760         {
10761                 rsurface.modelvertex3f = (float *)vertex3f;
10762                 rsurface.modelsvector3f = svector3f ? (float *)svector3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10763                 rsurface.modeltvector3f = tvector3f ? (float *)tvector3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10764                 rsurface.modelnormal3f = normal3f ? (float *)normal3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10765         }
10766         else if (wantnormals)
10767         {
10768                 rsurface.modelvertex3f = (float *)vertex3f;
10769                 rsurface.modelsvector3f = NULL;
10770                 rsurface.modeltvector3f = NULL;
10771                 rsurface.modelnormal3f = normal3f ? (float *)normal3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10772         }
10773         else
10774         {
10775                 rsurface.modelvertex3f = (float *)vertex3f;
10776                 rsurface.modelsvector3f = NULL;
10777                 rsurface.modeltvector3f = NULL;
10778                 rsurface.modelnormal3f = NULL;
10779         }
10780         rsurface.modelvertexmesh = NULL;
10781         rsurface.modelvertexmeshbuffer = NULL;
10782         rsurface.modelvertex3fbuffer = NULL;
10783         rsurface.modelvertex3f_vertexbuffer = 0;
10784         rsurface.modelvertex3f_bufferoffset = 0;
10785         rsurface.modelsvector3f_vertexbuffer = 0;
10786         rsurface.modelsvector3f_bufferoffset = 0;
10787         rsurface.modeltvector3f_vertexbuffer = 0;
10788         rsurface.modeltvector3f_bufferoffset = 0;
10789         rsurface.modelnormal3f_vertexbuffer = 0;
10790         rsurface.modelnormal3f_bufferoffset = 0;
10791         rsurface.modelgeneratedvertex = true;
10792         rsurface.modellightmapcolor4f  = (float *)color4f;
10793         rsurface.modellightmapcolor4f_vertexbuffer = 0;
10794         rsurface.modellightmapcolor4f_bufferoffset = 0;
10795         rsurface.modeltexcoordtexture2f  = (float *)texcoord2f;
10796         rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
10797         rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10798         rsurface.modeltexcoordlightmap2f  = NULL;
10799         rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
10800         rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10801         rsurface.modelelement3i = (int *)element3i;
10802         rsurface.modelelement3i_indexbuffer = NULL;
10803         rsurface.modelelement3i_bufferoffset = 0;
10804         rsurface.modelelement3s = (unsigned short *)element3s;
10805         rsurface.modelelement3s_indexbuffer = NULL;
10806         rsurface.modelelement3s_bufferoffset = 0;
10807         rsurface.modellightmapoffsets = NULL;
10808         rsurface.modelsurfaces = NULL;
10809         rsurface.batchgeneratedvertex = false;
10810         rsurface.batchfirstvertex = 0;
10811         rsurface.batchnumvertices = 0;
10812         rsurface.batchfirsttriangle = 0;
10813         rsurface.batchnumtriangles = 0;
10814         rsurface.batchvertex3f  = NULL;
10815         rsurface.batchvertex3f_vertexbuffer = NULL;
10816         rsurface.batchvertex3f_bufferoffset = 0;
10817         rsurface.batchsvector3f = NULL;
10818         rsurface.batchsvector3f_vertexbuffer = NULL;
10819         rsurface.batchsvector3f_bufferoffset = 0;
10820         rsurface.batchtvector3f = NULL;
10821         rsurface.batchtvector3f_vertexbuffer = NULL;
10822         rsurface.batchtvector3f_bufferoffset = 0;
10823         rsurface.batchnormal3f  = NULL;
10824         rsurface.batchnormal3f_vertexbuffer = NULL;
10825         rsurface.batchnormal3f_bufferoffset = 0;
10826         rsurface.batchlightmapcolor4f = NULL;
10827         rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10828         rsurface.batchlightmapcolor4f_bufferoffset = 0;
10829         rsurface.batchtexcoordtexture2f = NULL;
10830         rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10831         rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10832         rsurface.batchtexcoordlightmap2f = NULL;
10833         rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10834         rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10835         rsurface.batchvertexmesh = NULL;
10836         rsurface.batchvertexmeshbuffer = NULL;
10837         rsurface.batchvertex3fbuffer = NULL;
10838         rsurface.batchelement3i = NULL;
10839         rsurface.batchelement3i_indexbuffer = NULL;
10840         rsurface.batchelement3i_bufferoffset = 0;
10841         rsurface.batchelement3s = NULL;
10842         rsurface.batchelement3s_indexbuffer = NULL;
10843         rsurface.batchelement3s_bufferoffset = 0;
10844         rsurface.passcolor4f = NULL;
10845         rsurface.passcolor4f_vertexbuffer = NULL;
10846         rsurface.passcolor4f_bufferoffset = 0;
10847
10848         if (rsurface.modelnumvertices && rsurface.modelelement3i)
10849         {
10850                 if ((wantnormals || wanttangents) && !normal3f)
10851                 {
10852                         rsurface.modelnormal3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10853                         Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10854                 }
10855                 if (wanttangents && !svector3f)
10856                 {
10857                         rsurface.modelsvector3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10858                         rsurface.modeltvector3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10859                         Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.modelsvector3f, rsurface.modeltvector3f, r_smoothnormals_areaweighting.integer != 0);
10860                 }
10861         }
10862 }
10863
10864 float RSurf_FogPoint(const float *v)
10865 {
10866         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10867         float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10868         float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10869         float FogHeightFade = r_refdef.fogheightfade;
10870         float fogfrac;
10871         unsigned int fogmasktableindex;
10872         if (r_refdef.fogplaneviewabove)
10873                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10874         else
10875                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10876         fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10877         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10878 }
10879
10880 float RSurf_FogVertex(const float *v)
10881 {
10882         // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10883         float FogPlaneViewDist = rsurface.fogplaneviewdist;
10884         float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10885         float FogHeightFade = rsurface.fogheightfade;
10886         float fogfrac;
10887         unsigned int fogmasktableindex;
10888         if (r_refdef.fogplaneviewabove)
10889                 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10890         else
10891                 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10892         fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10893         return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10894 }
10895
10896 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10897 {
10898         int i;
10899         for (i = 0;i < numelements;i++)
10900                 outelement3i[i] = inelement3i[i] + adjust;
10901 }
10902
10903 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10904 extern cvar_t gl_vbo;
10905 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10906 {
10907         int deformindex;
10908         int firsttriangle;
10909         int numtriangles;
10910         int firstvertex;
10911         int endvertex;
10912         int numvertices;
10913         int surfacefirsttriangle;
10914         int surfacenumtriangles;
10915         int surfacefirstvertex;
10916         int surfaceendvertex;
10917         int surfacenumvertices;
10918         int batchnumvertices;
10919         int batchnumtriangles;
10920         int needsupdate;
10921         int i, j;
10922         qboolean gaps;
10923         qboolean dynamicvertex;
10924         float amplitude;
10925         float animpos;
10926         float scale;
10927         float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10928         float waveparms[4];
10929         q3shaderinfo_deform_t *deform;
10930         const msurface_t *surface, *firstsurface;
10931         r_vertexmesh_t *vertexmesh;
10932         if (!texturenumsurfaces)
10933                 return;
10934         // find vertex range of this surface batch
10935         gaps = false;
10936         firstsurface = texturesurfacelist[0];
10937         firsttriangle = firstsurface->num_firsttriangle;
10938         batchnumvertices = 0;
10939         batchnumtriangles = 0;
10940         firstvertex = endvertex = firstsurface->num_firstvertex;
10941         for (i = 0;i < texturenumsurfaces;i++)
10942         {
10943                 surface = texturesurfacelist[i];
10944                 if (surface != firstsurface + i)
10945                         gaps = true;
10946                 surfacefirstvertex = surface->num_firstvertex;
10947                 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10948                 surfacenumvertices = surface->num_vertices;
10949                 surfacenumtriangles = surface->num_triangles;
10950                 if (firstvertex > surfacefirstvertex)
10951                         firstvertex = surfacefirstvertex;
10952                 if (endvertex < surfaceendvertex)
10953                         endvertex = surfaceendvertex;
10954                 batchnumvertices += surfacenumvertices;
10955                 batchnumtriangles += surfacenumtriangles;
10956         }
10957
10958         // we now know the vertex range used, and if there are any gaps in it
10959         rsurface.batchfirstvertex = firstvertex;
10960         rsurface.batchnumvertices = endvertex - firstvertex;
10961         rsurface.batchfirsttriangle = firsttriangle;
10962         rsurface.batchnumtriangles = batchnumtriangles;
10963
10964         // this variable holds flags for which properties have been updated that
10965         // may require regenerating vertexmesh array...
10966         needsupdate = 0;
10967
10968         // check if any dynamic vertex processing must occur
10969         dynamicvertex = false;
10970
10971         // if there is a chance of animated vertex colors, it's a dynamic batch
10972         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10973         {
10974                 dynamicvertex = true;
10975                 batchneed |= BATCHNEED_NOGAPS;
10976                 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR;
10977         }
10978
10979         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10980         {
10981                 switch (deform->deform)
10982                 {
10983                 default:
10984                 case Q3DEFORM_PROJECTIONSHADOW:
10985                 case Q3DEFORM_TEXT0:
10986                 case Q3DEFORM_TEXT1:
10987                 case Q3DEFORM_TEXT2:
10988                 case Q3DEFORM_TEXT3:
10989                 case Q3DEFORM_TEXT4:
10990                 case Q3DEFORM_TEXT5:
10991                 case Q3DEFORM_TEXT6:
10992                 case Q3DEFORM_TEXT7:
10993                 case Q3DEFORM_NONE:
10994                         break;
10995                 case Q3DEFORM_AUTOSPRITE:
10996                         dynamicvertex = true;
10997                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10998                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10999                         break;
11000                 case Q3DEFORM_AUTOSPRITE2:
11001                         dynamicvertex = true;
11002                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11003                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11004                         break;
11005                 case Q3DEFORM_NORMAL:
11006                         dynamicvertex = true;
11007                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11008                         needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11009                         break;
11010                 case Q3DEFORM_WAVE:
11011                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11012                                 break; // if wavefunc is a nop, ignore this transform
11013                         dynamicvertex = true;
11014                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11015                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11016                         break;
11017                 case Q3DEFORM_BULGE:
11018                         dynamicvertex = true;
11019                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11020                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11021                         break;
11022                 case Q3DEFORM_MOVE:
11023                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11024                                 break; // if wavefunc is a nop, ignore this transform
11025                         dynamicvertex = true;
11026                         batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11027                         needsupdate |= BATCHNEED_VERTEXMESH_VERTEX;
11028                         break;
11029                 }
11030         }
11031         switch(rsurface.texture->tcgen.tcgen)
11032         {
11033         default:
11034         case Q3TCGEN_TEXTURE:
11035                 break;
11036         case Q3TCGEN_LIGHTMAP:
11037                 dynamicvertex = true;
11038                 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
11039                 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
11040                 break;
11041         case Q3TCGEN_VECTOR:
11042                 dynamicvertex = true;
11043                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11044                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11045                 break;
11046         case Q3TCGEN_ENVIRONMENT:
11047                 dynamicvertex = true;
11048                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
11049                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11050                 break;
11051         }
11052         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11053         {
11054                 dynamicvertex = true;
11055                 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11056                 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11057         }
11058
11059         if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11060         {
11061                 dynamicvertex = true;
11062                 batchneed |= BATCHNEED_NOGAPS;
11063                 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
11064         }
11065
11066         if (dynamicvertex || gaps || rsurface.batchfirstvertex)
11067         {
11068                 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
11069                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)      batchneed |= BATCHNEED_ARRAY_VERTEX;
11070                 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)      batchneed |= BATCHNEED_ARRAY_NORMAL;
11071                 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)      batchneed |= BATCHNEED_ARRAY_VECTOR;
11072                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
11073                 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)    batchneed |= BATCHNEED_ARRAY_TEXCOORD;
11074                 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP)    batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
11075         }
11076
11077         // when the model data has no vertex buffer (dynamic mesh), we need to
11078         // eliminate gaps
11079         if (vid.useinterleavedarrays ? !rsurface.modelvertexmeshbuffer : !rsurface.modelvertex3f_vertexbuffer)
11080                 batchneed |= BATCHNEED_NOGAPS;
11081
11082         // if needsupdate, we have to do a dynamic vertex batch for sure
11083         if (needsupdate & batchneed)
11084                 dynamicvertex = true;
11085
11086         // see if we need to build vertexmesh from arrays
11087         if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11088                 dynamicvertex = true;
11089
11090         // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
11091         // also some drivers strongly dislike firstvertex
11092         if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
11093                 dynamicvertex = true;
11094
11095         rsurface.batchvertex3f = rsurface.modelvertex3f;
11096         rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
11097         rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
11098         rsurface.batchsvector3f = rsurface.modelsvector3f;
11099         rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
11100         rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
11101         rsurface.batchtvector3f = rsurface.modeltvector3f;
11102         rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
11103         rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
11104         rsurface.batchnormal3f = rsurface.modelnormal3f;
11105         rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
11106         rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
11107         rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
11108         rsurface.batchlightmapcolor4f_vertexbuffer  = rsurface.modellightmapcolor4f_vertexbuffer;
11109         rsurface.batchlightmapcolor4f_bufferoffset  = rsurface.modellightmapcolor4f_bufferoffset;
11110         rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
11111         rsurface.batchtexcoordtexture2f_vertexbuffer  = rsurface.modeltexcoordtexture2f_vertexbuffer;
11112         rsurface.batchtexcoordtexture2f_bufferoffset  = rsurface.modeltexcoordtexture2f_bufferoffset;
11113         rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
11114         rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
11115         rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
11116         rsurface.batchvertex3fbuffer = rsurface.modelvertex3fbuffer;
11117         rsurface.batchvertexmesh = rsurface.modelvertexmesh;
11118         rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
11119         rsurface.batchelement3i = rsurface.modelelement3i;
11120         rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
11121         rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
11122         rsurface.batchelement3s = rsurface.modelelement3s;
11123         rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
11124         rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
11125
11126         // if any dynamic vertex processing has to occur in software, we copy the
11127         // entire surface list together before processing to rebase the vertices
11128         // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
11129         //
11130         // if any gaps exist and we do not have a static vertex buffer, we have to
11131         // copy the surface list together to avoid wasting upload bandwidth on the
11132         // vertices in the gaps.
11133         //
11134         // if gaps exist and we have a static vertex buffer, we still have to
11135         // combine the index buffer ranges into one dynamic index buffer.
11136         //
11137         // in all cases we end up with data that can be drawn in one call.
11138
11139         if (!dynamicvertex)
11140         {
11141                 // static vertex data, just set pointers...
11142                 rsurface.batchgeneratedvertex = false;
11143                 // if there are gaps, we want to build a combined index buffer,
11144                 // otherwise use the original static buffer with an appropriate offset
11145                 if (gaps)
11146                 {
11147                         // build a new triangle elements array for this batch
11148                         rsurface.batchelement3i = (int *)R_FrameData_Alloc(batchnumtriangles * sizeof(int[3]));
11149                         rsurface.batchfirsttriangle = 0;
11150                         numtriangles = 0;
11151                         for (i = 0;i < texturenumsurfaces;i++)
11152                         {
11153                                 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11154                                 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11155                                 memcpy(rsurface.batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
11156                                 numtriangles += surfacenumtriangles;
11157                         }
11158                         rsurface.batchelement3i_indexbuffer = NULL;
11159                         rsurface.batchelement3i_bufferoffset = 0;
11160                         rsurface.batchelement3s = NULL;
11161                         rsurface.batchelement3s_indexbuffer = NULL;
11162                         rsurface.batchelement3s_bufferoffset = 0;
11163                         if (endvertex <= 65536)
11164                         {
11165                                 // make a 16bit (unsigned short) index array if possible
11166                                 rsurface.batchelement3s = (unsigned short *)R_FrameData_Alloc(batchnumtriangles * sizeof(unsigned short[3]));
11167                                 for (i = 0;i < numtriangles*3;i++)
11168                                         rsurface.batchelement3s[i] = rsurface.batchelement3i[i];
11169                         }
11170                 }
11171                 return;
11172         }
11173
11174         // something needs software processing, do it for real...
11175         // we only directly handle separate array data in this case and then
11176         // generate interleaved data if needed...
11177         rsurface.batchgeneratedvertex = true;
11178
11179         // now copy the vertex data into a combined array and make an index array
11180         // (this is what Quake3 does all the time)
11181         //if (gaps || rsurface.batchfirstvertex)
11182         {
11183                 rsurface.batchvertex3fbuffer = NULL;
11184                 rsurface.batchvertexmesh = NULL;
11185                 rsurface.batchvertexmeshbuffer = NULL;
11186                 rsurface.batchvertex3f = NULL;
11187                 rsurface.batchvertex3f_vertexbuffer = NULL;
11188                 rsurface.batchvertex3f_bufferoffset = 0;
11189                 rsurface.batchsvector3f = NULL;
11190                 rsurface.batchsvector3f_vertexbuffer = NULL;
11191                 rsurface.batchsvector3f_bufferoffset = 0;
11192                 rsurface.batchtvector3f = NULL;
11193                 rsurface.batchtvector3f_vertexbuffer = NULL;
11194                 rsurface.batchtvector3f_bufferoffset = 0;
11195                 rsurface.batchnormal3f = NULL;
11196                 rsurface.batchnormal3f_vertexbuffer = NULL;
11197                 rsurface.batchnormal3f_bufferoffset = 0;
11198                 rsurface.batchlightmapcolor4f = NULL;
11199                 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11200                 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11201                 rsurface.batchtexcoordtexture2f = NULL;
11202                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11203                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11204                 rsurface.batchtexcoordlightmap2f = NULL;
11205                 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
11206                 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11207                 rsurface.batchelement3i = (int *)R_FrameData_Alloc(batchnumtriangles * sizeof(int[3]));
11208                 rsurface.batchelement3i_indexbuffer = NULL;
11209                 rsurface.batchelement3i_bufferoffset = 0;
11210                 rsurface.batchelement3s = NULL;
11211                 rsurface.batchelement3s_indexbuffer = NULL;
11212                 rsurface.batchelement3s_bufferoffset = 0;
11213                 // we'll only be setting up certain arrays as needed
11214                 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11215                         rsurface.batchvertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(batchnumvertices * sizeof(r_vertexmesh_t));
11216                 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11217                         rsurface.batchvertex3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11218                 if (batchneed & BATCHNEED_ARRAY_NORMAL)
11219                         rsurface.batchnormal3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11220                 if (batchneed & BATCHNEED_ARRAY_VECTOR)
11221                 {
11222                         rsurface.batchsvector3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11223                         rsurface.batchtvector3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11224                 }
11225                 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
11226                         rsurface.batchlightmapcolor4f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[4]));
11227                 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
11228                         rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11229                 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
11230                         rsurface.batchtexcoordlightmap2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11231                 numvertices = 0;
11232                 numtriangles = 0;
11233                 for (i = 0;i < texturenumsurfaces;i++)
11234                 {
11235                         surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
11236                         surfacenumvertices = texturesurfacelist[i]->num_vertices;
11237                         surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11238                         surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11239                         // copy only the data requested
11240                         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
11241                                 memcpy(rsurface.batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
11242                         if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
11243                         {
11244                                 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11245                                         memcpy(rsurface.batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11246                                 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
11247                                         memcpy(rsurface.batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11248                                 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
11249                                 {
11250                                         memcpy(rsurface.batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11251                                         memcpy(rsurface.batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11252                                 }
11253                                 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
11254                                         memcpy(rsurface.batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
11255                                 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
11256                                         memcpy(rsurface.batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11257                                 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
11258                                         memcpy(rsurface.batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11259                         }
11260                         RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
11261                         numvertices += surfacenumvertices;
11262                         numtriangles += surfacenumtriangles;
11263                 }
11264
11265                 // generate a 16bit index array as well if possible
11266                 // (in general, dynamic batches fit)
11267                 if (numvertices <= 65536)
11268                 {
11269                         rsurface.batchelement3s = (unsigned short *)R_FrameData_Alloc(batchnumtriangles * sizeof(unsigned short[3]));
11270                         for (i = 0;i < numtriangles*3;i++)
11271                                 rsurface.batchelement3s[i] = rsurface.batchelement3i[i];
11272                 }
11273
11274                 // since we've copied everything, the batch now starts at 0
11275                 rsurface.batchfirstvertex = 0;
11276                 rsurface.batchnumvertices = batchnumvertices;
11277                 rsurface.batchfirsttriangle = 0;
11278                 rsurface.batchnumtriangles = batchnumtriangles;
11279         }
11280
11281         // q1bsp surfaces rendered in vertex color mode have to have colors
11282         // calculated based on lightstyles
11283         if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11284         {
11285                 // generate color arrays for the surfaces in this list
11286                 int c[4];
11287                 int scale;
11288                 int size3;
11289                 const int *offsets;
11290                 const unsigned char *lm;
11291                 rsurface.batchlightmapcolor4f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[4]));
11292                 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11293                 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11294                 numvertices = 0;
11295                 for (i = 0;i < texturenumsurfaces;i++)
11296                 {
11297                         surface = texturesurfacelist[i];
11298                         offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
11299                         surfacenumvertices = surface->num_vertices;
11300                         if (surface->lightmapinfo->samples)
11301                         {
11302                                 for (j = 0;j < surfacenumvertices;j++)
11303                                 {
11304                                         lm = surface->lightmapinfo->samples + offsets[j];
11305                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
11306                                         VectorScale(lm, scale, c);
11307                                         if (surface->lightmapinfo->styles[1] != 255)
11308                                         {
11309                                                 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11310                                                 lm += size3;
11311                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
11312                                                 VectorMA(c, scale, lm, c);
11313                                                 if (surface->lightmapinfo->styles[2] != 255)
11314                                                 {
11315                                                         lm += size3;
11316                                                         scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
11317                                                         VectorMA(c, scale, lm, c);
11318                                                         if (surface->lightmapinfo->styles[3] != 255)
11319                                                         {
11320                                                                 lm += size3;
11321                                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
11322                                                                 VectorMA(c, scale, lm, c);
11323                                                         }
11324                                                 }
11325                                         }
11326                                         c[0] >>= 7;
11327                                         c[1] >>= 7;
11328                                         c[2] >>= 7;
11329                                         Vector4Set(rsurface.batchlightmapcolor4f + 4*numvertices, min(c[0], 255) * (1.0f / 255.0f), min(c[1], 255) * (1.0f / 255.0f), min(c[2], 255) * (1.0f / 255.0f), 1);
11330                                         numvertices++;
11331                                 }
11332                         }
11333                         else
11334                         {
11335                                 for (j = 0;j < surfacenumvertices;j++)
11336                                 {
11337                                         Vector4Set(rsurface.batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
11338                                         numvertices++;
11339                                 }
11340                         }
11341                 }
11342         }
11343
11344         // if vertices are deformed (sprite flares and things in maps, possibly
11345         // water waves, bulges and other deformations), modify the copied vertices
11346         // in place
11347         for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11348         {
11349                 switch (deform->deform)
11350                 {
11351                 default:
11352                 case Q3DEFORM_PROJECTIONSHADOW:
11353                 case Q3DEFORM_TEXT0:
11354                 case Q3DEFORM_TEXT1:
11355                 case Q3DEFORM_TEXT2:
11356                 case Q3DEFORM_TEXT3:
11357                 case Q3DEFORM_TEXT4:
11358                 case Q3DEFORM_TEXT5:
11359                 case Q3DEFORM_TEXT6:
11360                 case Q3DEFORM_TEXT7:
11361                 case Q3DEFORM_NONE:
11362                         break;
11363                 case Q3DEFORM_AUTOSPRITE:
11364                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11365                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11366                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11367                         VectorNormalize(newforward);
11368                         VectorNormalize(newright);
11369                         VectorNormalize(newup);
11370 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11371 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
11372 //                      rsurface.batchvertex3f_bufferoffset = 0;
11373 //                      rsurface.batchsvector3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchsvector3f);
11374 //                      rsurface.batchsvector3f_vertexbuffer = NULL;
11375 //                      rsurface.batchsvector3f_bufferoffset = 0;
11376 //                      rsurface.batchtvector3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchtvector3f);
11377 //                      rsurface.batchtvector3f_vertexbuffer = NULL;
11378 //                      rsurface.batchtvector3f_bufferoffset = 0;
11379 //                      rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11380 //                      rsurface.batchnormal3f_vertexbuffer = NULL;
11381 //                      rsurface.batchnormal3f_bufferoffset = 0;
11382                         // a single autosprite surface can contain multiple sprites...
11383                         for (j = 0;j < batchnumvertices - 3;j += 4)
11384                         {
11385                                 VectorClear(center);
11386                                 for (i = 0;i < 4;i++)
11387                                         VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11388                                 VectorScale(center, 0.25f, center);
11389                                 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
11390                                 VectorCopy(rsurface.batchsvector3f + 3*j, right);
11391                                 VectorCopy(rsurface.batchtvector3f + 3*j, up);
11392                                 for (i = 0;i < 4;i++)
11393                                 {
11394                                         VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
11395                                         VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.batchvertex3f + 3*(j+i));
11396                                 }
11397                         }
11398                         // if we get here, BATCHNEED_ARRAY_NORMAL and BATCHNEED_ARRAY_VECTOR are in batchneed, so no need to check
11399                         Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11400                         Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11401                         break;
11402                 case Q3DEFORM_AUTOSPRITE2:
11403                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11404                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11405                         Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11406                         VectorNormalize(newforward);
11407                         VectorNormalize(newright);
11408                         VectorNormalize(newup);
11409 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11410 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
11411 //                      rsurface.batchvertex3f_bufferoffset = 0;
11412                         {
11413                                 const float *v1, *v2;
11414                                 vec3_t start, end;
11415                                 float f, l;
11416                                 struct
11417                                 {
11418                                         float length2;
11419                                         const float *v1;
11420                                         const float *v2;
11421                                 }
11422                                 shortest[2];
11423                                 memset(shortest, 0, sizeof(shortest));
11424                                 // a single autosprite surface can contain multiple sprites...
11425                                 for (j = 0;j < batchnumvertices - 3;j += 4)
11426                                 {
11427                                         VectorClear(center);
11428                                         for (i = 0;i < 4;i++)
11429                                                 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11430                                         VectorScale(center, 0.25f, center);
11431                                         // find the two shortest edges, then use them to define the
11432                                         // axis vectors for rotating around the central axis
11433                                         for (i = 0;i < 6;i++)
11434                                         {
11435                                                 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
11436                                                 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
11437                                                 l = VectorDistance2(v1, v2);
11438                                                 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
11439                                                 if (v1[2] != v2[2])
11440                                                         l += (1.0f / 1024.0f);
11441                                                 if (shortest[0].length2 > l || i == 0)
11442                                                 {
11443                                                         shortest[1] = shortest[0];
11444                                                         shortest[0].length2 = l;
11445                                                         shortest[0].v1 = v1;
11446                                                         shortest[0].v2 = v2;
11447                                                 }
11448                                                 else if (shortest[1].length2 > l || i == 1)
11449                                                 {
11450                                                         shortest[1].length2 = l;
11451                                                         shortest[1].v1 = v1;
11452                                                         shortest[1].v2 = v2;
11453                                                 }
11454                                         }
11455                                         VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
11456                                         VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
11457                                         // this calculates the right vector from the shortest edge
11458                                         // and the up vector from the edge midpoints
11459                                         VectorSubtract(shortest[0].v1, shortest[0].v2, right);
11460                                         VectorNormalize(right);
11461                                         VectorSubtract(end, start, up);
11462                                         VectorNormalize(up);
11463                                         // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
11464                                         VectorSubtract(rsurface.localvieworigin, center, forward);
11465                                         //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
11466                                         VectorNegate(forward, forward);
11467                                         VectorReflect(forward, 0, up, forward);
11468                                         VectorNormalize(forward);
11469                                         CrossProduct(up, forward, newright);
11470                                         VectorNormalize(newright);
11471                                         // rotate the quad around the up axis vector, this is made
11472                                         // especially easy by the fact we know the quad is flat,
11473                                         // so we only have to subtract the center position and
11474                                         // measure distance along the right vector, and then
11475                                         // multiply that by the newright vector and add back the
11476                                         // center position
11477                                         // we also need to subtract the old position to undo the
11478                                         // displacement from the center, which we do with a
11479                                         // DotProduct, the subtraction/addition of center is also
11480                                         // optimized into DotProducts here
11481                                         l = DotProduct(right, center);
11482                                         for (i = 0;i < 4;i++)
11483                                         {
11484                                                 v1 = rsurface.batchvertex3f + 3*(j+i);
11485                                                 f = DotProduct(right, v1) - l;
11486                                                 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.batchvertex3f + 3*(j+i));
11487                                         }
11488                                 }
11489                         }
11490                         if(batchneed & (BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR)) // otherwise these can stay NULL
11491                         {
11492 //                              rsurface.batchnormal3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11493 //                              rsurface.batchnormal3f_vertexbuffer = NULL;
11494 //                              rsurface.batchnormal3f_bufferoffset = 0;
11495                                 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11496                         }
11497                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11498                         {
11499 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11500 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
11501 //                              rsurface.batchsvector3f_bufferoffset = 0;
11502 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11503 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
11504 //                              rsurface.batchtvector3f_bufferoffset = 0;
11505                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11506                         }
11507                         break;
11508                 case Q3DEFORM_NORMAL:
11509                         // deform the normals to make reflections wavey
11510                         rsurface.batchnormal3f = (float *)R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11511                         rsurface.batchnormal3f_vertexbuffer = NULL;
11512                         rsurface.batchnormal3f_bufferoffset = 0;
11513                         for (j = 0;j < batchnumvertices;j++)
11514                         {
11515                                 float vertex[3];
11516                                 float *normal = rsurface.batchnormal3f + 3*j;
11517                                 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
11518                                 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f(      vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11519                                 normal[1] = rsurface.batchnormal3f[j*3+1] + deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11520                                 normal[2] = rsurface.batchnormal3f[j*3+2] + deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11521                                 VectorNormalize(normal);
11522                         }
11523                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11524                         {
11525 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11526 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
11527 //                              rsurface.batchsvector3f_bufferoffset = 0;
11528 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11529 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
11530 //                              rsurface.batchtvector3f_bufferoffset = 0;
11531                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11532                         }
11533                         break;
11534                 case Q3DEFORM_WAVE:
11535                         // deform vertex array to make wavey water and flags and such
11536                         waveparms[0] = deform->waveparms[0];
11537                         waveparms[1] = deform->waveparms[1];
11538                         waveparms[2] = deform->waveparms[2];
11539                         waveparms[3] = deform->waveparms[3];
11540                         if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
11541                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
11542                         // this is how a divisor of vertex influence on deformation
11543                         animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
11544                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11545 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11546 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
11547 //                      rsurface.batchvertex3f_bufferoffset = 0;
11548 //                      rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11549 //                      rsurface.batchnormal3f_vertexbuffer = NULL;
11550 //                      rsurface.batchnormal3f_bufferoffset = 0;
11551                         for (j = 0;j < batchnumvertices;j++)
11552                         {
11553                                 // if the wavefunc depends on time, evaluate it per-vertex
11554                                 if (waveparms[3])
11555                                 {
11556                                         waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
11557                                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11558                                 }
11559                                 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.batchvertex3f + 3*j);
11560                         }
11561                         // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
11562                         Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11563                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11564                         {
11565 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11566 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
11567 //                              rsurface.batchsvector3f_bufferoffset = 0;
11568 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11569 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
11570 //                              rsurface.batchtvector3f_bufferoffset = 0;
11571                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11572                         }
11573                         break;
11574                 case Q3DEFORM_BULGE:
11575                         // deform vertex array to make the surface have moving bulges
11576 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11577 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
11578 //                      rsurface.batchvertex3f_bufferoffset = 0;
11579 //                      rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11580 //                      rsurface.batchnormal3f_vertexbuffer = NULL;
11581 //                      rsurface.batchnormal3f_bufferoffset = 0;
11582                         for (j = 0;j < batchnumvertices;j++)
11583                         {
11584                                 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
11585                                 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.batchvertex3f + 3*j);
11586                         }
11587                         // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
11588                         Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11589                         if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11590                         {
11591 //                              rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11592 //                              rsurface.batchsvector3f_vertexbuffer = NULL;
11593 //                              rsurface.batchsvector3f_bufferoffset = 0;
11594 //                              rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11595 //                              rsurface.batchtvector3f_vertexbuffer = NULL;
11596 //                              rsurface.batchtvector3f_bufferoffset = 0;
11597                                 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11598                         }
11599                         break;
11600                 case Q3DEFORM_MOVE:
11601                         // deform vertex array
11602                         if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11603                                 break; // if wavefunc is a nop, don't make a dynamic vertex array
11604                         scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
11605                         VectorScale(deform->parms, scale, waveparms);
11606 //                      rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11607 //                      rsurface.batchvertex3f_vertexbuffer = NULL;
11608 //                      rsurface.batchvertex3f_bufferoffset = 0;
11609                         for (j = 0;j < batchnumvertices;j++)
11610                                 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.batchvertex3f + 3*j);
11611                         break;
11612                 }
11613         }
11614
11615         // generate texcoords based on the chosen texcoord source
11616         switch(rsurface.texture->tcgen.tcgen)
11617         {
11618         default:
11619         case Q3TCGEN_TEXTURE:
11620                 break;
11621         case Q3TCGEN_LIGHTMAP:
11622 //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11623 //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11624 //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11625                 if (rsurface.batchtexcoordlightmap2f)
11626                         memcpy(rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, batchnumvertices * sizeof(float[2]));
11627                 break;
11628         case Q3TCGEN_VECTOR:
11629 //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11630 //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11631 //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11632                 for (j = 0;j < batchnumvertices;j++)
11633                 {
11634                         rsurface.batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
11635                         rsurface.batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
11636                 }
11637                 break;
11638         case Q3TCGEN_ENVIRONMENT:
11639                 // make environment reflections using a spheremap
11640                 rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11641                 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11642                 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11643                 for (j = 0;j < batchnumvertices;j++)
11644                 {
11645                         // identical to Q3A's method, but executed in worldspace so
11646                         // carried models can be shiny too
11647
11648                         float viewer[3], d, reflected[3], worldreflected[3];
11649
11650                         VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
11651                         // VectorNormalize(viewer);
11652
11653                         d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
11654
11655                         reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
11656                         reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
11657                         reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
11658                         // note: this is proportinal to viewer, so we can normalize later
11659
11660                         Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
11661                         VectorNormalize(worldreflected);
11662
11663                         // note: this sphere map only uses world x and z!
11664                         // so positive and negative y will LOOK THE SAME.
11665                         rsurface.batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
11666                         rsurface.batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
11667                 }
11668                 break;
11669         }
11670         // the only tcmod that needs software vertex processing is turbulent, so
11671         // check for it here and apply the changes if needed
11672         // and we only support that as the first one
11673         // (handling a mixture of turbulent and other tcmods would be problematic
11674         //  without punting it entirely to a software path)
11675         if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11676         {
11677                 amplitude = rsurface.texture->tcmods[0].parms[1];
11678                 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
11679 //              rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11680 //              rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11681 //              rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11682                 for (j = 0;j < batchnumvertices;j++)
11683                 {
11684                         rsurface.batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11685                         rsurface.batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1]                                ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11686                 }
11687         }
11688
11689         if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11690         {
11691                 // convert the modified arrays to vertex structs
11692 //              rsurface.batchvertexmesh = R_FrameData_Alloc(batchnumvertices * sizeof(r_vertexmesh_t));
11693 //              rsurface.batchvertexmeshbuffer = NULL;
11694                 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
11695                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11696                                 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
11697                 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
11698                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11699                                 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
11700                 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
11701                 {
11702                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11703                         {
11704                                 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
11705                                 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
11706                         }
11707                 }
11708                 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
11709                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11710                                 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
11711                 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
11712                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11713                                 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
11714                 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
11715                         for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11716                                 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
11717         }
11718 }
11719
11720 void RSurf_DrawBatch(void)
11721 {
11722         // sometimes a zero triangle surface (usually a degenerate patch) makes it
11723         // through the pipeline, killing it earlier in the pipeline would have
11724         // per-surface overhead rather than per-batch overhead, so it's best to
11725         // reject it here, before it hits glDraw.
11726         if (rsurface.batchnumtriangles == 0)
11727                 return;
11728 #if 0
11729         // batch debugging code
11730         if (r_test.integer && rsurface.entity == r_refdef.scene.worldentity && rsurface.batchvertex3f == r_refdef.scene.worldentity->model->surfmesh.data_vertex3f)
11731         {
11732                 int i;
11733                 int j;
11734                 int c;
11735                 const int *e;
11736                 e = rsurface.batchelement3i + rsurface.batchfirsttriangle*3;
11737                 for (i = 0;i < rsurface.batchnumtriangles*3;i++)
11738                 {
11739                         c = e[i];
11740                         for (j = 0;j < rsurface.entity->model->num_surfaces;j++)
11741                         {
11742                                 if (c >= rsurface.modelsurfaces[j].num_firstvertex && c < (rsurface.modelsurfaces[j].num_firstvertex + rsurface.modelsurfaces[j].num_vertices))
11743                                 {
11744                                         if (rsurface.modelsurfaces[j].texture != rsurface.texture)
11745                                                 Sys_Error("RSurf_DrawBatch: index %i uses different texture (%s) than surface %i which it belongs to (which uses %s)\n", c, rsurface.texture->name, j, rsurface.modelsurfaces[j].texture->name);
11746                                         break;
11747                                 }
11748                         }
11749                 }
11750         }
11751 #endif
11752         R_Mesh_Draw(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchfirsttriangle, rsurface.batchnumtriangles, rsurface.batchelement3i, rsurface.batchelement3i_indexbuffer, rsurface.batchelement3i_bufferoffset, rsurface.batchelement3s, rsurface.batchelement3s_indexbuffer, rsurface.batchelement3s_bufferoffset);
11753 }
11754
11755 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
11756 {
11757         // pick the closest matching water plane
11758         int planeindex, vertexindex, bestplaneindex = -1;
11759         float d, bestd;
11760         vec3_t vert;
11761         const float *v;
11762         r_waterstate_waterplane_t *p;
11763         qboolean prepared = false;
11764         bestd = 0;
11765         for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
11766         {
11767                 if(p->camera_entity != rsurface.texture->camera_entity)
11768                         continue;
11769                 d = 0;
11770                 if(!prepared)
11771                 {
11772                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, 1, &surface);
11773                         prepared = true;
11774                         if(rsurface.batchnumvertices == 0)
11775                                 break;
11776                 }
11777                 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
11778                 {
11779                         Matrix4x4_Transform(&rsurface.matrix, v, vert);
11780                         d += fabs(PlaneDiff(vert, &p->plane));
11781                 }
11782                 if (bestd > d || bestplaneindex < 0)
11783                 {
11784                         bestd = d;
11785                         bestplaneindex = planeindex;
11786                 }
11787         }
11788         return bestplaneindex;
11789         // NOTE: this MAY return a totally unrelated water plane; we can ignore
11790         // this situation though, as it might be better to render single larger
11791         // batches with useless stuff (backface culled for example) than to
11792         // render multiple smaller batches
11793 }
11794
11795 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
11796 {
11797         int i;
11798         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11799         rsurface.passcolor4f_vertexbuffer = 0;
11800         rsurface.passcolor4f_bufferoffset = 0;
11801         for (i = 0;i < rsurface.batchnumvertices;i++)
11802                 Vector4Set(rsurface.passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
11803 }
11804
11805 static void RSurf_DrawBatch_GL11_ApplyFog(void)
11806 {
11807         int i;
11808         float f;
11809         const float *v;
11810         const float *c;
11811         float *c2;
11812         if (rsurface.passcolor4f)
11813         {
11814                 // generate color arrays
11815                 c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11816                 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11817                 rsurface.passcolor4f_vertexbuffer = 0;
11818                 rsurface.passcolor4f_bufferoffset = 0;
11819                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
11820                 {
11821                         f = RSurf_FogVertex(v);
11822                         c2[0] = c[0] * f;
11823                         c2[1] = c[1] * f;
11824                         c2[2] = c[2] * f;
11825                         c2[3] = c[3];
11826                 }
11827         }
11828         else
11829         {
11830                 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11831                 rsurface.passcolor4f_vertexbuffer = 0;
11832                 rsurface.passcolor4f_bufferoffset = 0;
11833                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
11834                 {
11835                         f = RSurf_FogVertex(v);
11836                         c2[0] = f;
11837                         c2[1] = f;
11838                         c2[2] = f;
11839                         c2[3] = 1;
11840                 }
11841         }
11842 }
11843
11844 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11845 {
11846         int i;
11847         float f;
11848         const float *v;
11849         const float *c;
11850         float *c2;
11851         if (!rsurface.passcolor4f)
11852                 return;
11853         c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11854         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11855         rsurface.passcolor4f_vertexbuffer = 0;
11856         rsurface.passcolor4f_bufferoffset = 0;
11857         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
11858         {
11859                 f = RSurf_FogVertex(v);
11860                 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11861                 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11862                 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11863                 c2[3] = c[3];
11864         }
11865 }
11866
11867 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11868 {
11869         int i;
11870         const float *c;
11871         float *c2;
11872         if (!rsurface.passcolor4f)
11873                 return;
11874         c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11875         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11876         rsurface.passcolor4f_vertexbuffer = 0;
11877         rsurface.passcolor4f_bufferoffset = 0;
11878         for (i = 0, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11879         {
11880                 c2[0] = c[0] * r;
11881                 c2[1] = c[1] * g;
11882                 c2[2] = c[2] * b;
11883                 c2[3] = c[3] * a;
11884         }
11885 }
11886
11887 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11888 {
11889         int i;
11890         const float *c;
11891         float *c2;
11892         if (!rsurface.passcolor4f)
11893                 return;
11894         c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11895         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11896         rsurface.passcolor4f_vertexbuffer = 0;
11897         rsurface.passcolor4f_bufferoffset = 0;
11898         for (i = 0, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11899         {
11900                 c2[0] = c[0] + r_refdef.scene.ambient;
11901                 c2[1] = c[1] + r_refdef.scene.ambient;
11902                 c2[2] = c[2] + r_refdef.scene.ambient;
11903                 c2[3] = c[3];
11904         }
11905 }
11906
11907 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11908 {
11909         // TODO: optimize
11910         rsurface.passcolor4f = NULL;
11911         rsurface.passcolor4f_vertexbuffer = 0;
11912         rsurface.passcolor4f_bufferoffset = 0;
11913         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
11914         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11915         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11916         GL_Color(r, g, b, a);
11917         R_Mesh_TexBind(0, rsurface.lightmaptexture);
11918         RSurf_DrawBatch();
11919 }
11920
11921 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11922 {
11923         // TODO: optimize applyfog && applycolor case
11924         // just apply fog if necessary, and tint the fog color array if necessary
11925         rsurface.passcolor4f = NULL;
11926         rsurface.passcolor4f_vertexbuffer = 0;
11927         rsurface.passcolor4f_bufferoffset = 0;
11928         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
11929         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11930         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11931         GL_Color(r, g, b, a);
11932         RSurf_DrawBatch();
11933 }
11934
11935 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11936 {
11937         // TODO: optimize
11938         rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11939         rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11940         rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11941         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
11942         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11943         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11944         GL_Color(r, g, b, a);
11945         RSurf_DrawBatch();
11946 }
11947
11948 static void RSurf_DrawBatch_GL11_ClampColor(void)
11949 {
11950         int i;
11951         const float *c1;
11952         float *c2;
11953         if (!rsurface.passcolor4f)
11954                 return;
11955         for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11956         {
11957                 c2[0] = bound(0.0f, c1[0], 1.0f);
11958                 c2[1] = bound(0.0f, c1[1], 1.0f);
11959                 c2[2] = bound(0.0f, c1[2], 1.0f);
11960                 c2[3] = bound(0.0f, c1[3], 1.0f);
11961         }
11962 }
11963
11964 static void RSurf_DrawBatch_GL11_ApplyFakeLight(void)
11965 {
11966         int i;
11967         float f;
11968         const float *v;
11969         const float *n;
11970         float *c;
11971         //vec3_t eyedir;
11972
11973         // fake shading
11974         rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11975         rsurface.passcolor4f_vertexbuffer = 0;
11976         rsurface.passcolor4f_bufferoffset = 0;
11977         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
11978         {
11979                 f = -DotProduct(r_refdef.view.forward, n);
11980                 f = max(0, f);
11981                 f = f * 0.85 + 0.15; // work around so stuff won't get black
11982                 f *= r_refdef.lightmapintensity;
11983                 Vector4Set(c, f, f, f, 1);
11984         }
11985 }
11986
11987 static void RSurf_DrawBatch_GL11_FakeLight(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11988 {
11989         RSurf_DrawBatch_GL11_ApplyFakeLight();
11990         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
11991         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11992         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11993         GL_Color(r, g, b, a);
11994         RSurf_DrawBatch();
11995 }
11996
11997 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
11998 {
11999         int i;
12000         float f;
12001         float alpha;
12002         const float *v;
12003         const float *n;
12004         float *c;
12005         vec3_t ambientcolor;
12006         vec3_t diffusecolor;
12007         vec3_t lightdir;
12008         // TODO: optimize
12009         // model lighting
12010         VectorCopy(rsurface.modellight_lightdir, lightdir);
12011         f = 0.5f * r_refdef.lightmapintensity;
12012         ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
12013         ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
12014         ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
12015         diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
12016         diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
12017         diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
12018         alpha = *a;
12019         if (VectorLength2(diffusecolor) > 0)
12020         {
12021                 // q3-style directional shading
12022                 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
12023                 rsurface.passcolor4f_vertexbuffer = 0;
12024                 rsurface.passcolor4f_bufferoffset = 0;
12025                 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
12026                 {
12027                         if ((f = DotProduct(n, lightdir)) > 0)
12028                                 VectorMA(ambientcolor, f, diffusecolor, c);
12029                         else
12030                                 VectorCopy(ambientcolor, c);
12031                         c[3] = alpha;
12032                 }
12033                 *r = 1;
12034                 *g = 1;
12035                 *b = 1;
12036                 *a = 1;
12037                 *applycolor = false;
12038         }
12039         else
12040         {
12041                 *r = ambientcolor[0];
12042                 *g = ambientcolor[1];
12043                 *b = ambientcolor[2];
12044                 rsurface.passcolor4f = NULL;
12045                 rsurface.passcolor4f_vertexbuffer = 0;
12046                 rsurface.passcolor4f_bufferoffset = 0;
12047         }
12048 }
12049
12050 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12051 {
12052         RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
12053         if (applyfog)   RSurf_DrawBatch_GL11_ApplyFog();
12054         if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12055         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12056         GL_Color(r, g, b, a);
12057         RSurf_DrawBatch();
12058 }
12059
12060 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
12061 {
12062         int i;
12063         float f;
12064         const float *v;
12065         float *c;
12066         for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
12067         {
12068                 f = 1 - RSurf_FogVertex(v);
12069                 c[0] = r;
12070                 c[1] = g;
12071                 c[2] = b;
12072                 c[3] = f * a;
12073         }
12074 }
12075
12076 void RSurf_SetupDepthAndCulling(void)
12077 {
12078         // submodels are biased to avoid z-fighting with world surfaces that they
12079         // may be exactly overlapping (avoids z-fighting artifacts on certain
12080         // doors and things in Quake maps)
12081         GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
12082         GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
12083         GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
12084         GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
12085 }
12086
12087 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12088 {
12089         // transparent sky would be ridiculous
12090         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12091                 return;
12092         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12093         skyrenderlater = true;
12094         RSurf_SetupDepthAndCulling();
12095         GL_DepthMask(true);
12096         // LordHavoc: HalfLife maps have freaky skypolys so don't use
12097         // skymasking on them, and Quake3 never did sky masking (unlike
12098         // software Quake and software Quake2), so disable the sky masking
12099         // in Quake3 maps as it causes problems with q3map2 sky tricks,
12100         // and skymasking also looks very bad when noclipping outside the
12101         // level, so don't use it then either.
12102         if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
12103         {
12104                 R_Mesh_ResetTextureState();
12105                 if (skyrendermasked)
12106                 {
12107                         R_SetupShader_DepthOrShadow();
12108                         // depth-only (masking)
12109                         GL_ColorMask(0,0,0,0);
12110                         // just to make sure that braindead drivers don't draw
12111                         // anything despite that colormask...
12112                         GL_BlendFunc(GL_ZERO, GL_ONE);
12113                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12114                         if (rsurface.batchvertex3fbuffer)
12115                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
12116                         else
12117                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
12118                 }
12119                 else
12120                 {
12121                         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12122                         // fog sky
12123                         GL_BlendFunc(GL_ONE, GL_ZERO);
12124                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12125                         GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
12126                         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12127                 }
12128                 RSurf_DrawBatch();
12129                 if (skyrendermasked)
12130                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12131         }
12132         R_Mesh_ResetTextureState();
12133         GL_Color(1, 1, 1, 1);
12134 }
12135
12136 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
12137 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
12138 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12139 {
12140         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
12141                 return;
12142         if (prepass)
12143         {
12144                 // render screenspace normalmap to texture
12145                 GL_DepthMask(true);
12146                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL);
12147                 RSurf_DrawBatch();
12148                 return;
12149         }
12150
12151         // bind lightmap texture
12152
12153         // water/refraction/reflection/camera surfaces have to be handled specially
12154         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)))
12155         {
12156                 int start, end, startplaneindex;
12157                 for (start = 0;start < texturenumsurfaces;start = end)
12158                 {
12159                         startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
12160                         if(startplaneindex < 0)
12161                         {
12162                                 // this happens if the plane e.g. got backface culled and thus didn't get a water plane. We can just ignore this.
12163                                 // Con_Printf("No matching water plane for surface with material flags 0x%08x - PLEASE DEBUG THIS\n", rsurface.texture->currentmaterialflags);
12164                                 end = start + 1;
12165                                 continue;
12166                         }
12167                         for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
12168                                 ;
12169                         // now that we have a batch using the same planeindex, render it
12170                         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)))
12171                         {
12172                                 // render water or distortion background
12173                                 GL_DepthMask(true);
12174                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12175                                 RSurf_DrawBatch();
12176                                 // blend surface on top
12177                                 GL_DepthMask(false);
12178                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL);
12179                                 RSurf_DrawBatch();
12180                         }
12181                         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION))
12182                         {
12183                                 // render surface with reflection texture as input
12184                                 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12185                                 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12186                                 RSurf_DrawBatch();
12187                         }
12188                 }
12189                 return;
12190         }
12191
12192         // render surface batch normally
12193         GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12194         R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL);
12195         RSurf_DrawBatch();
12196 }
12197
12198 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12199 {
12200         // OpenGL 1.3 path - anything not completely ancient
12201         qboolean applycolor;
12202         qboolean applyfog;
12203         int layerindex;
12204         const texturelayer_t *layer;
12205         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12206         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12207
12208         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12209         {
12210                 vec4_t layercolor;
12211                 int layertexrgbscale;
12212                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12213                 {
12214                         if (layerindex == 0)
12215                                 GL_AlphaTest(true);
12216                         else
12217                         {
12218                                 GL_AlphaTest(false);
12219                                 GL_DepthFunc(GL_EQUAL);
12220                         }
12221                 }
12222                 GL_DepthMask(layer->depthmask && writedepth);
12223                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12224                 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
12225                 {
12226                         layertexrgbscale = 4;
12227                         VectorScale(layer->color, 0.25f, layercolor);
12228                 }
12229                 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
12230                 {
12231                         layertexrgbscale = 2;
12232                         VectorScale(layer->color, 0.5f, layercolor);
12233                 }
12234                 else
12235                 {
12236                         layertexrgbscale = 1;
12237                         VectorScale(layer->color, 1.0f, layercolor);
12238                 }
12239                 layercolor[3] = layer->color[3];
12240                 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
12241                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12242                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12243                 switch (layer->type)
12244                 {
12245                 case TEXTURELAYERTYPE_LITTEXTURE:
12246                         // single-pass lightmapped texture with 2x rgbscale
12247                         R_Mesh_TexBind(0, r_texture_white);
12248                         R_Mesh_TexMatrix(0, NULL);
12249                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12250                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12251                         R_Mesh_TexBind(1, layer->texture);
12252                         R_Mesh_TexMatrix(1, &layer->texmatrix);
12253                         R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12254                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12255                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12256                                 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12257                         else if (FAKELIGHT_ENABLED)
12258                                 RSurf_DrawBatch_GL11_FakeLight(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12259                         else if (rsurface.uselightmaptexture)
12260                                 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12261                         else
12262                                 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12263                         break;
12264                 case TEXTURELAYERTYPE_TEXTURE:
12265                         // singletexture unlit texture with transparency support
12266                         R_Mesh_TexBind(0, layer->texture);
12267                         R_Mesh_TexMatrix(0, &layer->texmatrix);
12268                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12269                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12270                         R_Mesh_TexBind(1, 0);
12271                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12272                         RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12273                         break;
12274                 case TEXTURELAYERTYPE_FOG:
12275                         // singletexture fogging
12276                         if (layer->texture)
12277                         {
12278                                 R_Mesh_TexBind(0, layer->texture);
12279                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12280                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12281                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12282                         }
12283                         else
12284                         {
12285                                 R_Mesh_TexBind(0, 0);
12286                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12287                         }
12288                         R_Mesh_TexBind(1, 0);
12289                         R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12290                         // generate a color array for the fog pass
12291                         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
12292                         RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
12293                         RSurf_DrawBatch();
12294                         break;
12295                 default:
12296                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12297                 }
12298         }
12299         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12300         {
12301                 GL_DepthFunc(GL_LEQUAL);
12302                 GL_AlphaTest(false);
12303         }
12304 }
12305
12306 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12307 {
12308         // OpenGL 1.1 - crusty old voodoo path
12309         qboolean applyfog;
12310         int layerindex;
12311         const texturelayer_t *layer;
12312         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12313         R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12314
12315         for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12316         {
12317                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12318                 {
12319                         if (layerindex == 0)
12320                                 GL_AlphaTest(true);
12321                         else
12322                         {
12323                                 GL_AlphaTest(false);
12324                                 GL_DepthFunc(GL_EQUAL);
12325                         }
12326                 }
12327                 GL_DepthMask(layer->depthmask && writedepth);
12328                 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12329                 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12330                 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12331                 switch (layer->type)
12332                 {
12333                 case TEXTURELAYERTYPE_LITTEXTURE:
12334                         if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
12335                         {
12336                                 // two-pass lit texture with 2x rgbscale
12337                                 // first the lightmap pass
12338                                 R_Mesh_TexBind(0, r_texture_white);
12339                                 R_Mesh_TexMatrix(0, NULL);
12340                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12341                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12342                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12343                                         RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
12344                                 else if (FAKELIGHT_ENABLED)
12345                                         RSurf_DrawBatch_GL11_FakeLight(1, 1, 1, 1, false, false);
12346                                 else if (rsurface.uselightmaptexture)
12347                                         RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
12348                                 else
12349                                         RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
12350                                 // then apply the texture to it
12351                                 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
12352                                 R_Mesh_TexBind(0, layer->texture);
12353                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12354                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12355                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12356                                 RSurf_DrawBatch_GL11_Unlit(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);
12357                         }
12358                         else
12359                         {
12360                                 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
12361                                 R_Mesh_TexBind(0, layer->texture);
12362                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12363                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12364                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12365                                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12366                                         RSurf_DrawBatch_GL11_VertexShade(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);
12367                                 else
12368                                         RSurf_DrawBatch_GL11_VertexColor(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);
12369                         }
12370                         break;
12371                 case TEXTURELAYERTYPE_TEXTURE:
12372                         // singletexture unlit texture with transparency support
12373                         R_Mesh_TexBind(0, layer->texture);
12374                         R_Mesh_TexMatrix(0, &layer->texmatrix);
12375                         R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12376                         R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12377                         RSurf_DrawBatch_GL11_Unlit(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);
12378                         break;
12379                 case TEXTURELAYERTYPE_FOG:
12380                         // singletexture fogging
12381                         if (layer->texture)
12382                         {
12383                                 R_Mesh_TexBind(0, layer->texture);
12384                                 R_Mesh_TexMatrix(0, &layer->texmatrix);
12385                                 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12386                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12387                         }
12388                         else
12389                         {
12390                                 R_Mesh_TexBind(0, 0);
12391                                 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12392                         }
12393                         // generate a color array for the fog pass
12394                         R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
12395                         RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
12396                         RSurf_DrawBatch();
12397                         break;
12398                 default:
12399                         Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12400                 }
12401         }
12402         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12403         {
12404                 GL_DepthFunc(GL_LEQUAL);
12405                 GL_AlphaTest(false);
12406         }
12407 }
12408
12409 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12410 {
12411         int vi;
12412         int j;
12413         r_vertexgeneric_t *batchvertex;
12414         float c[4];
12415
12416 //      R_Mesh_ResetTextureState();
12417         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12418
12419         if(rsurface.texture && rsurface.texture->currentskinframe)
12420         {
12421                 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
12422                 c[3] *= rsurface.texture->currentalpha;
12423         }
12424         else
12425         {
12426                 c[0] = 1;
12427                 c[1] = 0;
12428                 c[2] = 1;
12429                 c[3] = 1;
12430         }
12431
12432         if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
12433         {
12434                 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
12435                 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
12436                 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
12437         }
12438
12439         // brighten it up (as texture value 127 means "unlit")
12440         c[0] *= 2 * r_refdef.view.colorscale;
12441         c[1] *= 2 * r_refdef.view.colorscale;
12442         c[2] *= 2 * r_refdef.view.colorscale;
12443
12444         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
12445                 c[3] *= r_wateralpha.value;
12446
12447         if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
12448         {
12449                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12450                 GL_DepthMask(false);
12451         }
12452         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
12453         {
12454                 GL_BlendFunc(GL_ONE, GL_ONE);
12455                 GL_DepthMask(false);
12456         }
12457         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12458         {
12459                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
12460                 GL_DepthMask(false);
12461         }
12462         else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
12463         {
12464                 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
12465                 GL_DepthMask(false);
12466         }
12467         else
12468         {
12469                 GL_BlendFunc(GL_ONE, GL_ZERO);
12470                 GL_DepthMask(writedepth);
12471         }
12472
12473         if (r_showsurfaces.integer == 3)
12474         {
12475                 rsurface.passcolor4f = NULL;
12476
12477                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
12478                 {
12479                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12480
12481                         rsurface.passcolor4f = NULL;
12482                         rsurface.passcolor4f_vertexbuffer = 0;
12483                         rsurface.passcolor4f_bufferoffset = 0;
12484                 }
12485                 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12486                 {
12487                         qboolean applycolor = true;
12488                         float one = 1.0;
12489
12490                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12491
12492                         r_refdef.lightmapintensity = 1;
12493                         RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
12494                         r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12495                 }
12496                 else if (FAKELIGHT_ENABLED)
12497                 {
12498                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12499
12500                         r_refdef.lightmapintensity = r_fakelight_intensity.value;
12501                         RSurf_DrawBatch_GL11_ApplyFakeLight();
12502                         r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12503                 }
12504                 else
12505                 {
12506                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12507
12508                         rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12509                         rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12510                         rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12511                 }
12512
12513                 if(!rsurface.passcolor4f)
12514                         RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
12515
12516                 RSurf_DrawBatch_GL11_ApplyAmbient();
12517                 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
12518                 if(r_refdef.fogenabled)
12519                         RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
12520                 RSurf_DrawBatch_GL11_ClampColor();
12521
12522                 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
12523                 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12524                 RSurf_DrawBatch();
12525         }
12526         else if (!r_refdef.view.showdebug)
12527         {
12528                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12529                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12530                 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12531                 {
12532                         VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12533                         Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
12534                 }
12535                 R_Mesh_PrepareVertices_Generic_Unlock();
12536                 RSurf_DrawBatch();
12537         }
12538         else if (r_showsurfaces.integer == 4)
12539         {
12540                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12541                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12542                 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12543                 {
12544                         unsigned char c = vi << 3;
12545                         VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12546                         Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
12547                 }
12548                 R_Mesh_PrepareVertices_Generic_Unlock();
12549                 RSurf_DrawBatch();
12550         }
12551         else if (r_showsurfaces.integer == 2)
12552         {
12553                 const int *e;
12554                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12555                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
12556                 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
12557                 {
12558                         unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
12559                         VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
12560                         VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
12561                         VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
12562                         Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
12563                         Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
12564                         Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
12565                 }
12566                 R_Mesh_PrepareVertices_Generic_Unlock();
12567                 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
12568         }
12569         else
12570         {
12571                 int texturesurfaceindex;
12572                 int k;
12573                 const msurface_t *surface;
12574                 unsigned char surfacecolor4ub[4];
12575                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12576                 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
12577                 vi = 0;
12578                 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
12579                 {
12580                         surface = texturesurfacelist[texturesurfaceindex];
12581                         k = (int)(((size_t)surface) / sizeof(msurface_t));
12582                         Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
12583                         for (j = 0;j < surface->num_vertices;j++)
12584                         {
12585                                 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12586                                 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
12587                                 vi++;
12588                         }
12589                 }
12590                 R_Mesh_PrepareVertices_Generic_Unlock();
12591                 RSurf_DrawBatch();
12592         }
12593 }
12594
12595 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12596 {
12597         CHECKGLERROR
12598         RSurf_SetupDepthAndCulling();
12599         if (r_showsurfaces.integer)
12600         {
12601                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12602                 return;
12603         }
12604         switch (vid.renderpath)
12605         {
12606         case RENDERPATH_GL20:
12607         case RENDERPATH_D3D9:
12608         case RENDERPATH_D3D10:
12609         case RENDERPATH_D3D11:
12610         case RENDERPATH_SOFT:
12611         case RENDERPATH_GLES2:
12612                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12613                 break;
12614         case RENDERPATH_GL13:
12615                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12616                 break;
12617         case RENDERPATH_GL11:
12618                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12619                 break;
12620         }
12621         CHECKGLERROR
12622 }
12623
12624 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12625 {
12626         CHECKGLERROR
12627         RSurf_SetupDepthAndCulling();
12628         if (r_showsurfaces.integer)
12629         {
12630                 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12631                 return;
12632         }
12633         switch (vid.renderpath)
12634         {
12635         case RENDERPATH_GL20:
12636         case RENDERPATH_D3D9:
12637         case RENDERPATH_D3D10:
12638         case RENDERPATH_D3D11:
12639         case RENDERPATH_SOFT:
12640         case RENDERPATH_GLES2:
12641                 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12642                 break;
12643         case RENDERPATH_GL13:
12644                 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12645                 break;
12646         case RENDERPATH_GL11:
12647                 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12648                 break;
12649         }
12650         CHECKGLERROR
12651 }
12652
12653 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12654 {
12655         int i, j;
12656         int texturenumsurfaces, endsurface;
12657         texture_t *texture;
12658         const msurface_t *surface;
12659 #define MAXBATCH_TRANSPARENTSURFACES 256
12660         const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
12661
12662         // if the model is static it doesn't matter what value we give for
12663         // wantnormals and wanttangents, so this logic uses only rules applicable
12664         // to a model, knowing that they are meaningless otherwise
12665         if (ent == r_refdef.scene.worldentity)
12666                 RSurf_ActiveWorldEntity();
12667         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12668                 RSurf_ActiveModelEntity(ent, false, false, false);
12669         else
12670         {
12671                 switch (vid.renderpath)
12672                 {
12673                 case RENDERPATH_GL20:
12674                 case RENDERPATH_D3D9:
12675                 case RENDERPATH_D3D10:
12676                 case RENDERPATH_D3D11:
12677                 case RENDERPATH_SOFT:
12678                 case RENDERPATH_GLES2:
12679                         RSurf_ActiveModelEntity(ent, true, true, false);
12680                         break;
12681                 case RENDERPATH_GL13:
12682                 case RENDERPATH_GL11:
12683                         RSurf_ActiveModelEntity(ent, true, false, false);
12684                         break;
12685                 }
12686         }
12687
12688         if (r_transparentdepthmasking.integer)
12689         {
12690                 qboolean setup = false;
12691                 for (i = 0;i < numsurfaces;i = j)
12692                 {
12693                         j = i + 1;
12694                         surface = rsurface.modelsurfaces + surfacelist[i];
12695                         texture = surface->texture;
12696                         rsurface.texture = R_GetCurrentTexture(texture);
12697                         rsurface.lightmaptexture = NULL;
12698                         rsurface.deluxemaptexture = NULL;
12699                         rsurface.uselightmaptexture = false;
12700                         // scan ahead until we find a different texture
12701                         endsurface = min(i + 1024, numsurfaces);
12702                         texturenumsurfaces = 0;
12703                         texturesurfacelist[texturenumsurfaces++] = surface;
12704                         for (;j < endsurface;j++)
12705                         {
12706                                 surface = rsurface.modelsurfaces + surfacelist[j];
12707                                 if (texture != surface->texture)
12708                                         break;
12709                                 texturesurfacelist[texturenumsurfaces++] = surface;
12710                         }
12711                         if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
12712                                 continue;
12713                         // render the range of surfaces as depth
12714                         if (!setup)
12715                         {
12716                                 setup = true;
12717                                 GL_ColorMask(0,0,0,0);
12718                                 GL_Color(1,1,1,1);
12719                                 GL_DepthTest(true);
12720                                 GL_BlendFunc(GL_ONE, GL_ZERO);
12721                                 GL_DepthMask(true);
12722 //                              R_Mesh_ResetTextureState();
12723                                 R_SetupShader_DepthOrShadow();
12724                         }
12725                         RSurf_SetupDepthAndCulling();
12726                         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
12727                         if (rsurface.batchvertex3fbuffer)
12728                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
12729                         else
12730                                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
12731                         RSurf_DrawBatch();
12732                 }
12733                 if (setup)
12734                         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12735         }
12736
12737         for (i = 0;i < numsurfaces;i = j)
12738         {
12739                 j = i + 1;
12740                 surface = rsurface.modelsurfaces + surfacelist[i];
12741                 texture = surface->texture;
12742                 rsurface.texture = R_GetCurrentTexture(texture);
12743                 // scan ahead until we find a different texture
12744                 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
12745                 texturenumsurfaces = 0;
12746                 texturesurfacelist[texturenumsurfaces++] = surface;
12747                 if(FAKELIGHT_ENABLED)
12748                 {
12749                         rsurface.lightmaptexture = NULL;
12750                         rsurface.deluxemaptexture = NULL;
12751                         rsurface.uselightmaptexture = false;
12752                         for (;j < endsurface;j++)
12753                         {
12754                                 surface = rsurface.modelsurfaces + surfacelist[j];
12755                                 if (texture != surface->texture)
12756                                         break;
12757                                 texturesurfacelist[texturenumsurfaces++] = surface;
12758                         }
12759                 }
12760                 else
12761                 {
12762                         rsurface.lightmaptexture = surface->lightmaptexture;
12763                         rsurface.deluxemaptexture = surface->deluxemaptexture;
12764                         rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
12765                         for (;j < endsurface;j++)
12766                         {
12767                                 surface = rsurface.modelsurfaces + surfacelist[j];
12768                                 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
12769                                         break;
12770                                 texturesurfacelist[texturenumsurfaces++] = surface;
12771                         }
12772                 }
12773                 // render the range of surfaces
12774                 if (ent == r_refdef.scene.worldentity)
12775                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12776                 else
12777                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12778         }
12779         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12780 }
12781
12782 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
12783 {
12784         // transparent surfaces get pushed off into the transparent queue
12785         int surfacelistindex;
12786         const msurface_t *surface;
12787         vec3_t tempcenter, center;
12788         for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
12789         {
12790                 surface = texturesurfacelist[surfacelistindex];
12791                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
12792                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
12793                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
12794                 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
12795                 if (queueentity->transparent_offset) // transparent offset
12796                 {
12797                         center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
12798                         center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
12799                         center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
12800                 }
12801                 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
12802         }
12803 }
12804
12805 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12806 {
12807         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12808                 return;
12809         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12810                 return;
12811         RSurf_SetupDepthAndCulling();
12812         RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
12813         if (rsurface.batchvertex3fbuffer)
12814                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
12815         else
12816                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
12817         RSurf_DrawBatch();
12818 }
12819
12820 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
12821 {
12822         const entity_render_t *queueentity = r_refdef.scene.worldentity;
12823         CHECKGLERROR
12824         if (depthonly)
12825                 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12826         else if (prepass)
12827         {
12828                 if (!rsurface.texture->currentnumlayers)
12829                         return;
12830                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12831                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12832                 else
12833                         R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12834         }
12835         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12836                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12837         else if (!rsurface.texture->currentnumlayers)
12838                 return;
12839         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12840         {
12841                 // in the deferred case, transparent surfaces were queued during prepass
12842                 if (!r_shadow_usingdeferredprepass)
12843                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12844         }
12845         else
12846         {
12847                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12848                 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12849         }
12850         CHECKGLERROR
12851 }
12852
12853 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12854 {
12855         int i, j;
12856         texture_t *texture;
12857         R_FrameData_SetMark();
12858         // break the surface list down into batches by texture and use of lightmapping
12859         for (i = 0;i < numsurfaces;i = j)
12860         {
12861                 j = i + 1;
12862                 // texture is the base texture pointer, rsurface.texture is the
12863                 // current frame/skin the texture is directing us to use (for example
12864                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12865                 // use skin 1 instead)
12866                 texture = surfacelist[i]->texture;
12867                 rsurface.texture = R_GetCurrentTexture(texture);
12868                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12869                 {
12870                         // if this texture is not the kind we want, skip ahead to the next one
12871                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12872                                 ;
12873                         continue;
12874                 }
12875                 if(FAKELIGHT_ENABLED || depthonly || prepass)
12876                 {
12877                         rsurface.lightmaptexture = NULL;
12878                         rsurface.deluxemaptexture = NULL;
12879                         rsurface.uselightmaptexture = false;
12880                         // simply scan ahead until we find a different texture or lightmap state
12881                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12882                                 ;
12883                 }
12884                 else
12885                 {
12886                         rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12887                         rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12888                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12889                         // simply scan ahead until we find a different texture or lightmap state
12890                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12891                                 ;
12892                 }
12893                 // render the range of surfaces
12894                 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12895         }
12896         R_FrameData_ReturnToMark();
12897 }
12898
12899 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12900 {
12901         CHECKGLERROR
12902         if (depthonly)
12903                 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12904         else if (prepass)
12905         {
12906                 if (!rsurface.texture->currentnumlayers)
12907                         return;
12908                 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12909                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12910                 else
12911                         R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12912         }
12913         else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12914                 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12915         else if (!rsurface.texture->currentnumlayers)
12916                 return;
12917         else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12918         {
12919                 // in the deferred case, transparent surfaces were queued during prepass
12920                 if (!r_shadow_usingdeferredprepass)
12921                         R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12922         }
12923         else
12924         {
12925                 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12926                 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12927         }
12928         CHECKGLERROR
12929 }
12930
12931 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12932 {
12933         int i, j;
12934         texture_t *texture;
12935         R_FrameData_SetMark();
12936         // break the surface list down into batches by texture and use of lightmapping
12937         for (i = 0;i < numsurfaces;i = j)
12938         {
12939                 j = i + 1;
12940                 // texture is the base texture pointer, rsurface.texture is the
12941                 // current frame/skin the texture is directing us to use (for example
12942                 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12943                 // use skin 1 instead)
12944                 texture = surfacelist[i]->texture;
12945                 rsurface.texture = R_GetCurrentTexture(texture);
12946                 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12947                 {
12948                         // if this texture is not the kind we want, skip ahead to the next one
12949                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12950                                 ;
12951                         continue;
12952                 }
12953                 if(FAKELIGHT_ENABLED || depthonly || prepass)
12954                 {
12955                         rsurface.lightmaptexture = NULL;
12956                         rsurface.deluxemaptexture = NULL;
12957                         rsurface.uselightmaptexture = false;
12958                         // simply scan ahead until we find a different texture or lightmap state
12959                         for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12960                                 ;
12961                 }
12962                 else
12963                 {
12964                         rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12965                         rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12966                         rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12967                         // simply scan ahead until we find a different texture or lightmap state
12968                         for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12969                                 ;
12970                 }
12971                 // render the range of surfaces
12972                 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12973         }
12974         R_FrameData_ReturnToMark();
12975 }
12976
12977 float locboxvertex3f[6*4*3] =
12978 {
12979         1,0,1, 1,0,0, 1,1,0, 1,1,1,
12980         0,1,1, 0,1,0, 0,0,0, 0,0,1,
12981         1,1,1, 1,1,0, 0,1,0, 0,1,1,
12982         0,0,1, 0,0,0, 1,0,0, 1,0,1,
12983         0,0,1, 1,0,1, 1,1,1, 0,1,1,
12984         1,0,0, 0,0,0, 0,1,0, 1,1,0
12985 };
12986
12987 unsigned short locboxelements[6*2*3] =
12988 {
12989          0, 1, 2, 0, 2, 3,
12990          4, 5, 6, 4, 6, 7,
12991          8, 9,10, 8,10,11,
12992         12,13,14, 12,14,15,
12993         16,17,18, 16,18,19,
12994         20,21,22, 20,22,23
12995 };
12996
12997 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12998 {
12999         int i, j;
13000         cl_locnode_t *loc = (cl_locnode_t *)ent;
13001         vec3_t mins, size;
13002         float vertex3f[6*4*3];
13003         CHECKGLERROR
13004         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13005         GL_DepthMask(false);
13006         GL_DepthRange(0, 1);
13007         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13008         GL_DepthTest(true);
13009         GL_CullFace(GL_NONE);
13010         R_EntityMatrix(&identitymatrix);
13011
13012 //      R_Mesh_ResetTextureState();
13013
13014         i = surfacelist[0];
13015         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13016                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13017                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13018                         surfacelist[0] < 0 ? 0.5f : 0.125f);
13019
13020         if (VectorCompare(loc->mins, loc->maxs))
13021         {
13022                 VectorSet(size, 2, 2, 2);
13023                 VectorMA(loc->mins, -0.5f, size, mins);
13024         }
13025         else
13026         {
13027                 VectorCopy(loc->mins, mins);
13028                 VectorSubtract(loc->maxs, loc->mins, size);
13029         }
13030
13031         for (i = 0;i < 6*4*3;)
13032                 for (j = 0;j < 3;j++, i++)
13033                         vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
13034
13035         R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
13036         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13037         R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
13038 }
13039
13040 void R_DrawLocs(void)
13041 {
13042         int index;
13043         cl_locnode_t *loc, *nearestloc;
13044         vec3_t center;
13045         nearestloc = CL_Locs_FindNearest(cl.movement_origin);
13046         for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
13047         {
13048                 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
13049                 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
13050         }
13051 }
13052
13053 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
13054 {
13055         if (decalsystem->decals)
13056                 Mem_Free(decalsystem->decals);
13057         memset(decalsystem, 0, sizeof(*decalsystem));
13058 }
13059
13060 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)
13061 {
13062         tridecal_t *decal;
13063         tridecal_t *decals;
13064         int i;
13065
13066         // expand or initialize the system
13067         if (decalsystem->maxdecals <= decalsystem->numdecals)
13068         {
13069                 decalsystem_t old = *decalsystem;
13070                 qboolean useshortelements;
13071                 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
13072                 useshortelements = decalsystem->maxdecals * 3 <= 65536;
13073                 decalsystem->decals = (tridecal_t *)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)));
13074                 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
13075                 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
13076                 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
13077                 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
13078                 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
13079                 if (decalsystem->numdecals)
13080                         memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
13081                 if (old.decals)
13082                         Mem_Free(old.decals);
13083                 for (i = 0;i < decalsystem->maxdecals*3;i++)
13084                         decalsystem->element3i[i] = i;
13085                 if (useshortelements)
13086                         for (i = 0;i < decalsystem->maxdecals*3;i++)
13087                                 decalsystem->element3s[i] = i;
13088         }
13089
13090         // grab a decal and search for another free slot for the next one
13091         decals = decalsystem->decals;
13092         decal = decalsystem->decals + (i = decalsystem->freedecal++);
13093         for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
13094                 ;
13095         decalsystem->freedecal = i;
13096         if (decalsystem->numdecals <= i)
13097                 decalsystem->numdecals = i + 1;
13098
13099         // initialize the decal
13100         decal->lived = 0;
13101         decal->triangleindex = triangleindex;
13102         decal->surfaceindex = surfaceindex;
13103         decal->decalsequence = decalsequence;
13104         decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
13105         decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
13106         decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
13107         decal->color4ub[0][3] = 255;
13108         decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
13109         decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
13110         decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
13111         decal->color4ub[1][3] = 255;
13112         decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
13113         decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
13114         decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
13115         decal->color4ub[2][3] = 255;
13116         decal->vertex3f[0][0] = v0[0];
13117         decal->vertex3f[0][1] = v0[1];
13118         decal->vertex3f[0][2] = v0[2];
13119         decal->vertex3f[1][0] = v1[0];
13120         decal->vertex3f[1][1] = v1[1];
13121         decal->vertex3f[1][2] = v1[2];
13122         decal->vertex3f[2][0] = v2[0];
13123         decal->vertex3f[2][1] = v2[1];
13124         decal->vertex3f[2][2] = v2[2];
13125         decal->texcoord2f[0][0] = t0[0];
13126         decal->texcoord2f[0][1] = t0[1];
13127         decal->texcoord2f[1][0] = t1[0];
13128         decal->texcoord2f[1][1] = t1[1];
13129         decal->texcoord2f[2][0] = t2[0];
13130         decal->texcoord2f[2][1] = t2[1];
13131 }
13132
13133 extern cvar_t cl_decals_bias;
13134 extern cvar_t cl_decals_models;
13135 extern cvar_t cl_decals_newsystem_intensitymultiplier;
13136 // baseparms, parms, temps
13137 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)
13138 {
13139         int cornerindex;
13140         int index;
13141         float v[9][3];
13142         const float *vertex3f;
13143         int numpoints;
13144         float points[2][9][3];
13145         float temp[3];
13146         float tc[9][2];
13147         float f;
13148         float c[9][4];
13149         const int *e;
13150
13151         e = rsurface.modelelement3i + 3*triangleindex;
13152
13153         vertex3f = rsurface.modelvertex3f;
13154
13155         for (cornerindex = 0;cornerindex < 3;cornerindex++)
13156         {
13157                 index = 3*e[cornerindex];
13158                 VectorCopy(vertex3f + index, v[cornerindex]);
13159         }
13160         // cull backfaces
13161         //TriangleNormal(v[0], v[1], v[2], normal);
13162         //if (DotProduct(normal, localnormal) < 0.0f)
13163         //      continue;
13164         // clip by each of the box planes formed from the projection matrix
13165         // if anything survives, we emit the decal
13166         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]);
13167         if (numpoints < 3)
13168                 return;
13169         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]);
13170         if (numpoints < 3)
13171                 return;
13172         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]);
13173         if (numpoints < 3)
13174                 return;
13175         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]);
13176         if (numpoints < 3)
13177                 return;
13178         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]);
13179         if (numpoints < 3)
13180                 return;
13181         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]);
13182         if (numpoints < 3)
13183                 return;
13184         // some part of the triangle survived, so we have to accept it...
13185         if (dynamic)
13186         {
13187                 // dynamic always uses the original triangle
13188                 numpoints = 3;
13189                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13190                 {
13191                         index = 3*e[cornerindex];
13192                         VectorCopy(vertex3f + index, v[cornerindex]);
13193                 }
13194         }
13195         for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
13196         {
13197                 // convert vertex positions to texcoords
13198                 Matrix4x4_Transform(projection, v[cornerindex], temp);
13199                 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
13200                 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
13201                 // calculate distance fade from the projection origin
13202                 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
13203                 f = bound(0.0f, f, 1.0f);
13204                 c[cornerindex][0] = r * f;
13205                 c[cornerindex][1] = g * f;
13206                 c[cornerindex][2] = b * f;
13207                 c[cornerindex][3] = 1.0f;
13208                 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
13209         }
13210         if (dynamic)
13211                 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);
13212         else
13213                 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
13214                         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);
13215 }
13216 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)
13217 {
13218         matrix4x4_t projection;
13219         decalsystem_t *decalsystem;
13220         qboolean dynamic;
13221         dp_model_t *model;
13222         const msurface_t *surface;
13223         const msurface_t *surfaces;
13224         const int *surfacelist;
13225         const texture_t *texture;
13226         int numtriangles;
13227         int numsurfacelist;
13228         int surfacelistindex;
13229         int surfaceindex;
13230         int triangleindex;
13231         float localorigin[3];
13232         float localnormal[3];
13233         float localmins[3];
13234         float localmaxs[3];
13235         float localsize;
13236         //float normal[3];
13237         float planes[6][4];
13238         float angles[3];
13239         bih_t *bih;
13240         int bih_triangles_count;
13241         int bih_triangles[256];
13242         int bih_surfaces[256];
13243
13244         decalsystem = &ent->decalsystem;
13245         model = ent->model;
13246         if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
13247         {
13248                 R_DecalSystem_Reset(&ent->decalsystem);
13249                 return;
13250         }
13251
13252         if (!model->brush.data_leafs && !cl_decals_models.integer)
13253         {
13254                 if (decalsystem->model)
13255                         R_DecalSystem_Reset(decalsystem);
13256                 return;
13257         }
13258
13259         if (decalsystem->model != model)
13260                 R_DecalSystem_Reset(decalsystem);
13261         decalsystem->model = model;
13262
13263         RSurf_ActiveModelEntity(ent, false, false, false);
13264
13265         Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
13266         Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
13267         VectorNormalize(localnormal);
13268         localsize = worldsize*rsurface.inversematrixscale;
13269         localmins[0] = localorigin[0] - localsize;
13270         localmins[1] = localorigin[1] - localsize;
13271         localmins[2] = localorigin[2] - localsize;
13272         localmaxs[0] = localorigin[0] + localsize;
13273         localmaxs[1] = localorigin[1] + localsize;
13274         localmaxs[2] = localorigin[2] + localsize;
13275
13276         //VectorCopy(localnormal, planes[4]);
13277         //VectorVectors(planes[4], planes[2], planes[0]);
13278         AnglesFromVectors(angles, localnormal, NULL, false);
13279         AngleVectors(angles, planes[0], planes[2], planes[4]);
13280         VectorNegate(planes[0], planes[1]);
13281         VectorNegate(planes[2], planes[3]);
13282         VectorNegate(planes[4], planes[5]);
13283         planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
13284         planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
13285         planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
13286         planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
13287         planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
13288         planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
13289
13290 #if 1
13291 // works
13292 {
13293         matrix4x4_t forwardprojection;
13294         Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
13295         Matrix4x4_Invert_Simple(&projection, &forwardprojection);
13296 }
13297 #else
13298 // broken
13299 {
13300         float projectionvector[4][3];
13301         VectorScale(planes[0], ilocalsize, projectionvector[0]);
13302         VectorScale(planes[2], ilocalsize, projectionvector[1]);
13303         VectorScale(planes[4], ilocalsize, projectionvector[2]);
13304         projectionvector[0][0] = planes[0][0] * ilocalsize;
13305         projectionvector[0][1] = planes[1][0] * ilocalsize;
13306         projectionvector[0][2] = planes[2][0] * ilocalsize;
13307         projectionvector[1][0] = planes[0][1] * ilocalsize;
13308         projectionvector[1][1] = planes[1][1] * ilocalsize;
13309         projectionvector[1][2] = planes[2][1] * ilocalsize;
13310         projectionvector[2][0] = planes[0][2] * ilocalsize;
13311         projectionvector[2][1] = planes[1][2] * ilocalsize;
13312         projectionvector[2][2] = planes[2][2] * ilocalsize;
13313         projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
13314         projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
13315         projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
13316         Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
13317 }
13318 #endif
13319
13320         dynamic = model->surfmesh.isanimated;
13321         numsurfacelist = model->nummodelsurfaces;
13322         surfacelist = model->sortedmodelsurfaces;
13323         surfaces = model->data_surfaces;
13324
13325         bih = NULL;
13326         bih_triangles_count = -1;
13327         if(!dynamic)
13328         {
13329                 if(model->render_bih.numleafs)
13330                         bih = &model->render_bih;
13331                 else if(model->collision_bih.numleafs)
13332                         bih = &model->collision_bih;
13333         }
13334         if(bih)
13335                 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
13336         if(bih_triangles_count == 0)
13337                 return;
13338         if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
13339                 return;
13340         if(bih_triangles_count > 0)
13341         {
13342                 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
13343                 {
13344                         surfaceindex = bih_surfaces[triangleindex];
13345                         surface = surfaces + surfaceindex;
13346                         texture = surface->texture;
13347                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13348                                 continue;
13349                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13350                                 continue;
13351                         R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
13352                 }
13353         }
13354         else
13355         {
13356                 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
13357                 {
13358                         surfaceindex = surfacelist[surfacelistindex];
13359                         surface = surfaces + surfaceindex;
13360                         // check cull box first because it rejects more than any other check
13361                         if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
13362                                 continue;
13363                         // skip transparent surfaces
13364                         texture = surface->texture;
13365                         if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13366                                 continue;
13367                         if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13368                                 continue;
13369                         numtriangles = surface->num_triangles;
13370                         for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
13371                                 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
13372                 }
13373         }
13374 }
13375
13376 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
13377 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)
13378 {
13379         int renderentityindex;
13380         float worldmins[3];
13381         float worldmaxs[3];
13382         entity_render_t *ent;
13383
13384         if (!cl_decals_newsystem.integer)
13385                 return;
13386
13387         worldmins[0] = worldorigin[0] - worldsize;
13388         worldmins[1] = worldorigin[1] - worldsize;
13389         worldmins[2] = worldorigin[2] - worldsize;
13390         worldmaxs[0] = worldorigin[0] + worldsize;
13391         worldmaxs[1] = worldorigin[1] + worldsize;
13392         worldmaxs[2] = worldorigin[2] + worldsize;
13393
13394         R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13395
13396         for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
13397         {
13398                 ent = r_refdef.scene.entities[renderentityindex];
13399                 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
13400                         continue;
13401
13402                 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13403         }
13404 }
13405
13406 typedef struct r_decalsystem_splatqueue_s
13407 {
13408         vec3_t worldorigin;
13409         vec3_t worldnormal;
13410         float color[4];
13411         float tcrange[4];
13412         float worldsize;
13413         int decalsequence;
13414 }
13415 r_decalsystem_splatqueue_t;
13416
13417 int r_decalsystem_numqueued = 0;
13418 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
13419
13420 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)
13421 {
13422         r_decalsystem_splatqueue_t *queue;
13423
13424         if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
13425                 return;
13426
13427         queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
13428         VectorCopy(worldorigin, queue->worldorigin);
13429         VectorCopy(worldnormal, queue->worldnormal);
13430         Vector4Set(queue->color, r, g, b, a);
13431         Vector4Set(queue->tcrange, s1, t1, s2, t2);
13432         queue->worldsize = worldsize;
13433         queue->decalsequence = cl.decalsequence++;
13434 }
13435
13436 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
13437 {
13438         int i;
13439         r_decalsystem_splatqueue_t *queue;
13440
13441         for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
13442                 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);
13443         r_decalsystem_numqueued = 0;
13444 }
13445
13446 extern cvar_t cl_decals_max;
13447 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
13448 {
13449         int i;
13450         decalsystem_t *decalsystem = &ent->decalsystem;
13451         int numdecals;
13452         int killsequence;
13453         tridecal_t *decal;
13454         float frametime;
13455         float lifetime;
13456
13457         if (!decalsystem->numdecals)
13458                 return;
13459
13460         if (r_showsurfaces.integer)
13461                 return;
13462
13463         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13464         {
13465                 R_DecalSystem_Reset(decalsystem);
13466                 return;
13467         }
13468
13469         killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
13470         lifetime = cl_decals_time.value + cl_decals_fadetime.value;
13471
13472         if (decalsystem->lastupdatetime)
13473                 frametime = (cl.time - decalsystem->lastupdatetime);
13474         else
13475                 frametime = 0;
13476         decalsystem->lastupdatetime = cl.time;
13477         decal = decalsystem->decals;
13478         numdecals = decalsystem->numdecals;
13479
13480         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13481         {
13482                 if (decal->color4ub[0][3])
13483                 {
13484                         decal->lived += frametime;
13485                         if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
13486                         {
13487                                 memset(decal, 0, sizeof(*decal));
13488                                 if (decalsystem->freedecal > i)
13489                                         decalsystem->freedecal = i;
13490                         }
13491                 }
13492         }
13493         decal = decalsystem->decals;
13494         while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
13495                 numdecals--;
13496
13497         // collapse the array by shuffling the tail decals into the gaps
13498         for (;;)
13499         {
13500                 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
13501                         decalsystem->freedecal++;
13502                 if (decalsystem->freedecal == numdecals)
13503                         break;
13504                 decal[decalsystem->freedecal] = decal[--numdecals];
13505         }
13506
13507         decalsystem->numdecals = numdecals;
13508
13509         if (numdecals <= 0)
13510         {
13511                 // if there are no decals left, reset decalsystem
13512                 R_DecalSystem_Reset(decalsystem);
13513         }
13514 }
13515
13516 extern skinframe_t *decalskinframe;
13517 static void R_DrawModelDecals_Entity(entity_render_t *ent)
13518 {
13519         int i;
13520         decalsystem_t *decalsystem = &ent->decalsystem;
13521         int numdecals;
13522         tridecal_t *decal;
13523         float faderate;
13524         float alpha;
13525         float *v3f;
13526         float *c4f;
13527         float *t2f;
13528         const int *e;
13529         const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
13530         int numtris = 0;
13531
13532         numdecals = decalsystem->numdecals;
13533         if (!numdecals)
13534                 return;
13535
13536         if (r_showsurfaces.integer)
13537                 return;
13538
13539         if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13540         {
13541                 R_DecalSystem_Reset(decalsystem);
13542                 return;
13543         }
13544
13545         // if the model is static it doesn't matter what value we give for
13546         // wantnormals and wanttangents, so this logic uses only rules applicable
13547         // to a model, knowing that they are meaningless otherwise
13548         if (ent == r_refdef.scene.worldentity)
13549                 RSurf_ActiveWorldEntity();
13550         else
13551                 RSurf_ActiveModelEntity(ent, false, false, false);
13552
13553         decalsystem->lastupdatetime = cl.time;
13554         decal = decalsystem->decals;
13555
13556         faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
13557
13558         // update vertex positions for animated models
13559         v3f = decalsystem->vertex3f;
13560         c4f = decalsystem->color4f;
13561         t2f = decalsystem->texcoord2f;
13562         for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13563         {
13564                 if (!decal->color4ub[0][3])
13565                         continue;
13566
13567                 if (surfacevisible && !surfacevisible[decal->surfaceindex])
13568                         continue;
13569
13570                 // update color values for fading decals
13571                 if (decal->lived >= cl_decals_time.value)
13572                 {
13573                         alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
13574                         alpha *= (1.0f/255.0f);
13575                 }
13576                 else
13577                         alpha = 1.0f/255.0f;
13578
13579                 c4f[ 0] = decal->color4ub[0][0] * alpha;
13580                 c4f[ 1] = decal->color4ub[0][1] * alpha;
13581                 c4f[ 2] = decal->color4ub[0][2] * alpha;
13582                 c4f[ 3] = 1;
13583                 c4f[ 4] = decal->color4ub[1][0] * alpha;
13584                 c4f[ 5] = decal->color4ub[1][1] * alpha;
13585                 c4f[ 6] = decal->color4ub[1][2] * alpha;
13586                 c4f[ 7] = 1;
13587                 c4f[ 8] = decal->color4ub[2][0] * alpha;
13588                 c4f[ 9] = decal->color4ub[2][1] * alpha;
13589                 c4f[10] = decal->color4ub[2][2] * alpha;
13590                 c4f[11] = 1;
13591
13592                 t2f[0] = decal->texcoord2f[0][0];
13593                 t2f[1] = decal->texcoord2f[0][1];
13594                 t2f[2] = decal->texcoord2f[1][0];
13595                 t2f[3] = decal->texcoord2f[1][1];
13596                 t2f[4] = decal->texcoord2f[2][0];
13597                 t2f[5] = decal->texcoord2f[2][1];
13598
13599                 // update vertex positions for animated models
13600                 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
13601                 {
13602                         e = rsurface.modelelement3i + 3*decal->triangleindex;
13603                         VectorCopy(rsurface.modelvertex3f + 3*e[0], v3f);
13604                         VectorCopy(rsurface.modelvertex3f + 3*e[1], v3f + 3);
13605                         VectorCopy(rsurface.modelvertex3f + 3*e[2], v3f + 6);
13606                 }
13607                 else
13608                 {
13609                         VectorCopy(decal->vertex3f[0], v3f);
13610                         VectorCopy(decal->vertex3f[1], v3f + 3);
13611                         VectorCopy(decal->vertex3f[2], v3f + 6);
13612                 }
13613
13614                 if (r_refdef.fogenabled)
13615                 {
13616                         alpha = RSurf_FogVertex(v3f);
13617                         VectorScale(c4f, alpha, c4f);
13618                         alpha = RSurf_FogVertex(v3f + 3);
13619                         VectorScale(c4f + 4, alpha, c4f + 4);
13620                         alpha = RSurf_FogVertex(v3f + 6);
13621                         VectorScale(c4f + 8, alpha, c4f + 8);
13622                 }
13623
13624                 v3f += 9;
13625                 c4f += 12;
13626                 t2f += 6;
13627                 numtris++;
13628         }
13629
13630         if (numtris > 0)
13631         {
13632                 r_refdef.stats.drawndecals += numtris;
13633
13634                 // now render the decals all at once
13635                 // (this assumes they all use one particle font texture!)
13636                 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);
13637 //              R_Mesh_ResetTextureState();
13638                 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
13639                 GL_DepthMask(false);
13640                 GL_DepthRange(0, 1);
13641                 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
13642                 GL_DepthTest(true);
13643                 GL_CullFace(GL_NONE);
13644                 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
13645                 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
13646                 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
13647         }
13648 }
13649
13650 static void R_DrawModelDecals(void)
13651 {
13652         int i, numdecals;
13653
13654         // fade faster when there are too many decals
13655         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13656         for (i = 0;i < r_refdef.scene.numentities;i++)
13657                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13658
13659         R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
13660         for (i = 0;i < r_refdef.scene.numentities;i++)
13661                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13662                         R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
13663
13664         R_DecalSystem_ApplySplatEntitiesQueue();
13665
13666         numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13667         for (i = 0;i < r_refdef.scene.numentities;i++)
13668                 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13669
13670         r_refdef.stats.totaldecals += numdecals;
13671
13672         if (r_showsurfaces.integer)
13673                 return;
13674
13675         R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
13676
13677         for (i = 0;i < r_refdef.scene.numentities;i++)
13678         {
13679                 if (!r_refdef.viewcache.entityvisible[i])
13680                         continue;
13681                 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13682                         R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
13683         }
13684 }
13685
13686 extern cvar_t mod_collision_bih;
13687 void R_DrawDebugModel(void)
13688 {
13689         entity_render_t *ent = rsurface.entity;
13690         int i, j, k, l, flagsmask;
13691         const msurface_t *surface;
13692         dp_model_t *model = ent->model;
13693         vec3_t v;
13694
13695         switch(vid.renderpath)
13696         {
13697         case RENDERPATH_GL11:
13698         case RENDERPATH_GL13:
13699         case RENDERPATH_GL20:
13700                 break;
13701         case RENDERPATH_D3D9:
13702                 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13703                 return;
13704         case RENDERPATH_D3D10:
13705                 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13706                 return;
13707         case RENDERPATH_D3D11:
13708                 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13709                 return;
13710         case RENDERPATH_SOFT:
13711                 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13712                 return;
13713         case RENDERPATH_GLES2:
13714                 //Con_DPrintf("FIXME GLES2 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13715                 return;
13716         }
13717
13718         flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
13719
13720 //      R_Mesh_ResetTextureState();
13721         R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13722         GL_DepthRange(0, 1);
13723         GL_DepthTest(!r_showdisabledepthtest.integer);
13724         GL_DepthMask(false);
13725         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13726
13727         if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
13728         {
13729                 int triangleindex;
13730                 int bihleafindex;
13731                 qboolean cullbox = ent == r_refdef.scene.worldentity;
13732                 const q3mbrush_t *brush;
13733                 const bih_t *bih = &model->collision_bih;
13734                 const bih_leaf_t *bihleaf;
13735                 float vertex3f[3][3];
13736                 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
13737                 cullbox = false;
13738                 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
13739                 {
13740                         if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
13741                                 continue;
13742                         switch (bihleaf->type)
13743                         {
13744                         case BIH_BRUSH:
13745                                 brush = model->brush.data_brushes + bihleaf->itemindex;
13746                                 if (brush->colbrushf && brush->colbrushf->numtriangles)
13747                                 {
13748                                         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);
13749                                         R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
13750                                         R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
13751                                 }
13752                                 break;
13753                         case BIH_COLLISIONTRIANGLE:
13754                                 triangleindex = bihleaf->itemindex;
13755                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
13756                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
13757                                 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
13758                                 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);
13759                                 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13760                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13761                                 break;
13762                         case BIH_RENDERTRIANGLE:
13763                                 triangleindex = bihleaf->itemindex;
13764                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
13765                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
13766                                 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
13767                                 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);
13768                                 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13769                                 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13770                                 break;
13771                         }
13772                 }
13773         }
13774
13775         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13776
13777         if (r_showtris.integer || (r_shownormals.value != 0))
13778         {
13779                 if (r_showdisabledepthtest.integer)
13780                 {
13781                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13782                         GL_DepthMask(false);
13783                 }
13784                 else
13785                 {
13786                         GL_BlendFunc(GL_ONE, GL_ZERO);
13787                         GL_DepthMask(true);
13788                 }
13789                 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
13790                 {
13791                         if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
13792                                 continue;
13793                         rsurface.texture = R_GetCurrentTexture(surface->texture);
13794                         if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
13795                         {
13796                                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
13797                                 if (r_showtris.value > 0)
13798                                 {
13799                                         if (!rsurface.texture->currentlayers->depthmask)
13800                                                 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
13801                                         else if (ent == r_refdef.scene.worldentity)
13802                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
13803                                         else
13804                                                 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
13805                                         R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
13806                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
13807                                         RSurf_DrawBatch();
13808                                         qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
13809                                         CHECKGLERROR
13810                                 }
13811                                 if (r_shownormals.value < 0)
13812                                 {
13813                                         qglBegin(GL_LINES);
13814                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13815                                         {
13816                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13817                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13818                                                 qglVertex3f(v[0], v[1], v[2]);
13819                                                 VectorMA(v, -r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13820                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13821                                                 qglVertex3f(v[0], v[1], v[2]);
13822                                         }
13823                                         qglEnd();
13824                                         CHECKGLERROR
13825                                 }
13826                                 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
13827                                 {
13828                                         qglBegin(GL_LINES);
13829                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13830                                         {
13831                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13832                                                 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13833                                                 qglVertex3f(v[0], v[1], v[2]);
13834                                                 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13835                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13836                                                 qglVertex3f(v[0], v[1], v[2]);
13837                                         }
13838                                         qglEnd();
13839                                         CHECKGLERROR
13840                                         qglBegin(GL_LINES);
13841                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13842                                         {
13843                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13844                                                 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13845                                                 qglVertex3f(v[0], v[1], v[2]);
13846                                                 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
13847                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13848                                                 qglVertex3f(v[0], v[1], v[2]);
13849                                         }
13850                                         qglEnd();
13851                                         CHECKGLERROR
13852                                         qglBegin(GL_LINES);
13853                                         for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13854                                         {
13855                                                 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13856                                                 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13857                                                 qglVertex3f(v[0], v[1], v[2]);
13858                                                 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13859                                                 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13860                                                 qglVertex3f(v[0], v[1], v[2]);
13861                                         }
13862                                         qglEnd();
13863                                         CHECKGLERROR
13864                                 }
13865                         }
13866                 }
13867                 rsurface.texture = NULL;
13868         }
13869 }
13870
13871 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13872 int r_maxsurfacelist = 0;
13873 const msurface_t **r_surfacelist = NULL;
13874 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13875 {
13876         int i, j, endj, flagsmask;
13877         dp_model_t *model = r_refdef.scene.worldmodel;
13878         msurface_t *surfaces;
13879         unsigned char *update;
13880         int numsurfacelist = 0;
13881         if (model == NULL)
13882                 return;
13883
13884         if (r_maxsurfacelist < model->num_surfaces)
13885         {
13886                 r_maxsurfacelist = model->num_surfaces;
13887                 if (r_surfacelist)
13888                         Mem_Free((msurface_t**)r_surfacelist);
13889                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13890         }
13891
13892         RSurf_ActiveWorldEntity();
13893
13894         surfaces = model->data_surfaces;
13895         update = model->brushq1.lightmapupdateflags;
13896
13897         // update light styles on this submodel
13898         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13899         {
13900                 model_brush_lightstyleinfo_t *style;
13901                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13902                 {
13903                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
13904                         {
13905                                 int *list = style->surfacelist;
13906                                 style->value = r_refdef.scene.lightstylevalue[style->style];
13907                                 for (j = 0;j < style->numsurfaces;j++)
13908                                         update[list[j]] = true;
13909                         }
13910                 }
13911         }
13912
13913         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13914
13915         if (debug)
13916         {
13917                 R_DrawDebugModel();
13918                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13919                 return;
13920         }
13921
13922         rsurface.lightmaptexture = NULL;
13923         rsurface.deluxemaptexture = NULL;
13924         rsurface.uselightmaptexture = false;
13925         rsurface.texture = NULL;
13926         rsurface.rtlight = NULL;
13927         numsurfacelist = 0;
13928         // add visible surfaces to draw list
13929         for (i = 0;i < model->nummodelsurfaces;i++)
13930         {
13931                 j = model->sortedmodelsurfaces[i];
13932                 if (r_refdef.viewcache.world_surfacevisible[j])
13933                         r_surfacelist[numsurfacelist++] = surfaces + j;
13934         }
13935         // update lightmaps if needed
13936         if (model->brushq1.firstrender)
13937         {
13938                 model->brushq1.firstrender = false;
13939                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13940                         if (update[j])
13941                                 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13942         }
13943         else if (update)
13944         {
13945                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13946                         if (r_refdef.viewcache.world_surfacevisible[j])
13947                                 if (update[j])
13948                                         R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13949         }
13950         // don't do anything if there were no surfaces
13951         if (!numsurfacelist)
13952         {
13953                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13954                 return;
13955         }
13956         R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13957
13958         // add to stats if desired
13959         if (r_speeds.integer && !skysurfaces && !depthonly)
13960         {
13961                 r_refdef.stats.world_surfaces += numsurfacelist;
13962                 for (j = 0;j < numsurfacelist;j++)
13963                         r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13964         }
13965
13966         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13967 }
13968
13969 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13970 {
13971         int i, j, endj, flagsmask;
13972         dp_model_t *model = ent->model;
13973         msurface_t *surfaces;
13974         unsigned char *update;
13975         int numsurfacelist = 0;
13976         if (model == NULL)
13977                 return;
13978
13979         if (r_maxsurfacelist < model->num_surfaces)
13980         {
13981                 r_maxsurfacelist = model->num_surfaces;
13982                 if (r_surfacelist)
13983                         Mem_Free((msurface_t **)r_surfacelist);
13984                 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13985         }
13986
13987         // if the model is static it doesn't matter what value we give for
13988         // wantnormals and wanttangents, so this logic uses only rules applicable
13989         // to a model, knowing that they are meaningless otherwise
13990         if (ent == r_refdef.scene.worldentity)
13991                 RSurf_ActiveWorldEntity();
13992         else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13993                 RSurf_ActiveModelEntity(ent, false, false, false);
13994         else if (prepass)
13995                 RSurf_ActiveModelEntity(ent, true, true, true);
13996         else if (depthonly)
13997         {
13998                 switch (vid.renderpath)
13999                 {
14000                 case RENDERPATH_GL20:
14001                 case RENDERPATH_D3D9:
14002                 case RENDERPATH_D3D10:
14003                 case RENDERPATH_D3D11:
14004                 case RENDERPATH_SOFT:
14005                 case RENDERPATH_GLES2:
14006                         RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
14007                         break;
14008                 case RENDERPATH_GL13:
14009                 case RENDERPATH_GL11:
14010                         RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
14011                         break;
14012                 }
14013         }
14014         else
14015         {
14016                 switch (vid.renderpath)
14017                 {
14018                 case RENDERPATH_GL20:
14019                 case RENDERPATH_D3D9:
14020                 case RENDERPATH_D3D10:
14021                 case RENDERPATH_D3D11:
14022                 case RENDERPATH_SOFT:
14023                 case RENDERPATH_GLES2:
14024                         RSurf_ActiveModelEntity(ent, true, true, false);
14025                         break;
14026                 case RENDERPATH_GL13:
14027                 case RENDERPATH_GL11:
14028                         RSurf_ActiveModelEntity(ent, true, false, false);
14029                         break;
14030                 }
14031         }
14032
14033         surfaces = model->data_surfaces;
14034         update = model->brushq1.lightmapupdateflags;
14035
14036         // update light styles
14037         if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
14038         {
14039                 model_brush_lightstyleinfo_t *style;
14040                 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
14041                 {
14042                         if (style->value != r_refdef.scene.lightstylevalue[style->style])
14043                         {
14044                                 int *list = style->surfacelist;
14045                                 style->value = r_refdef.scene.lightstylevalue[style->style];
14046                                 for (j = 0;j < style->numsurfaces;j++)
14047                                         update[list[j]] = true;
14048                         }
14049                 }
14050         }
14051
14052         flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
14053
14054         if (debug)
14055         {
14056                 R_DrawDebugModel();
14057                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14058                 return;
14059         }
14060
14061         rsurface.lightmaptexture = NULL;
14062         rsurface.deluxemaptexture = NULL;
14063         rsurface.uselightmaptexture = false;
14064         rsurface.texture = NULL;
14065         rsurface.rtlight = NULL;
14066         numsurfacelist = 0;
14067         // add visible surfaces to draw list
14068         for (i = 0;i < model->nummodelsurfaces;i++)
14069                 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
14070         // don't do anything if there were no surfaces
14071         if (!numsurfacelist)
14072         {
14073                 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14074                 return;
14075         }
14076         // update lightmaps if needed
14077         if (update)
14078         {
14079                 int updated = 0;
14080                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14081                 {
14082                         if (update[j])
14083                         {
14084                                 updated++;
14085                                 R_BuildLightMap(ent, surfaces + j);
14086                         }
14087                 }
14088         }
14089         if (update)
14090                 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14091                         if (update[j])
14092                                 R_BuildLightMap(ent, surfaces + j);
14093         R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
14094
14095         // add to stats if desired
14096         if (r_speeds.integer && !skysurfaces && !depthonly)
14097         {
14098                 r_refdef.stats.entities_surfaces += numsurfacelist;
14099                 for (j = 0;j < numsurfacelist;j++)
14100                         r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
14101         }
14102
14103         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14104 }
14105
14106 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14107 {
14108         static texture_t texture;
14109         static msurface_t surface;
14110         const msurface_t *surfacelist = &surface;
14111
14112         // fake enough texture and surface state to render this geometry
14113
14114         texture.update_lastrenderframe = -1; // regenerate this texture
14115         texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
14116         texture.currentskinframe = skinframe;
14117         texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
14118         texture.offsetmapping = OFFSETMAPPING_OFF;
14119         texture.offsetscale = 1;
14120         texture.specularscalemod = 1;
14121         texture.specularpowermod = 1;
14122
14123         surface.texture = &texture;
14124         surface.num_triangles = numtriangles;
14125         surface.num_firsttriangle = firsttriangle;
14126         surface.num_vertices = numvertices;
14127         surface.num_firstvertex = firstvertex;
14128
14129         // now render it
14130         rsurface.texture = R_GetCurrentTexture(surface.texture);
14131         rsurface.lightmaptexture = NULL;
14132         rsurface.deluxemaptexture = NULL;
14133         rsurface.uselightmaptexture = false;
14134         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14135 }
14136
14137 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)
14138 {
14139         static msurface_t surface;
14140         const msurface_t *surfacelist = &surface;
14141
14142         // fake enough texture and surface state to render this geometry
14143         surface.texture = texture;
14144         surface.num_triangles = numtriangles;
14145         surface.num_firsttriangle = firsttriangle;
14146         surface.num_vertices = numvertices;
14147         surface.num_firstvertex = firstvertex;
14148
14149         // now render it
14150         rsurface.texture = R_GetCurrentTexture(surface.texture);
14151         rsurface.lightmaptexture = NULL;
14152         rsurface.deluxemaptexture = NULL;
14153         rsurface.uselightmaptexture = false;
14154         R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14155 }