2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
23 #include "cl_dyntexture.h"
31 mempool_t *r_main_mempool;
32 rtexturepool_t *r_main_texturepool;
34 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
36 static qboolean r_loadnormalmap;
37 static qboolean r_loadgloss;
39 static qboolean r_loaddds;
40 static qboolean r_savedds;
47 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
48 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
49 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
50 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
51 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
52 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
53 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
54 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
56 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
57 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
58 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
59 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
60 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
62 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
63 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
64 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
65 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
66 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
67 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%, 10 = 100%)"};
68 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
69 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
70 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
71 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
72 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
73 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
74 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
75 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
76 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
77 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
78 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
79 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
80 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
81 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
82 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)"};
83 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)"};
84 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
85 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
86 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
87 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
88 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
89 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
90 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
91 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."};
92 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
93 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
94 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
95 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."};
96 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
97 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
98 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
99 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
100 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"};
101 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"};
102 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
103 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
104 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
105 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
106 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"};
108 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
109 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
110 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
111 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
112 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
113 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
114 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
115 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
117 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)"};
118 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"};
120 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
121 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
122 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
123 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
124 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
126 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
127 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
128 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
130 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)"};
131 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
132 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
133 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
134 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
135 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)"};
136 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)"};
137 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)"};
138 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)"};
140 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)"};
141 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
142 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"};
143 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
144 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
146 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
147 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
148 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
149 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
151 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
152 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
153 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
154 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
155 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
156 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
157 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
159 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
160 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
161 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
162 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
164 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"};
166 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"};
168 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
170 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
171 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"};
172 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
173 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
174 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
175 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
176 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "16", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
178 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
180 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "1", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
182 extern cvar_t v_glslgamma;
184 extern qboolean v_flipped_state;
186 static struct r_bloomstate_s
191 int bloomwidth, bloomheight;
193 int screentexturewidth, screentextureheight;
194 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
196 int bloomtexturewidth, bloomtextureheight;
197 rtexture_t *texture_bloom;
199 // arrays for rendering the screen passes
200 float screentexcoord2f[8];
201 float bloomtexcoord2f[8];
202 float offsettexcoord2f[8];
204 r_viewport_t viewport;
208 r_waterstate_t r_waterstate;
210 /// shadow volume bsp struct with automatically growing nodes buffer
213 rtexture_t *r_texture_blanknormalmap;
214 rtexture_t *r_texture_white;
215 rtexture_t *r_texture_grey128;
216 rtexture_t *r_texture_black;
217 rtexture_t *r_texture_notexture;
218 rtexture_t *r_texture_whitecube;
219 rtexture_t *r_texture_normalizationcube;
220 rtexture_t *r_texture_fogattenuation;
221 rtexture_t *r_texture_fogheighttexture;
222 rtexture_t *r_texture_gammaramps;
223 unsigned int r_texture_gammaramps_serial;
224 //rtexture_t *r_texture_fogintensity;
225 rtexture_t *r_texture_reflectcube;
227 // TODO: hash lookups?
228 typedef struct cubemapinfo_s
235 int r_texture_numcubemaps;
236 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
238 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
239 unsigned int r_numqueries;
240 unsigned int r_maxqueries;
242 typedef struct r_qwskincache_s
244 char name[MAX_QPATH];
245 skinframe_t *skinframe;
249 static r_qwskincache_t *r_qwskincache;
250 static int r_qwskincache_size;
252 /// vertex coordinates for a quad that covers the screen exactly
253 const float r_screenvertex3f[12] =
261 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
264 for (i = 0;i < verts;i++)
275 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
278 for (i = 0;i < verts;i++)
288 // FIXME: move this to client?
291 if (gamemode == GAME_NEHAHRA)
293 Cvar_Set("gl_fogenable", "0");
294 Cvar_Set("gl_fogdensity", "0.2");
295 Cvar_Set("gl_fogred", "0.3");
296 Cvar_Set("gl_foggreen", "0.3");
297 Cvar_Set("gl_fogblue", "0.3");
299 r_refdef.fog_density = 0;
300 r_refdef.fog_red = 0;
301 r_refdef.fog_green = 0;
302 r_refdef.fog_blue = 0;
303 r_refdef.fog_alpha = 1;
304 r_refdef.fog_start = 0;
305 r_refdef.fog_end = 16384;
306 r_refdef.fog_height = 1<<30;
307 r_refdef.fog_fadedepth = 128;
308 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
311 static void R_BuildBlankTextures(void)
313 unsigned char data[4];
314 data[2] = 128; // normal X
315 data[1] = 128; // normal Y
316 data[0] = 255; // normal Z
317 data[3] = 128; // height
318 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
323 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
328 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
333 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, NULL);
336 static void R_BuildNoTexture(void)
339 unsigned char pix[16][16][4];
340 // this makes a light grey/dark grey checkerboard texture
341 for (y = 0;y < 16;y++)
343 for (x = 0;x < 16;x++)
345 if ((y < 8) ^ (x < 8))
361 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, NULL);
364 static void R_BuildWhiteCube(void)
366 unsigned char data[6*1*1*4];
367 memset(data, 255, sizeof(data));
368 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, NULL);
371 static void R_BuildNormalizationCube(void)
375 vec_t s, t, intensity;
378 data = Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
379 for (side = 0;side < 6;side++)
381 for (y = 0;y < NORMSIZE;y++)
383 for (x = 0;x < NORMSIZE;x++)
385 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
386 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
421 intensity = 127.0f / sqrt(DotProduct(v, v));
422 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
423 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
424 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
425 data[((side*64+y)*64+x)*4+3] = 255;
429 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, NULL);
433 static void R_BuildFogTexture(void)
437 unsigned char data1[FOGWIDTH][4];
438 //unsigned char data2[FOGWIDTH][4];
441 r_refdef.fogmasktable_start = r_refdef.fog_start;
442 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
443 r_refdef.fogmasktable_range = r_refdef.fogrange;
444 r_refdef.fogmasktable_density = r_refdef.fog_density;
446 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
447 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
449 d = (x * r - r_refdef.fogmasktable_start);
450 if(developer_extra.integer)
451 Con_DPrintf("%f ", d);
453 if (r_fog_exp2.integer)
454 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
456 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
457 if(developer_extra.integer)
458 Con_DPrintf(" : %f ", alpha);
459 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
460 if(developer_extra.integer)
461 Con_DPrintf(" = %f\n", alpha);
462 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
465 for (x = 0;x < FOGWIDTH;x++)
467 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
472 //data2[x][0] = 255 - b;
473 //data2[x][1] = 255 - b;
474 //data2[x][2] = 255 - b;
477 if (r_texture_fogattenuation)
479 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
480 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
484 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, NULL);
485 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALLOWUPDATES, NULL);
489 static void R_BuildFogHeightTexture(void)
491 unsigned char *inpixels;
499 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
500 if (r_refdef.fogheighttexturename[0])
501 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false);
504 r_refdef.fog_height_tablesize = 0;
505 if (r_texture_fogheighttexture)
506 R_FreeTexture(r_texture_fogheighttexture);
507 r_texture_fogheighttexture = NULL;
508 if (r_refdef.fog_height_table2d)
509 Mem_Free(r_refdef.fog_height_table2d);
510 r_refdef.fog_height_table2d = NULL;
511 if (r_refdef.fog_height_table1d)
512 Mem_Free(r_refdef.fog_height_table1d);
513 r_refdef.fog_height_table1d = NULL;
517 r_refdef.fog_height_tablesize = size;
518 r_refdef.fog_height_table1d = Mem_Alloc(r_main_mempool, size * 4);
519 r_refdef.fog_height_table2d = Mem_Alloc(r_main_mempool, size * size * 4);
520 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
522 // LordHavoc: now the magic - what is that table2d for? it is a cooked
523 // average fog color table accounting for every fog layer between a point
524 // and the camera. (Note: attenuation is handled separately!)
525 for (y = 0;y < size;y++)
527 for (x = 0;x < size;x++)
533 for (j = x;j <= y;j++)
535 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
541 for (j = x;j >= y;j--)
543 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
548 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
549 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
550 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
551 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
554 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, NULL);
557 //=======================================================================================================================================================
559 static const char *builtinshaderstring =
560 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
561 "// written by Forest 'LordHavoc' Hale\n"
562 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
564 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
567 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
568 "#define USELIGHTMAP\n"
570 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
571 "#define USEEYEVECTOR\n"
574 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
575 "# extension GL_ARB_texture_rectangle : enable\n"
578 "#ifdef USESHADOWMAP2D\n"
579 "# ifdef GL_EXT_gpu_shader4\n"
580 "# extension GL_EXT_gpu_shader4 : enable\n"
582 "# ifdef GL_ARB_texture_gather\n"
583 "# extension GL_ARB_texture_gather : enable\n"
585 "# ifdef GL_AMD_texture_texture4\n"
586 "# extension GL_AMD_texture_texture4 : enable\n"
591 "#ifdef USESHADOWMAPCUBE\n"
592 "# extension GL_EXT_gpu_shader4 : enable\n"
595 "//#ifdef USESHADOWSAMPLER\n"
596 "//# extension GL_ARB_shadow : enable\n"
599 "//#ifdef __GLSL_CG_DATA_TYPES\n"
600 "//# define myhalf half\n"
601 "//# define myhalf2 half2\n"
602 "//# define myhalf3 half3\n"
603 "//# define myhalf4 half4\n"
605 "# define myhalf float\n"
606 "# define myhalf2 vec2\n"
607 "# define myhalf3 vec3\n"
608 "# define myhalf4 vec4\n"
611 "#ifdef VERTEX_SHADER\n"
612 "uniform mat4 ModelViewProjectionMatrix;\n"
615 "#ifdef MODE_DEPTH_OR_SHADOW\n"
616 "#ifdef VERTEX_SHADER\n"
619 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
622 "#else // !MODE_DEPTH_ORSHADOW\n"
627 "#ifdef MODE_SHOWDEPTH\n"
628 "#ifdef VERTEX_SHADER\n"
631 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
632 " gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
636 "#ifdef FRAGMENT_SHADER\n"
639 " gl_FragColor = gl_Color;\n"
642 "#else // !MODE_SHOWDEPTH\n"
647 "#ifdef MODE_POSTPROCESS\n"
648 "varying vec2 TexCoord1;\n"
649 "varying vec2 TexCoord2;\n"
651 "#ifdef VERTEX_SHADER\n"
654 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
655 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
657 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
662 "#ifdef FRAGMENT_SHADER\n"
663 "uniform sampler2D Texture_First;\n"
665 "uniform sampler2D Texture_Second;\n"
667 "#ifdef USEGAMMARAMPS\n"
668 "uniform sampler2D Texture_GammaRamps;\n"
670 "#ifdef USESATURATION\n"
671 "uniform float Saturation;\n"
673 "#ifdef USEVIEWTINT\n"
674 "uniform vec4 ViewTintColor;\n"
676 "//uncomment these if you want to use them:\n"
677 "uniform vec4 UserVec1;\n"
678 "// uniform vec4 UserVec2;\n"
679 "// uniform vec4 UserVec3;\n"
680 "// uniform vec4 UserVec4;\n"
681 "// uniform float ClientTime;\n"
682 "uniform vec2 PixelSize;\n"
685 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
687 " gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
689 "#ifdef USEVIEWTINT\n"
690 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
693 "#ifdef USEPOSTPROCESSING\n"
694 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
695 "// 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"
696 " if (UserVec1.x > 100.0) {\n"
697 " // vec2 ts = textureSize(Texture_First, 0);\n"
698 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
699 " vec2 px = PixelSize;\n"
700 " vec4 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y));\n"
701 " vec4 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0));\n"
702 " vec4 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y));\n"
703 " vec4 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y));\n"
704 " vec4 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0));\n"
705 " vec4 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y));\n"
706 " vec4 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y));\n"
707 " vec4 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y));\n"
708 " vec4 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y));\n"
709 " vec4 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y));\n"
710 " vec4 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y));\n"
711 " vec4 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y));\n"
713 " float px1 = -1.0 * (0.30*x1.r + 0.59*x1.g + 0.11*x1.b);\n"
714 " float px2 = -2.0 * (0.30*x2.r + 0.59*x2.g + 0.11*x2.b);\n"
715 " float px3 = -1.0 * (0.30*x3.r + 0.59*x3.g + 0.11*x3.b);\n"
716 " float px4 = 1.0 * (0.30*x4.r + 0.59*x4.g + 0.11*x4.b);\n"
717 " float px5 = 2.0 * (0.30*x5.r + 0.59*x5.g + 0.11*x5.b);\n"
718 " float px6 = 1.0 * (0.30*x6.r + 0.59*x6.g + 0.11*x6.b);\n"
719 " float py1 = -1.0 * (0.30*y1.r + 0.59*y1.g + 0.11*y1.b);\n"
720 " float py2 = -2.0 * (0.30*y2.r + 0.59*y2.g + 0.11*y2.b);\n"
721 " float py3 = -1.0 * (0.30*y3.r + 0.59*y3.g + 0.11*y3.b);\n"
722 " float py4 = 1.0 * (0.30*y4.r + 0.59*y4.g + 0.11*y4.b);\n"
723 " float py5 = 2.0 * (0.30*y5.r + 0.59*y5.g + 0.11*y5.b);\n"
724 " float py6 = 1.0 * (0.30*y6.r + 0.59*y6.g + 0.11*y6.b);\n"
725 " gl_FragColor = 0.25 * vec4(vec3(abs(px1 + px2 + px3 + px4 + px5 + px6)), 1) + 0.25 * vec4(vec3(abs(py1 + py2 + py3 + py4 + py5 + py6)), 1);\n"
727 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
728 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
729 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
730 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
731 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
732 " gl_FragColor /= (1 + 5 * UserVec1.y);\n"
736 "#ifdef USESATURATION\n"
737 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
738 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
739 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
740 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
743 "#ifdef USEGAMMARAMPS\n"
744 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
745 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
746 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
750 "#else // !MODE_POSTPROCESS\n"
755 "#ifdef MODE_GENERIC\n"
756 "#ifdef USEDIFFUSE\n"
757 "varying vec2 TexCoord1;\n"
759 "#ifdef USESPECULAR\n"
760 "varying vec2 TexCoord2;\n"
762 "#ifdef VERTEX_SHADER\n"
765 " gl_FrontColor = gl_Color;\n"
766 "#ifdef USEDIFFUSE\n"
767 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
769 "#ifdef USESPECULAR\n"
770 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
772 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
776 "#ifdef FRAGMENT_SHADER\n"
777 "#ifdef USEDIFFUSE\n"
778 "uniform sampler2D Texture_First;\n"
780 "#ifdef USESPECULAR\n"
781 "uniform sampler2D Texture_Second;\n"
786 " gl_FragColor = gl_Color;\n"
787 "#ifdef USEDIFFUSE\n"
788 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
791 "#ifdef USESPECULAR\n"
792 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
793 "# ifdef USECOLORMAPPING\n"
794 " gl_FragColor *= tex2;\n"
797 " gl_FragColor += tex2;\n"
799 "# ifdef USEVERTEXTEXTUREBLEND\n"
800 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
805 "#else // !MODE_GENERIC\n"
810 "#ifdef MODE_BLOOMBLUR\n"
811 "varying TexCoord;\n"
812 "#ifdef VERTEX_SHADER\n"
815 " gl_FrontColor = gl_Color;\n"
816 " TexCoord = gl_MultiTexCoord0.xy;\n"
817 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
821 "#ifdef FRAGMENT_SHADER\n"
822 "uniform sampler2D Texture_First;\n"
823 "uniform vec4 BloomBlur_Parameters;\n"
828 " vec2 tc = TexCoord;\n"
829 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
830 " tc += BloomBlur_Parameters.xy;\n"
831 " for (i = 1;i < SAMPLES;i++)\n"
833 " color += texture2D(Texture_First, tc).rgb;\n"
834 " tc += BloomBlur_Parameters.xy;\n"
836 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
839 "#else // !MODE_BLOOMBLUR\n"
840 "#ifdef MODE_REFRACTION\n"
841 "varying vec2 TexCoord;\n"
842 "varying vec4 ModelViewProjectionPosition;\n"
843 "uniform mat4 TexMatrix;\n"
844 "#ifdef VERTEX_SHADER\n"
848 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
849 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
850 " ModelViewProjectionPosition = gl_Position;\n"
854 "#ifdef FRAGMENT_SHADER\n"
855 "uniform sampler2D Texture_Normal;\n"
856 "uniform sampler2D Texture_Refraction;\n"
857 "uniform sampler2D Texture_Reflection;\n"
859 "uniform vec4 DistortScaleRefractReflect;\n"
860 "uniform vec4 ScreenScaleRefractReflect;\n"
861 "uniform vec4 ScreenCenterRefractReflect;\n"
862 "uniform vec4 RefractColor;\n"
863 "uniform vec4 ReflectColor;\n"
864 "uniform float ReflectFactor;\n"
865 "uniform float ReflectOffset;\n"
869 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
870 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
871 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
872 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
873 " // FIXME temporary hack to detect the case that the reflection\n"
874 " // gets blackened at edges due to leaving the area that contains actual\n"
876 " // Remove this 'ack once we have a better way to stop this thing from\n"
878 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
879 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
880 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
881 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
882 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
883 " gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
886 "#else // !MODE_REFRACTION\n"
891 "#ifdef MODE_WATER\n"
892 "varying vec2 TexCoord;\n"
893 "varying vec3 EyeVector;\n"
894 "varying vec4 ModelViewProjectionPosition;\n"
895 "#ifdef VERTEX_SHADER\n"
896 "uniform vec3 EyePosition;\n"
897 "uniform mat4 TexMatrix;\n"
901 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
902 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
903 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
904 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
905 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
906 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
907 " ModelViewProjectionPosition = gl_Position;\n"
911 "#ifdef FRAGMENT_SHADER\n"
912 "uniform sampler2D Texture_Normal;\n"
913 "uniform sampler2D Texture_Refraction;\n"
914 "uniform sampler2D Texture_Reflection;\n"
916 "uniform vec4 DistortScaleRefractReflect;\n"
917 "uniform vec4 ScreenScaleRefractReflect;\n"
918 "uniform vec4 ScreenCenterRefractReflect;\n"
919 "uniform vec4 RefractColor;\n"
920 "uniform vec4 ReflectColor;\n"
921 "uniform float ReflectFactor;\n"
922 "uniform float ReflectOffset;\n"
926 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
927 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
928 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
929 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
930 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
931 " // FIXME temporary hack to detect the case that the reflection\n"
932 " // gets blackened at edges due to leaving the area that contains actual\n"
934 " // Remove this 'ack once we have a better way to stop this thing from\n"
936 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
937 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
938 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
939 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
940 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
941 " f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
942 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
943 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
944 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
945 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
946 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
947 " gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
950 "#else // !MODE_WATER\n"
955 "// common definitions between vertex shader and fragment shader:\n"
957 "varying vec2 TexCoord;\n"
958 "#ifdef USEVERTEXTEXTUREBLEND\n"
959 "varying vec2 TexCoord2;\n"
961 "#ifdef USELIGHTMAP\n"
962 "varying vec2 TexCoordLightmap;\n"
965 "#ifdef MODE_LIGHTSOURCE\n"
966 "varying vec3 CubeVector;\n"
969 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
970 "varying vec3 LightVector;\n"
973 "#ifdef USEEYEVECTOR\n"
974 "varying vec3 EyeVector;\n"
977 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
980 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
981 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
982 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
983 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
986 "#ifdef USEREFLECTION\n"
987 "varying vec4 ModelViewProjectionPosition;\n"
989 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
990 "uniform vec3 LightPosition;\n"
991 "varying vec4 ModelViewPosition;\n"
994 "#ifdef MODE_LIGHTSOURCE\n"
995 "uniform vec3 LightPosition;\n"
997 "uniform vec3 EyePosition;\n"
998 "#ifdef MODE_LIGHTDIRECTION\n"
999 "uniform vec3 LightDir;\n"
1001 "uniform vec4 FogPlane;\n"
1003 "#ifdef USESHADOWMAPORTHO\n"
1004 "varying vec3 ShadowMapTC;\n"
1011 "// 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"
1013 "// fragment shader specific:\n"
1014 "#ifdef FRAGMENT_SHADER\n"
1016 "uniform sampler2D Texture_Normal;\n"
1017 "uniform sampler2D Texture_Color;\n"
1018 "uniform sampler2D Texture_Gloss;\n"
1020 "uniform sampler2D Texture_Glow;\n"
1022 "#ifdef USEVERTEXTEXTUREBLEND\n"
1023 "uniform sampler2D Texture_SecondaryNormal;\n"
1024 "uniform sampler2D Texture_SecondaryColor;\n"
1025 "uniform sampler2D Texture_SecondaryGloss;\n"
1027 "uniform sampler2D Texture_SecondaryGlow;\n"
1030 "#ifdef USECOLORMAPPING\n"
1031 "uniform sampler2D Texture_Pants;\n"
1032 "uniform sampler2D Texture_Shirt;\n"
1035 "#ifdef USEFOGHEIGHTTEXTURE\n"
1036 "uniform sampler2D Texture_FogHeightTexture;\n"
1038 "uniform sampler2D Texture_FogMask;\n"
1040 "#ifdef USELIGHTMAP\n"
1041 "uniform sampler2D Texture_Lightmap;\n"
1043 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1044 "uniform sampler2D Texture_Deluxemap;\n"
1046 "#ifdef USEREFLECTION\n"
1047 "uniform sampler2D Texture_Reflection;\n"
1050 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1051 "uniform sampler2D Texture_ScreenDepth;\n"
1052 "uniform sampler2D Texture_ScreenNormalMap;\n"
1054 "#ifdef USEDEFERREDLIGHTMAP\n"
1055 "uniform sampler2D Texture_ScreenDiffuse;\n"
1056 "uniform sampler2D Texture_ScreenSpecular;\n"
1059 "uniform myhalf3 Color_Pants;\n"
1060 "uniform myhalf3 Color_Shirt;\n"
1061 "uniform myhalf3 FogColor;\n"
1064 "uniform float FogRangeRecip;\n"
1065 "uniform float FogPlaneViewDist;\n"
1066 "uniform float FogHeightFade;\n"
1067 "vec3 FogVertex(vec3 surfacecolor)\n"
1069 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1070 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1072 "#ifdef USEFOGHEIGHTTEXTURE\n"
1073 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1074 " fogfrac = fogheightpixel.a;\n"
1075 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1077 "# ifdef USEFOGOUTSIDE\n"
1078 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1080 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1082 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1087 "#ifdef USEOFFSETMAPPING\n"
1088 "uniform float OffsetMapping_Scale;\n"
1089 "vec2 OffsetMapping(vec2 TexCoord)\n"
1091 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1092 " // 14 sample relief mapping: linear search and then binary search\n"
1093 " // this basically steps forward a small amount repeatedly until it finds\n"
1094 " // itself inside solid, then jitters forward and back using decreasing\n"
1095 " // amounts to find the impact\n"
1096 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1097 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1098 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1099 " vec3 RT = vec3(TexCoord, 1);\n"
1100 " OffsetVector *= 0.1;\n"
1101 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1102 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1103 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1104 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1105 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1106 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1107 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1108 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1109 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1110 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1111 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1112 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1113 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1114 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1117 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1118 " // this basically moves forward the full distance, and then backs up based\n"
1119 " // on height of samples\n"
1120 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1121 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1122 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1123 " TexCoord += OffsetVector;\n"
1124 " OffsetVector *= 0.333;\n"
1125 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1126 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1127 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1128 " return TexCoord;\n"
1131 "#endif // USEOFFSETMAPPING\n"
1133 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1134 "uniform sampler2D Texture_Attenuation;\n"
1135 "uniform samplerCube Texture_Cube;\n"
1138 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1140 "#ifdef USESHADOWMAPRECT\n"
1141 "# ifdef USESHADOWSAMPLER\n"
1142 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1144 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1148 "#ifdef USESHADOWMAP2D\n"
1149 "# ifdef USESHADOWSAMPLER\n"
1150 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1152 "uniform sampler2D Texture_ShadowMap2D;\n"
1156 "#ifdef USESHADOWMAPVSDCT\n"
1157 "uniform samplerCube Texture_CubeProjection;\n"
1160 "#ifdef USESHADOWMAPCUBE\n"
1161 "# ifdef USESHADOWSAMPLER\n"
1162 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1164 "uniform samplerCube Texture_ShadowMapCube;\n"
1168 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1169 "uniform vec2 ShadowMap_TextureScale;\n"
1170 "uniform vec4 ShadowMap_Parameters;\n"
1173 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1174 "# ifdef USESHADOWMAPORTHO\n"
1175 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1177 "# ifdef USESHADOWMAPVSDCT\n"
1178 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1180 " vec3 adir = abs(dir);\n"
1181 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1182 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1183 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1186 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1188 " vec3 adir = abs(dir);\n"
1189 " float ma = adir.z;\n"
1190 " vec4 proj = vec4(dir, 2.5);\n"
1191 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1192 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1193 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1194 " 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"
1198 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1200 "#ifdef USESHADOWMAPCUBE\n"
1201 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1203 " vec3 adir = abs(dir);\n"
1204 " return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1208 "# ifdef USESHADOWMAPRECT\n"
1209 "float ShadowMapCompare(vec3 dir)\n"
1211 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1213 "# ifdef USESHADOWSAMPLER\n"
1215 "# ifdef USESHADOWMAPPCF\n"
1216 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1217 " 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"
1219 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1224 "# ifdef USESHADOWMAPPCF\n"
1225 "# if USESHADOWMAPPCF > 1\n"
1226 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1227 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1228 " 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"
1229 " 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"
1230 " 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"
1231 " 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"
1232 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1233 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1235 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1236 " vec2 offset = fract(shadowmaptc.xy);\n"
1237 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1238 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1239 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1240 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1241 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1244 " f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1248 "# ifdef USESHADOWMAPORTHO\n"
1249 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1256 "# ifdef USESHADOWMAP2D\n"
1257 "float ShadowMapCompare(vec3 dir)\n"
1259 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1262 "# ifdef USESHADOWSAMPLER\n"
1263 "# ifdef USESHADOWMAPPCF\n"
1264 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1265 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1266 " 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"
1268 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1271 "# ifdef USESHADOWMAPPCF\n"
1272 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1273 "# ifdef GL_ARB_texture_gather\n"
1274 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1276 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1278 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1279 "# if USESHADOWMAPPCF > 1\n"
1280 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1281 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1282 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1283 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1284 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1285 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1286 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1287 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1288 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1289 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1290 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1291 " locols.yz += group2.ab;\n"
1292 " hicols.yz += group8.rg;\n"
1293 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1294 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1295 " mix(locols, hicols, offset.y);\n"
1296 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1297 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1298 " f = dot(cols, vec4(1.0/25.0));\n"
1300 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1301 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1302 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1303 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1304 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1305 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1306 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1309 "# ifdef GL_EXT_gpu_shader4\n"
1310 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1312 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1314 "# if USESHADOWMAPPCF > 1\n"
1315 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1316 " center *= ShadowMap_TextureScale;\n"
1317 " 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"
1318 " 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"
1319 " 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"
1320 " 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"
1321 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1322 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1324 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1325 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1326 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1327 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1328 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1329 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1333 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1336 "# ifdef USESHADOWMAPORTHO\n"
1337 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1344 "# ifdef USESHADOWMAPCUBE\n"
1345 "float ShadowMapCompare(vec3 dir)\n"
1347 " // apply depth texture cubemap as light filter\n"
1348 " vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1350 "# ifdef USESHADOWSAMPLER\n"
1351 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1353 " f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1358 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1359 "#endif // FRAGMENT_SHADER\n"
1364 "#ifdef MODE_DEFERREDGEOMETRY\n"
1365 "#ifdef VERTEX_SHADER\n"
1366 "uniform mat4 TexMatrix;\n"
1367 "#ifdef USEVERTEXTEXTUREBLEND\n"
1368 "uniform mat4 BackgroundTexMatrix;\n"
1370 "uniform mat4 ModelViewMatrix;\n"
1373 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1374 "#ifdef USEVERTEXTEXTUREBLEND\n"
1375 " gl_FrontColor = gl_Color;\n"
1376 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1379 " // transform unnormalized eye direction into tangent space\n"
1380 "#ifdef USEOFFSETMAPPING\n"
1381 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1382 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1383 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1384 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1387 " VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1388 " VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1389 " VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1390 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1392 "#endif // VERTEX_SHADER\n"
1394 "#ifdef FRAGMENT_SHADER\n"
1397 "#ifdef USEOFFSETMAPPING\n"
1398 " // apply offsetmapping\n"
1399 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1400 "#define TexCoord TexCoordOffset\n"
1403 "#ifdef USEALPHAKILL\n"
1404 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1408 "#ifdef USEVERTEXTEXTUREBLEND\n"
1409 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1410 " float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1411 " //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1412 " //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1415 "#ifdef USEVERTEXTEXTUREBLEND\n"
1416 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1417 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1419 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1420 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1423 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1425 "#endif // FRAGMENT_SHADER\n"
1426 "#else // !MODE_DEFERREDGEOMETRY\n"
1431 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1432 "#ifdef VERTEX_SHADER\n"
1433 "uniform mat4 ModelViewMatrix;\n"
1436 " ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1437 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1439 "#endif // VERTEX_SHADER\n"
1441 "#ifdef FRAGMENT_SHADER\n"
1442 "uniform mat4 ViewToLight;\n"
1443 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1444 "uniform vec2 ScreenToDepth;\n"
1445 "uniform myhalf3 DeferredColor_Ambient;\n"
1446 "uniform myhalf3 DeferredColor_Diffuse;\n"
1447 "#ifdef USESPECULAR\n"
1448 "uniform myhalf3 DeferredColor_Specular;\n"
1449 "uniform myhalf SpecularPower;\n"
1451 "uniform myhalf2 PixelToScreenTexCoord;\n"
1454 " // calculate viewspace pixel position\n"
1455 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1457 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1458 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1459 " // decode viewspace pixel normal\n"
1460 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1461 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1462 " // surfacenormal = pixel normal in viewspace\n"
1463 " // LightVector = pixel to light in viewspace\n"
1464 " // CubeVector = position in lightspace\n"
1465 " // eyevector = pixel to view in viewspace\n"
1466 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1467 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1468 "#ifdef USEDIFFUSE\n"
1469 " // calculate diffuse shading\n"
1470 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1471 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1473 "#ifdef USESPECULAR\n"
1474 " // calculate directional shading\n"
1475 " vec3 eyevector = position * -1.0;\n"
1476 "# ifdef USEEXACTSPECULARMATH\n"
1477 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1479 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1480 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1484 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1485 " fade *= ShadowMapCompare(CubeVector);\n"
1488 "#ifdef USEDIFFUSE\n"
1489 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1491 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1493 "#ifdef USESPECULAR\n"
1494 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1496 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1499 "# ifdef USECUBEFILTER\n"
1500 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1501 " gl_FragData[0].rgb *= cubecolor;\n"
1502 " gl_FragData[1].rgb *= cubecolor;\n"
1505 "#endif // FRAGMENT_SHADER\n"
1506 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1511 "#ifdef VERTEX_SHADER\n"
1512 "uniform mat4 TexMatrix;\n"
1513 "#ifdef USEVERTEXTEXTUREBLEND\n"
1514 "uniform mat4 BackgroundTexMatrix;\n"
1516 "#ifdef MODE_LIGHTSOURCE\n"
1517 "uniform mat4 ModelToLight;\n"
1519 "#ifdef USESHADOWMAPORTHO\n"
1520 "uniform mat4 ShadowMapMatrix;\n"
1524 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1525 " gl_FrontColor = gl_Color;\n"
1527 " // copy the surface texcoord\n"
1528 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1529 "#ifdef USEVERTEXTEXTUREBLEND\n"
1530 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1532 "#ifdef USELIGHTMAP\n"
1533 " TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1536 "#ifdef MODE_LIGHTSOURCE\n"
1537 " // transform vertex position into light attenuation/cubemap space\n"
1538 " // (-1 to +1 across the light box)\n"
1539 " CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1541 "# ifdef USEDIFFUSE\n"
1542 " // transform unnormalized light direction into tangent space\n"
1543 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1544 " // normalize it per pixel)\n"
1545 " vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1546 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1547 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1548 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1552 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1553 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1554 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1555 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1558 " // transform unnormalized eye direction into tangent space\n"
1559 "#ifdef USEEYEVECTOR\n"
1560 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1561 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1562 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1563 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1567 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1568 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1571 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1572 " VectorS = gl_MultiTexCoord1.xyz;\n"
1573 " VectorT = gl_MultiTexCoord2.xyz;\n"
1574 " VectorR = gl_MultiTexCoord3.xyz;\n"
1577 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1578 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1580 "#ifdef USESHADOWMAPORTHO\n"
1581 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1584 "#ifdef USEREFLECTION\n"
1585 " ModelViewProjectionPosition = gl_Position;\n"
1588 "#endif // VERTEX_SHADER\n"
1593 "#ifdef FRAGMENT_SHADER\n"
1594 "#ifdef USEDEFERREDLIGHTMAP\n"
1595 "uniform myhalf2 PixelToScreenTexCoord;\n"
1596 "uniform myhalf3 DeferredMod_Diffuse;\n"
1597 "uniform myhalf3 DeferredMod_Specular;\n"
1599 "uniform myhalf3 Color_Ambient;\n"
1600 "uniform myhalf3 Color_Diffuse;\n"
1601 "uniform myhalf3 Color_Specular;\n"
1602 "uniform myhalf SpecularPower;\n"
1604 "uniform myhalf3 Color_Glow;\n"
1606 "uniform myhalf Alpha;\n"
1607 "#ifdef USEREFLECTION\n"
1608 "uniform vec4 DistortScaleRefractReflect;\n"
1609 "uniform vec4 ScreenScaleRefractReflect;\n"
1610 "uniform vec4 ScreenCenterRefractReflect;\n"
1611 "uniform myhalf4 ReflectColor;\n"
1613 "#ifdef USEREFLECTCUBE\n"
1614 "uniform mat4 ModelToReflectCube;\n"
1615 "uniform sampler2D Texture_ReflectMask;\n"
1616 "uniform samplerCube Texture_ReflectCube;\n"
1618 "#ifdef MODE_LIGHTDIRECTION\n"
1619 "uniform myhalf3 LightColor;\n"
1621 "#ifdef MODE_LIGHTSOURCE\n"
1622 "uniform myhalf3 LightColor;\n"
1626 "#ifdef USEOFFSETMAPPING\n"
1627 " // apply offsetmapping\n"
1628 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1629 "#define TexCoord TexCoordOffset\n"
1632 " // combine the diffuse textures (base, pants, shirt)\n"
1633 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1634 "#ifdef USEALPHAKILL\n"
1635 " if (color.a < 0.5)\n"
1638 " color.a *= Alpha;\n"
1639 "#ifdef USECOLORMAPPING\n"
1640 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1642 "#ifdef USEVERTEXTEXTUREBLEND\n"
1643 " myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1644 " //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1645 " //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1646 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1648 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1651 " // get the surface normal\n"
1652 "#ifdef USEVERTEXTEXTUREBLEND\n"
1653 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1655 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1658 " // get the material colors\n"
1659 " myhalf3 diffusetex = color.rgb;\n"
1660 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1661 "# ifdef USEVERTEXTEXTUREBLEND\n"
1662 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1664 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1668 "#ifdef USEREFLECTCUBE\n"
1669 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1670 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1671 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1672 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1678 "#ifdef MODE_LIGHTSOURCE\n"
1679 " // light source\n"
1680 "#ifdef USEDIFFUSE\n"
1681 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1682 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1683 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1684 "#ifdef USESPECULAR\n"
1685 "#ifdef USEEXACTSPECULARMATH\n"
1686 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1688 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1689 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1691 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1694 " color.rgb = diffusetex * Color_Ambient;\n"
1696 " color.rgb *= LightColor;\n"
1697 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1698 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1699 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1701 "# ifdef USECUBEFILTER\n"
1702 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1704 "#endif // MODE_LIGHTSOURCE\n"
1709 "#ifdef MODE_LIGHTDIRECTION\n"
1711 "#ifdef USEDIFFUSE\n"
1712 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1714 "#define lightcolor LightColor\n"
1715 "#endif // MODE_LIGHTDIRECTION\n"
1716 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1718 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1719 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1720 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1721 " // convert modelspace light vector to tangentspace\n"
1722 " myhalf3 lightnormal;\n"
1723 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1724 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1725 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1726 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1727 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1728 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1729 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1730 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1731 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1732 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1733 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1734 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1735 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1736 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1737 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1739 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1740 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1741 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1747 "#ifdef MODE_LIGHTMAP\n"
1748 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1749 "#endif // MODE_LIGHTMAP\n"
1750 "#ifdef MODE_VERTEXCOLOR\n"
1751 " color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1752 "#endif // MODE_VERTEXCOLOR\n"
1753 "#ifdef MODE_FLATCOLOR\n"
1754 " color.rgb = diffusetex * Color_Ambient;\n"
1755 "#endif // MODE_FLATCOLOR\n"
1761 "# ifdef USEDIFFUSE\n"
1762 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1763 "# ifdef USESPECULAR\n"
1764 "# ifdef USEEXACTSPECULARMATH\n"
1765 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1767 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1768 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1770 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1772 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1775 " color.rgb = diffusetex * Color_Ambient;\n"
1779 "#ifdef USESHADOWMAPORTHO\n"
1780 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1783 "#ifdef USEDEFERREDLIGHTMAP\n"
1784 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1785 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1786 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1790 "#ifdef USEVERTEXTEXTUREBLEND\n"
1791 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1793 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1798 " color.rgb = FogVertex(color.rgb);\n"
1801 " // 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"
1802 "#ifdef USEREFLECTION\n"
1803 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1804 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1805 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1806 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1807 " // FIXME temporary hack to detect the case that the reflection\n"
1808 " // gets blackened at edges due to leaving the area that contains actual\n"
1810 " // Remove this 'ack once we have a better way to stop this thing from\n"
1812 " float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1813 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1814 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1815 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1816 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1817 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1820 " gl_FragColor = vec4(color);\n"
1822 "#endif // FRAGMENT_SHADER\n"
1824 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1825 "#endif // !MODE_DEFERREDGEOMETRY\n"
1826 "#endif // !MODE_WATER\n"
1827 "#endif // !MODE_REFRACTION\n"
1828 "#endif // !MODE_BLOOMBLUR\n"
1829 "#endif // !MODE_GENERIC\n"
1830 "#endif // !MODE_POSTPROCESS\n"
1831 "#endif // !MODE_SHOWDEPTH\n"
1832 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1836 =========================================================================================================================================================
1840 =========================================================================================================================================================
1844 =========================================================================================================================================================
1848 =========================================================================================================================================================
1852 =========================================================================================================================================================
1856 =========================================================================================================================================================
1860 =========================================================================================================================================================
1863 const char *builtincgshaderstring =
1864 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1865 "// written by Forest 'LordHavoc' Hale\n"
1866 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1868 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1869 "#if defined(USEREFLECTION)\n"
1870 "#undef USESHADOWMAPORTHO\n"
1873 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1876 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1877 "#define USELIGHTMAP\n"
1879 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1880 "#define USEEYEVECTOR\n"
1883 "#ifdef FRAGMENT_SHADER\n"
1884 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1887 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1888 "#ifdef VERTEX_SHADER\n"
1891 "float4 gl_Vertex : POSITION,\n"
1892 "uniform float4x4 ModelViewProjectionMatrix,\n"
1893 "out float4 gl_Position : POSITION\n"
1896 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1899 "#else // !MODE_DEPTH_ORSHADOW\n"
1904 "#ifdef MODE_SHOWDEPTH\n"
1905 "#ifdef VERTEX_SHADER\n"
1908 "float4 gl_Vertex : POSITION,\n"
1909 "uniform float4x4 ModelViewProjectionMatrix,\n"
1910 "out float4 gl_Position : POSITION,\n"
1911 "out float4 gl_FrontColor : COLOR0\n"
1914 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1915 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1919 "#ifdef FRAGMENT_SHADER\n"
1922 "float4 gl_FrontColor : COLOR0,\n"
1923 "out float4 gl_FragColor : COLOR\n"
1926 " gl_FragColor = gl_FrontColor;\n"
1929 "#else // !MODE_SHOWDEPTH\n"
1934 "#ifdef MODE_POSTPROCESS\n"
1936 "#ifdef VERTEX_SHADER\n"
1939 "float4 gl_Vertex : POSITION,\n"
1940 "uniform float4x4 ModelViewProjectionMatrix,\n"
1941 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1942 "float4 gl_MultiTexCoord1 : TEXCOORD4,\n"
1943 "out float4 gl_Position : POSITION,\n"
1944 "out float2 TexCoord1 : TEXCOORD0,\n"
1945 "out float2 TexCoord2 : TEXCOORD1\n"
1948 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1949 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
1951 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
1956 "#ifdef FRAGMENT_SHADER\n"
1959 "float2 TexCoord1 : TEXCOORD0,\n"
1960 "float2 TexCoord2 : TEXCOORD1,\n"
1961 "uniform sampler2D Texture_First,\n"
1963 "uniform sampler2D Texture_Second,\n"
1965 "#ifdef USEGAMMARAMPS\n"
1966 "uniform sampler2D Texture_GammaRamps,\n"
1968 "#ifdef USESATURATION\n"
1969 "uniform float Saturation,\n"
1971 "#ifdef USEVIEWTINT\n"
1972 "uniform float4 ViewTintColor,\n"
1974 "uniform float4 UserVec1,\n"
1975 "uniform float4 UserVec2,\n"
1976 "uniform float4 UserVec3,\n"
1977 "uniform float4 UserVec4,\n"
1978 "uniform float ClientTime,\n"
1979 "uniform float2 PixelSize,\n"
1980 "out float4 gl_FragColor : COLOR\n"
1983 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1985 " gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
1987 "#ifdef USEVIEWTINT\n"
1988 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
1991 "#ifdef USEPOSTPROCESSING\n"
1992 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
1993 "// 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"
1994 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
1995 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
1996 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
1997 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
1998 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
1999 " gl_FragColor /= (1 + 5 * UserVec1.y);\n"
2002 "#ifdef USESATURATION\n"
2003 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2004 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2005 " //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2006 " gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2009 "#ifdef USEGAMMARAMPS\n"
2010 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2011 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2012 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2016 "#else // !MODE_POSTPROCESS\n"
2021 "#ifdef MODE_GENERIC\n"
2022 "#ifdef VERTEX_SHADER\n"
2025 "float4 gl_Vertex : POSITION,\n"
2026 "uniform float4x4 ModelViewProjectionMatrix,\n"
2027 "float4 gl_Color : COLOR0,\n"
2028 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2029 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2030 "out float4 gl_Position : POSITION,\n"
2031 "out float4 gl_FrontColor : COLOR,\n"
2032 "out float2 TexCoord1 : TEXCOORD0,\n"
2033 "out float2 TexCoord2 : TEXCOORD1\n"
2036 " gl_FrontColor = gl_Color;\n"
2037 "#ifdef USEDIFFUSE\n"
2038 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2040 "#ifdef USESPECULAR\n"
2041 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2043 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2047 "#ifdef FRAGMENT_SHADER\n"
2051 "float4 gl_FrontColor : COLOR,\n"
2052 "float2 TexCoord1 : TEXCOORD0,\n"
2053 "float2 TexCoord2 : TEXCOORD1,\n"
2054 "#ifdef USEDIFFUSE\n"
2055 "uniform sampler2D Texture_First,\n"
2057 "#ifdef USESPECULAR\n"
2058 "uniform sampler2D Texture_Second,\n"
2060 "out float4 gl_FragColor : COLOR\n"
2063 " gl_FragColor = gl_FrontColor;\n"
2064 "#ifdef USEDIFFUSE\n"
2065 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2068 "#ifdef USESPECULAR\n"
2069 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2070 "# ifdef USECOLORMAPPING\n"
2071 " gl_FragColor *= tex2;\n"
2074 " gl_FragColor += tex2;\n"
2076 "# ifdef USEVERTEXTEXTUREBLEND\n"
2077 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2082 "#else // !MODE_GENERIC\n"
2087 "#ifdef MODE_BLOOMBLUR\n"
2088 "#ifdef VERTEX_SHADER\n"
2091 "float4 gl_Vertex : POSITION,\n"
2092 "uniform float4x4 ModelViewProjectionMatrix,\n"
2093 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2094 "out float4 gl_Position : POSITION,\n"
2095 "out float2 TexCoord : TEXCOORD0\n"
2098 " TexCoord = gl_MultiTexCoord0.xy;\n"
2099 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2103 "#ifdef FRAGMENT_SHADER\n"
2107 "float2 TexCoord : TEXCOORD0,\n"
2108 "uniform sampler2D Texture_First,\n"
2109 "uniform float4 BloomBlur_Parameters,\n"
2110 "out float4 gl_FragColor : COLOR\n"
2114 " float2 tc = TexCoord;\n"
2115 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2116 " tc += BloomBlur_Parameters.xy;\n"
2117 " for (i = 1;i < SAMPLES;i++)\n"
2119 " color += tex2D(Texture_First, tc).rgb;\n"
2120 " tc += BloomBlur_Parameters.xy;\n"
2122 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2125 "#else // !MODE_BLOOMBLUR\n"
2126 "#ifdef MODE_REFRACTION\n"
2127 "#ifdef VERTEX_SHADER\n"
2130 "float4 gl_Vertex : POSITION,\n"
2131 "uniform float4x4 ModelViewProjectionMatrix,\n"
2132 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2133 "uniform float4x4 TexMatrix,\n"
2134 "uniform float3 EyePosition,\n"
2135 "out float4 gl_Position : POSITION,\n"
2136 "out float2 TexCoord : TEXCOORD0,\n"
2137 "out float3 EyeVector : TEXCOORD1,\n"
2138 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2141 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2142 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2143 " ModelViewProjectionPosition = gl_Position;\n"
2147 "#ifdef FRAGMENT_SHADER\n"
2150 "float2 TexCoord : TEXCOORD0,\n"
2151 "float3 EyeVector : TEXCOORD1,\n"
2152 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2153 "uniform sampler2D Texture_Normal,\n"
2154 "uniform sampler2D Texture_Refraction,\n"
2155 "uniform sampler2D Texture_Reflection,\n"
2156 "uniform float4 DistortScaleRefractReflect,\n"
2157 "uniform float4 ScreenScaleRefractReflect,\n"
2158 "uniform float4 ScreenCenterRefractReflect,\n"
2159 "uniform float4 RefractColor,\n"
2160 "out float4 gl_FragColor : COLOR\n"
2163 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2164 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2165 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2166 " float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2167 " // FIXME temporary hack to detect the case that the reflection\n"
2168 " // gets blackened at edges due to leaving the area that contains actual\n"
2170 " // Remove this 'ack once we have a better way to stop this thing from\n"
2172 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2173 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2174 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2175 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2176 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2177 " gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2180 "#else // !MODE_REFRACTION\n"
2185 "#ifdef MODE_WATER\n"
2186 "#ifdef VERTEX_SHADER\n"
2190 "float4 gl_Vertex : POSITION,\n"
2191 "uniform float4x4 ModelViewProjectionMatrix,\n"
2192 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2193 "uniform float4x4 TexMatrix,\n"
2194 "uniform float3 EyePosition,\n"
2195 "out float4 gl_Position : POSITION,\n"
2196 "out float2 TexCoord : TEXCOORD0,\n"
2197 "out float3 EyeVector : TEXCOORD1,\n"
2198 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2201 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2202 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2203 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2204 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2205 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2206 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2207 " ModelViewProjectionPosition = gl_Position;\n"
2211 "#ifdef FRAGMENT_SHADER\n"
2214 "float2 TexCoord : TEXCOORD0,\n"
2215 "float3 EyeVector : TEXCOORD1,\n"
2216 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2217 "uniform sampler2D Texture_Normal,\n"
2218 "uniform sampler2D Texture_Refraction,\n"
2219 "uniform sampler2D Texture_Reflection,\n"
2220 "uniform float4 DistortScaleRefractReflect,\n"
2221 "uniform float4 ScreenScaleRefractReflect,\n"
2222 "uniform float4 ScreenCenterRefractReflect,\n"
2223 "uniform float4 RefractColor,\n"
2224 "uniform float4 ReflectColor,\n"
2225 "uniform float ReflectFactor,\n"
2226 "uniform float ReflectOffset,\n"
2227 "out float4 gl_FragColor : COLOR\n"
2230 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2231 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2232 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2233 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2234 " // FIXME temporary hack to detect the case that the reflection\n"
2235 " // gets blackened at edges due to leaving the area that contains actual\n"
2237 " // Remove this 'ack once we have a better way to stop this thing from\n"
2239 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2240 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2241 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2242 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2243 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2244 " f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2245 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2246 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2247 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2248 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2249 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2250 " gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2253 "#else // !MODE_WATER\n"
2258 "// 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"
2260 "// fragment shader specific:\n"
2261 "#ifdef FRAGMENT_SHADER\n"
2264 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask, sampler2D Texture_FogHeightTexture)\n"
2267 "#ifdef USEFOGHEIGHTTEXTURE\n"
2268 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2269 " fogfrac = fogheightpixel.a;\n"
2270 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2272 "# ifdef USEFOGOUTSIDE\n"
2273 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2275 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2277 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2282 "#ifdef USEOFFSETMAPPING\n"
2283 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2285 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2286 " // 14 sample relief mapping: linear search and then binary search\n"
2287 " // this basically steps forward a small amount repeatedly until it finds\n"
2288 " // itself inside solid, then jitters forward and back using decreasing\n"
2289 " // amounts to find the impact\n"
2290 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2291 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2292 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2293 " float3 RT = float3(TexCoord, 1);\n"
2294 " OffsetVector *= 0.1;\n"
2295 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2296 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2297 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2298 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2299 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2300 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2301 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2302 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2303 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2304 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2305 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2306 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2307 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2308 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2311 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2312 " // this basically moves forward the full distance, and then backs up based\n"
2313 " // on height of samples\n"
2314 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2315 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2316 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2317 " TexCoord += OffsetVector;\n"
2318 " OffsetVector *= 0.333;\n"
2319 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2320 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2321 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2322 " return TexCoord;\n"
2325 "#endif // USEOFFSETMAPPING\n"
2327 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2328 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2329 "# ifdef USESHADOWMAPORTHO\n"
2330 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2332 "# ifdef USESHADOWMAPVSDCT\n"
2333 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2335 " float3 adir = abs(dir);\n"
2336 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2337 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2338 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2341 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2343 " float3 adir = abs(dir);\n"
2344 " float ma = adir.z;\n"
2345 " float4 proj = float4(dir, 2.5);\n"
2346 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2347 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2348 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2349 " 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"
2353 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2355 "#ifdef USESHADOWMAPCUBE\n"
2356 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2358 " float3 adir = abs(dir);\n"
2359 " return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2363 "# ifdef USESHADOWMAPRECT\n"
2364 "#ifdef USESHADOWMAPVSDCT\n"
2365 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2367 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2370 "#ifdef USESHADOWMAPVSDCT\n"
2371 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2373 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2376 "# ifdef USESHADOWSAMPLER\n"
2378 "# ifdef USESHADOWMAPPCF\n"
2379 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2380 " f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2382 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2387 "# ifdef USESHADOWMAPPCF\n"
2388 "# if USESHADOWMAPPCF > 1\n"
2389 "# define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2390 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2391 " 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"
2392 " 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"
2393 " 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"
2394 " 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"
2395 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2396 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2398 "# define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2399 " float2 offset = frac(shadowmaptc.xy);\n"
2400 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2401 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2402 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2403 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2404 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2407 " f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2411 "# ifdef USESHADOWMAPORTHO\n"
2412 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2419 "# ifdef USESHADOWMAP2D\n"
2420 "#ifdef USESHADOWMAPVSDCT\n"
2421 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2423 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2426 "#ifdef USESHADOWMAPVSDCT\n"
2427 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2429 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2433 "# ifdef USESHADOWSAMPLER\n"
2434 "# ifdef USESHADOWMAPPCF\n"
2435 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
2436 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2437 " f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2439 " f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2442 "# ifdef USESHADOWMAPPCF\n"
2443 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2444 "# ifdef GL_ARB_texture_gather\n"
2445 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2447 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2449 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2450 " center *= ShadowMap_TextureScale;\n"
2451 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2452 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2453 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2454 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2455 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2456 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2457 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2459 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale) \n"
2460 "# if USESHADOWMAPPCF > 1\n"
2461 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2462 " center *= ShadowMap_TextureScale;\n"
2463 " 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"
2464 " 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"
2465 " 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"
2466 " 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"
2467 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2468 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2470 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2471 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2472 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2473 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2474 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2475 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2479 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2482 "# ifdef USESHADOWMAPORTHO\n"
2483 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2490 "# ifdef USESHADOWMAPCUBE\n"
2491 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2493 " // apply depth texture cubemap as light filter\n"
2494 " float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2496 "# ifdef USESHADOWSAMPLER\n"
2497 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2499 " f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2504 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2505 "#endif // FRAGMENT_SHADER\n"
2510 "#ifdef MODE_DEFERREDGEOMETRY\n"
2511 "#ifdef VERTEX_SHADER\n"
2514 "float4 gl_Vertex : POSITION,\n"
2515 "uniform float4x4 ModelViewProjectionMatrix,\n"
2516 "#ifdef USEVERTEXTEXTUREBLEND\n"
2517 "float4 gl_Color : COLOR0,\n"
2519 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2520 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2521 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2522 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2523 "uniform float4x4 TexMatrix,\n"
2524 "#ifdef USEVERTEXTEXTUREBLEND\n"
2525 "uniform float4x4 BackgroundTexMatrix,\n"
2527 "uniform float4x4 ModelViewMatrix,\n"
2528 "#ifdef USEOFFSETMAPPING\n"
2529 "uniform float3 EyePosition,\n"
2531 "out float4 gl_Position : POSITION,\n"
2532 "out float4 gl_FrontColor : COLOR,\n"
2533 "out float4 TexCoordBoth : TEXCOORD0,\n"
2534 "#ifdef USEOFFSETMAPPING\n"
2535 "out float3 EyeVector : TEXCOORD2,\n"
2537 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2538 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2539 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2542 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2543 "#ifdef USEVERTEXTEXTUREBLEND\n"
2544 " gl_FrontColor = gl_Color;\n"
2545 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2548 " // transform unnormalized eye direction into tangent space\n"
2549 "#ifdef USEOFFSETMAPPING\n"
2550 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2551 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2552 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2553 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2556 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2557 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2558 " VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2559 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2561 "#endif // VERTEX_SHADER\n"
2563 "#ifdef FRAGMENT_SHADER\n"
2566 "float4 TexCoordBoth : TEXCOORD0,\n"
2567 "float3 EyeVector : TEXCOORD2,\n"
2568 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2569 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2570 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2571 "uniform sampler2D Texture_Normal,\n"
2572 "#ifdef USEALPHAKILL\n"
2573 "uniform sampler2D Texture_Color,\n"
2575 "uniform sampler2D Texture_Gloss,\n"
2576 "#ifdef USEVERTEXTEXTUREBLEND\n"
2577 "uniform sampler2D Texture_SecondaryNormal,\n"
2578 "uniform sampler2D Texture_SecondaryGloss,\n"
2580 "#ifdef USEOFFSETMAPPING\n"
2581 "uniform float OffsetMapping_Scale,\n"
2583 "uniform half SpecularPower,\n"
2584 "out float4 gl_FragColor : COLOR\n"
2587 " float2 TexCoord = TexCoordBoth.xy;\n"
2588 "#ifdef USEOFFSETMAPPING\n"
2589 " // apply offsetmapping\n"
2590 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2591 "#define TexCoord TexCoordOffset\n"
2594 "#ifdef USEALPHAKILL\n"
2595 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2599 "#ifdef USEVERTEXTEXTUREBLEND\n"
2600 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2601 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2602 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2603 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2606 "#ifdef USEVERTEXTEXTUREBLEND\n"
2607 " float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2608 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2610 " float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2611 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2614 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2616 "#endif // FRAGMENT_SHADER\n"
2617 "#else // !MODE_DEFERREDGEOMETRY\n"
2622 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2623 "#ifdef VERTEX_SHADER\n"
2626 "float4 gl_Vertex : POSITION,\n"
2627 "uniform float4x4 ModelViewProjectionMatrix,\n"
2628 "uniform float4x4 ModelViewMatrix,\n"
2629 "out float4 gl_Position : POSITION,\n"
2630 "out float4 ModelViewPosition : TEXCOORD0\n"
2633 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2634 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2636 "#endif // VERTEX_SHADER\n"
2638 "#ifdef FRAGMENT_SHADER\n"
2641 "float2 Pixel : WPOS,\n"
2642 "float4 ModelViewPosition : TEXCOORD0,\n"
2643 "uniform float4x4 ViewToLight,\n"
2644 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2645 "uniform float3 LightPosition,\n"
2646 "uniform half2 PixelToScreenTexCoord,\n"
2647 "uniform half3 DeferredColor_Ambient,\n"
2648 "uniform half3 DeferredColor_Diffuse,\n"
2649 "#ifdef USESPECULAR\n"
2650 "uniform half3 DeferredColor_Specular,\n"
2651 "uniform half SpecularPower,\n"
2653 "uniform sampler2D Texture_Attenuation,\n"
2654 "uniform sampler2D Texture_ScreenDepth,\n"
2655 "uniform sampler2D Texture_ScreenNormalMap,\n"
2657 "#ifdef USECUBEFILTER\n"
2658 "uniform samplerCUBE Texture_Cube,\n"
2661 "#ifdef USESHADOWMAPRECT\n"
2662 "# ifdef USESHADOWSAMPLER\n"
2663 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2665 "uniform samplerRECT Texture_ShadowMapRect,\n"
2669 "#ifdef USESHADOWMAP2D\n"
2670 "# ifdef USESHADOWSAMPLER\n"
2671 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2673 "uniform sampler2D Texture_ShadowMap2D,\n"
2677 "#ifdef USESHADOWMAPVSDCT\n"
2678 "uniform samplerCUBE Texture_CubeProjection,\n"
2681 "#ifdef USESHADOWMAPCUBE\n"
2682 "# ifdef USESHADOWSAMPLER\n"
2683 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2685 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2689 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2690 "uniform float2 ShadowMap_TextureScale,\n"
2691 "uniform float4 ShadowMap_Parameters,\n"
2694 "out float4 gl_FragData0 : COLOR0,\n"
2695 "out float4 gl_FragData1 : COLOR1\n"
2698 " // calculate viewspace pixel position\n"
2699 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2700 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2701 " float3 position;\n"
2702 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2703 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2704 " // decode viewspace pixel normal\n"
2705 " half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2706 " half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2707 " // surfacenormal = pixel normal in viewspace\n"
2708 " // LightVector = pixel to light in viewspace\n"
2709 " // CubeVector = position in lightspace\n"
2710 " // eyevector = pixel to view in viewspace\n"
2711 " float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2712 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2713 "#ifdef USEDIFFUSE\n"
2714 " // calculate diffuse shading\n"
2715 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2716 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2718 "#ifdef USESPECULAR\n"
2719 " // calculate directional shading\n"
2720 " float3 eyevector = position * -1.0;\n"
2721 "# ifdef USEEXACTSPECULARMATH\n"
2722 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2724 " half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2725 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2729 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2730 " fade *= ShadowMapCompare(CubeVector,\n"
2731 "# if defined(USESHADOWMAP2D)\n"
2732 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2734 "# if defined(USESHADOWMAPRECT)\n"
2735 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2737 "# if defined(USESHADOWMAPCUBE)\n"
2738 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2741 "#ifdef USESHADOWMAPVSDCT\n"
2742 ", Texture_CubeProjection\n"
2747 "#ifdef USEDIFFUSE\n"
2748 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2750 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2752 "#ifdef USESPECULAR\n"
2753 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2755 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2758 "# ifdef USECUBEFILTER\n"
2759 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2760 " gl_FragData0.rgb *= cubecolor;\n"
2761 " gl_FragData1.rgb *= cubecolor;\n"
2764 "#endif // FRAGMENT_SHADER\n"
2765 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2770 "#ifdef VERTEX_SHADER\n"
2773 "float4 gl_Vertex : POSITION,\n"
2774 "uniform float4x4 ModelViewProjectionMatrix,\n"
2775 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2776 "float4 gl_Color : COLOR0,\n"
2778 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2779 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2780 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2781 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2782 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2784 "uniform float3 EyePosition,\n"
2785 "uniform float4x4 TexMatrix,\n"
2786 "#ifdef USEVERTEXTEXTUREBLEND\n"
2787 "uniform float4x4 BackgroundTexMatrix,\n"
2789 "#ifdef MODE_LIGHTSOURCE\n"
2790 "uniform float4x4 ModelToLight,\n"
2792 "#ifdef MODE_LIGHTSOURCE\n"
2793 "uniform float3 LightPosition,\n"
2795 "#ifdef MODE_LIGHTDIRECTION\n"
2796 "uniform float3 LightDir,\n"
2798 "uniform float4 FogPlane,\n"
2799 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2800 "uniform float3 LightPosition,\n"
2802 "#ifdef USESHADOWMAPORTHO\n"
2803 "uniform float4x4 ShadowMapMatrix,\n"
2806 "out float4 gl_FrontColor : COLOR,\n"
2807 "out float4 TexCoordBoth : TEXCOORD0,\n"
2808 "#ifdef USELIGHTMAP\n"
2809 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2811 "#ifdef USEEYEVECTOR\n"
2812 "out float3 EyeVector : TEXCOORD2,\n"
2814 "#ifdef USEREFLECTION\n"
2815 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2818 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2820 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2821 "out float3 LightVector : TEXCOORD1,\n"
2823 "#ifdef MODE_LIGHTSOURCE\n"
2824 "out float3 CubeVector : TEXCOORD3,\n"
2826 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2827 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2828 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2829 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2831 "#ifdef USESHADOWMAPORTHO\n"
2832 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2834 "out float4 gl_Position : POSITION\n"
2837 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2838 " gl_FrontColor = gl_Color;\n"
2840 " // copy the surface texcoord\n"
2841 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2842 "#ifdef USEVERTEXTEXTUREBLEND\n"
2843 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2845 "#ifdef USELIGHTMAP\n"
2846 " TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2849 "#ifdef MODE_LIGHTSOURCE\n"
2850 " // transform vertex position into light attenuation/cubemap space\n"
2851 " // (-1 to +1 across the light box)\n"
2852 " CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2854 "# ifdef USEDIFFUSE\n"
2855 " // transform unnormalized light direction into tangent space\n"
2856 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2857 " // normalize it per pixel)\n"
2858 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2859 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2860 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2861 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2865 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2866 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2867 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2868 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2871 " // transform unnormalized eye direction into tangent space\n"
2872 "#ifdef USEEYEVECTOR\n"
2873 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2874 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2875 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2876 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2880 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2881 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2884 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2885 " VectorS = gl_MultiTexCoord1.xyz;\n"
2886 " VectorT = gl_MultiTexCoord2.xyz;\n"
2887 " VectorR = gl_MultiTexCoord3.xyz;\n"
2890 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2891 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2893 "#ifdef USESHADOWMAPORTHO\n"
2894 " ShadowMapTC = float3(mul(ShadowMapMatrix, gl_Position));\n"
2897 "#ifdef USEREFLECTION\n"
2898 " ModelViewProjectionPosition = gl_Position;\n"
2901 "#endif // VERTEX_SHADER\n"
2906 "#ifdef FRAGMENT_SHADER\n"
2909 "#ifdef USEDEFERREDLIGHTMAP\n"
2910 "float2 Pixel : WPOS,\n"
2912 "float4 gl_FrontColor : COLOR,\n"
2913 "float4 TexCoordBoth : TEXCOORD0,\n"
2914 "#ifdef USELIGHTMAP\n"
2915 "float2 TexCoordLightmap : TEXCOORD1,\n"
2917 "#ifdef USEEYEVECTOR\n"
2918 "float3 EyeVector : TEXCOORD2,\n"
2920 "#ifdef USEREFLECTION\n"
2921 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2924 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2926 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2927 "float3 LightVector : TEXCOORD1,\n"
2929 "#ifdef MODE_LIGHTSOURCE\n"
2930 "float3 CubeVector : TEXCOORD3,\n"
2932 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2933 "float4 ModelViewPosition : TEXCOORD0,\n"
2935 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2936 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2937 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2938 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2940 "#ifdef USESHADOWMAPORTHO\n"
2941 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2944 "uniform sampler2D Texture_Normal,\n"
2945 "uniform sampler2D Texture_Color,\n"
2946 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2947 "uniform sampler2D Texture_Gloss,\n"
2950 "uniform sampler2D Texture_Glow,\n"
2952 "#ifdef USEVERTEXTEXTUREBLEND\n"
2953 "uniform sampler2D Texture_SecondaryNormal,\n"
2954 "uniform sampler2D Texture_SecondaryColor,\n"
2955 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2956 "uniform sampler2D Texture_SecondaryGloss,\n"
2959 "uniform sampler2D Texture_SecondaryGlow,\n"
2962 "#ifdef USECOLORMAPPING\n"
2963 "uniform sampler2D Texture_Pants,\n"
2964 "uniform sampler2D Texture_Shirt,\n"
2967 "uniform sampler2D Texture_FogHeightTexture,\n"
2968 "uniform sampler2D Texture_FogMask,\n"
2970 "#ifdef USELIGHTMAP\n"
2971 "uniform sampler2D Texture_Lightmap,\n"
2973 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2974 "uniform sampler2D Texture_Deluxemap,\n"
2976 "#ifdef USEREFLECTION\n"
2977 "uniform sampler2D Texture_Reflection,\n"
2980 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2981 "uniform sampler2D Texture_ScreenDepth,\n"
2982 "uniform sampler2D Texture_ScreenNormalMap,\n"
2984 "#ifdef USEDEFERREDLIGHTMAP\n"
2985 "uniform sampler2D Texture_ScreenDiffuse,\n"
2986 "uniform sampler2D Texture_ScreenSpecular,\n"
2989 "#ifdef USECOLORMAPPING\n"
2990 "uniform half3 Color_Pants,\n"
2991 "uniform half3 Color_Shirt,\n"
2994 "uniform float3 FogColor,\n"
2995 "uniform float FogRangeRecip,\n"
2996 "uniform float FogPlaneViewDist,\n"
2997 "uniform float FogHeightFade,\n"
3000 "#ifdef USEOFFSETMAPPING\n"
3001 "uniform float OffsetMapping_Scale,\n"
3004 "#ifdef USEDEFERREDLIGHTMAP\n"
3005 "uniform half2 PixelToScreenTexCoord,\n"
3006 "uniform half3 DeferredMod_Diffuse,\n"
3007 "uniform half3 DeferredMod_Specular,\n"
3009 "uniform half3 Color_Ambient,\n"
3010 "uniform half3 Color_Diffuse,\n"
3011 "uniform half3 Color_Specular,\n"
3012 "uniform half SpecularPower,\n"
3014 "uniform half3 Color_Glow,\n"
3016 "uniform half Alpha,\n"
3017 "#ifdef USEREFLECTION\n"
3018 "uniform float4 DistortScaleRefractReflect,\n"
3019 "uniform float4 ScreenScaleRefractReflect,\n"
3020 "uniform float4 ScreenCenterRefractReflect,\n"
3021 "uniform half4 ReflectColor,\n"
3023 "#ifdef USEREFLECTCUBE\n"
3024 "uniform float4x4 ModelToReflectCube,\n"
3025 "uniform sampler2D Texture_ReflectMask,\n"
3026 "uniform samplerCUBE Texture_ReflectCube,\n"
3028 "#ifdef MODE_LIGHTDIRECTION\n"
3029 "uniform half3 LightColor,\n"
3031 "#ifdef MODE_LIGHTSOURCE\n"
3032 "uniform half3 LightColor,\n"
3035 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3036 "uniform sampler2D Texture_Attenuation,\n"
3037 "uniform samplerCUBE Texture_Cube,\n"
3040 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3042 "#ifdef USESHADOWMAPRECT\n"
3043 "# ifdef USESHADOWSAMPLER\n"
3044 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
3046 "uniform samplerRECT Texture_ShadowMapRect,\n"
3050 "#ifdef USESHADOWMAP2D\n"
3051 "# ifdef USESHADOWSAMPLER\n"
3052 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
3054 "uniform sampler2D Texture_ShadowMap2D,\n"
3058 "#ifdef USESHADOWMAPVSDCT\n"
3059 "uniform samplerCUBE Texture_CubeProjection,\n"
3062 "#ifdef USESHADOWMAPCUBE\n"
3063 "# ifdef USESHADOWSAMPLER\n"
3064 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
3066 "uniform samplerCUBE Texture_ShadowMapCube,\n"
3070 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3071 "uniform float2 ShadowMap_TextureScale,\n"
3072 "uniform float4 ShadowMap_Parameters,\n"
3074 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3076 "out float4 gl_FragColor : COLOR\n"
3079 " float2 TexCoord = TexCoordBoth.xy;\n"
3080 "#ifdef USEVERTEXTEXTUREBLEND\n"
3081 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3083 "#ifdef USEOFFSETMAPPING\n"
3084 " // apply offsetmapping\n"
3085 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3086 "#define TexCoord TexCoordOffset\n"
3089 " // combine the diffuse textures (base, pants, shirt)\n"
3090 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3091 "#ifdef USEALPHAKILL\n"
3092 " if (color.a < 0.5)\n"
3095 " color.a *= Alpha;\n"
3096 "#ifdef USECOLORMAPPING\n"
3097 " color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
3099 "#ifdef USEVERTEXTEXTUREBLEND\n"
3100 " float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3101 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3102 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3103 " color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
3105 " //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
3108 " // get the surface normal\n"
3109 "#ifdef USEVERTEXTEXTUREBLEND\n"
3110 " half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3112 " half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
3115 " // get the material colors\n"
3116 " half3 diffusetex = color.rgb;\n"
3117 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3118 "# ifdef USEVERTEXTEXTUREBLEND\n"
3119 " half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
3121 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3125 "#ifdef USEREFLECTCUBE\n"
3126 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3127 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3128 " float3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
3129 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
3135 "#ifdef MODE_LIGHTSOURCE\n"
3136 " // light source\n"
3137 "#ifdef USEDIFFUSE\n"
3138 " half3 lightnormal = half3(normalize(LightVector));\n"
3139 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3140 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3141 "#ifdef USESPECULAR\n"
3142 "#ifdef USEEXACTSPECULARMATH\n"
3143 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3145 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3146 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3148 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3151 " color.rgb = diffusetex * Color_Ambient;\n"
3153 " color.rgb *= LightColor;\n"
3154 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3155 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3156 " color.rgb *= ShadowMapCompare(CubeVector,\n"
3157 "# if defined(USESHADOWMAP2D)\n"
3158 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3160 "# if defined(USESHADOWMAPRECT)\n"
3161 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3163 "# if defined(USESHADOWMAPCUBE)\n"
3164 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3167 "#ifdef USESHADOWMAPVSDCT\n"
3168 ", Texture_CubeProjection\n"
3173 "# ifdef USECUBEFILTER\n"
3174 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3176 "#endif // MODE_LIGHTSOURCE\n"
3181 "#ifdef MODE_LIGHTDIRECTION\n"
3183 "#ifdef USEDIFFUSE\n"
3184 " half3 lightnormal = half3(normalize(LightVector));\n"
3186 "#define lightcolor LightColor\n"
3187 "#endif // MODE_LIGHTDIRECTION\n"
3188 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3190 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3191 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3192 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3193 " // convert modelspace light vector to tangentspace\n"
3194 " half3 lightnormal;\n"
3195 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3196 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3197 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3198 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3199 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3200 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3201 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3202 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3203 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3204 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3205 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3206 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3207 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3208 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3209 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3211 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3212 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3213 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3219 "#ifdef MODE_LIGHTMAP\n"
3220 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3221 "#endif // MODE_LIGHTMAP\n"
3222 "#ifdef MODE_VERTEXCOLOR\n"
3223 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3224 "#endif // MODE_VERTEXCOLOR\n"
3225 "#ifdef MODE_FLATCOLOR\n"
3226 " color.rgb = diffusetex * Color_Ambient;\n"
3227 "#endif // MODE_FLATCOLOR\n"
3233 "# ifdef USEDIFFUSE\n"
3234 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3235 "# ifdef USESPECULAR\n"
3236 "# ifdef USEEXACTSPECULARMATH\n"
3237 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3239 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3240 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3242 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3244 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3247 " color.rgb = diffusetex * Color_Ambient;\n"
3251 "#ifdef USESHADOWMAPORTHO\n"
3252 " color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3253 "# if defined(USESHADOWMAP2D)\n"
3254 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3256 "# if defined(USESHADOWMAPRECT)\n"
3257 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3262 "#ifdef USEDEFERREDLIGHTMAP\n"
3263 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3264 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3265 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3269 "#ifdef USEVERTEXTEXTUREBLEND\n"
3270 " color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3272 " color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3277 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3280 " // 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"
3281 "#ifdef USEREFLECTION\n"
3282 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3283 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3284 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3285 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3286 " // FIXME temporary hack to detect the case that the reflection\n"
3287 " // gets blackened at edges due to leaving the area that contains actual\n"
3289 " // Remove this 'ack once we have a better way to stop this thing from\n"
3291 " float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3292 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3293 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3294 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3295 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3296 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3299 " gl_FragColor = float4(color);\n"
3301 "#endif // FRAGMENT_SHADER\n"
3303 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3304 "#endif // !MODE_DEFERREDGEOMETRY\n"
3305 "#endif // !MODE_WATER\n"
3306 "#endif // !MODE_REFRACTION\n"
3307 "#endif // !MODE_BLOOMBLUR\n"
3308 "#endif // !MODE_GENERIC\n"
3309 "#endif // !MODE_POSTPROCESS\n"
3310 "#endif // !MODE_SHOWDEPTH\n"
3311 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3314 char *glslshaderstring = NULL;
3315 char *cgshaderstring = NULL;
3317 //=======================================================================================================================================================
3319 typedef struct shaderpermutationinfo_s
3321 const char *pretext;
3324 shaderpermutationinfo_t;
3326 typedef struct shadermodeinfo_s
3328 const char *vertexfilename;
3329 const char *geometryfilename;
3330 const char *fragmentfilename;
3331 const char *pretext;
3336 typedef enum shaderpermutation_e
3338 SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3339 SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3340 SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3341 SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3342 SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3343 SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3344 SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3345 SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3346 SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3347 SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3348 SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3349 SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3350 SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3351 SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3352 SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3353 SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3354 SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3355 SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3356 SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3357 SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3358 SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3359 SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3360 SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3361 SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3362 SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3363 SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3364 SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3365 SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3366 SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3367 SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3368 SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3370 shaderpermutation_t;
3372 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3373 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3375 {"#define USEDIFFUSE\n", " diffuse"},
3376 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3377 {"#define USEVIEWTINT\n", " viewtint"},
3378 {"#define USECOLORMAPPING\n", " colormapping"},
3379 {"#define USESATURATION\n", " saturation"},
3380 {"#define USEFOGINSIDE\n", " foginside"},
3381 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3382 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3383 {"#define USEGAMMARAMPS\n", " gammaramps"},
3384 {"#define USECUBEFILTER\n", " cubefilter"},
3385 {"#define USEGLOW\n", " glow"},
3386 {"#define USEBLOOM\n", " bloom"},
3387 {"#define USESPECULAR\n", " specular"},
3388 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3389 {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3390 {"#define USEREFLECTION\n", " reflection"},
3391 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3392 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3393 {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3394 {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3395 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3396 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3397 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3398 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3399 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3400 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3401 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3402 {"#define USEALPHAKILL\n", " alphakill"},
3403 {"#define USEREFLECTCUBE\n", " reflectcube"},
3406 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3407 typedef enum shadermode_e
3409 SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3410 SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3411 SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3412 SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3413 SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3414 SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3415 SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3416 SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3417 SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3418 SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3419 SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3420 SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3421 SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3422 SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3423 SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3428 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3429 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3431 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3432 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3433 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3434 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3435 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3436 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3437 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3438 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3439 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3440 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3441 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3442 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3443 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3444 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3445 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3449 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3451 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3452 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3453 {"cg/default.cg", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3454 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3455 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3456 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3457 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3458 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3459 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3460 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3461 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3462 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3463 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3464 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3465 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3469 struct r_glsl_permutation_s;
3470 typedef struct r_glsl_permutation_s
3472 /// hash lookup data
3473 struct r_glsl_permutation_s *hashnext;
3475 unsigned int permutation;
3477 /// indicates if we have tried compiling this permutation already
3479 /// 0 if compilation failed
3481 /// locations of detected uniforms in program object, or -1 if not found
3482 int loc_Texture_First;
3483 int loc_Texture_Second;
3484 int loc_Texture_GammaRamps;
3485 int loc_Texture_Normal;
3486 int loc_Texture_Color;
3487 int loc_Texture_Gloss;
3488 int loc_Texture_Glow;
3489 int loc_Texture_SecondaryNormal;
3490 int loc_Texture_SecondaryColor;
3491 int loc_Texture_SecondaryGloss;
3492 int loc_Texture_SecondaryGlow;
3493 int loc_Texture_Pants;
3494 int loc_Texture_Shirt;
3495 int loc_Texture_FogHeightTexture;
3496 int loc_Texture_FogMask;
3497 int loc_Texture_Lightmap;
3498 int loc_Texture_Deluxemap;
3499 int loc_Texture_Attenuation;
3500 int loc_Texture_Cube;
3501 int loc_Texture_Refraction;
3502 int loc_Texture_Reflection;
3503 int loc_Texture_ShadowMapRect;
3504 int loc_Texture_ShadowMapCube;
3505 int loc_Texture_ShadowMap2D;
3506 int loc_Texture_CubeProjection;
3507 int loc_Texture_ScreenDepth;
3508 int loc_Texture_ScreenNormalMap;
3509 int loc_Texture_ScreenDiffuse;
3510 int loc_Texture_ScreenSpecular;
3511 int loc_Texture_ReflectMask;
3512 int loc_Texture_ReflectCube;
3514 int loc_BloomBlur_Parameters;
3516 int loc_Color_Ambient;
3517 int loc_Color_Diffuse;
3518 int loc_Color_Specular;
3520 int loc_Color_Pants;
3521 int loc_Color_Shirt;
3522 int loc_DeferredColor_Ambient;
3523 int loc_DeferredColor_Diffuse;
3524 int loc_DeferredColor_Specular;
3525 int loc_DeferredMod_Diffuse;
3526 int loc_DeferredMod_Specular;
3527 int loc_DistortScaleRefractReflect;
3528 int loc_EyePosition;
3530 int loc_FogHeightFade;
3532 int loc_FogPlaneViewDist;
3533 int loc_FogRangeRecip;
3536 int loc_LightPosition;
3537 int loc_OffsetMapping_Scale;
3539 int loc_ReflectColor;
3540 int loc_ReflectFactor;
3541 int loc_ReflectOffset;
3542 int loc_RefractColor;
3544 int loc_ScreenCenterRefractReflect;
3545 int loc_ScreenScaleRefractReflect;
3546 int loc_ScreenToDepth;
3547 int loc_ShadowMap_Parameters;
3548 int loc_ShadowMap_TextureScale;
3549 int loc_SpecularPower;
3554 int loc_ViewTintColor;
3555 int loc_ViewToLight;
3556 int loc_ModelToLight;
3558 int loc_BackgroundTexMatrix;
3559 int loc_ModelViewProjectionMatrix;
3560 int loc_ModelViewMatrix;
3561 int loc_PixelToScreenTexCoord;
3562 int loc_ModelToReflectCube;
3563 int loc_ShadowMapMatrix;
3565 r_glsl_permutation_t;
3567 #define SHADERPERMUTATION_HASHSIZE 256
3569 /// information about each possible shader permutation
3570 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3571 /// currently selected permutation
3572 r_glsl_permutation_t *r_glsl_permutation;
3573 /// storage for permutations linked in the hash table
3574 memexpandablearray_t r_glsl_permutationarray;
3576 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3578 //unsigned int hashdepth = 0;
3579 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3580 r_glsl_permutation_t *p;
3581 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3583 if (p->mode == mode && p->permutation == permutation)
3585 //if (hashdepth > 10)
3586 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3591 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3593 p->permutation = permutation;
3594 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3595 r_glsl_permutationhash[mode][hashindex] = p;
3596 //if (hashdepth > 10)
3597 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3601 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3604 if (!filename || !filename[0])
3606 if (!strcmp(filename, "glsl/default.glsl"))
3608 if (!glslshaderstring)
3610 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3611 if (glslshaderstring)
3612 Con_DPrintf("Loading shaders from file %s...\n", filename);
3614 glslshaderstring = (char *)builtinshaderstring;
3616 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3617 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3618 return shaderstring;
3620 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3623 if (printfromdisknotice)
3624 Con_DPrintf("from disk %s... ", filename);
3625 return shaderstring;
3627 return shaderstring;
3630 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3633 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3634 int vertstrings_count = 0;
3635 int geomstrings_count = 0;
3636 int fragstrings_count = 0;
3637 char *vertexstring, *geometrystring, *fragmentstring;
3638 const char *vertstrings_list[32+3];
3639 const char *geomstrings_list[32+3];
3640 const char *fragstrings_list[32+3];
3641 char permutationname[256];
3648 permutationname[0] = 0;
3649 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3650 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3651 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3653 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3655 // the first pretext is which type of shader to compile as
3656 // (later these will all be bound together as a program object)
3657 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3658 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3659 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3661 // the second pretext is the mode (for example a light source)
3662 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3663 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3664 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3665 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3667 // now add all the permutation pretexts
3668 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3670 if (permutation & (1<<i))
3672 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3673 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3674 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3675 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3679 // keep line numbers correct
3680 vertstrings_list[vertstrings_count++] = "\n";
3681 geomstrings_list[geomstrings_count++] = "\n";
3682 fragstrings_list[fragstrings_count++] = "\n";
3686 // now append the shader text itself
3687 vertstrings_list[vertstrings_count++] = vertexstring;
3688 geomstrings_list[geomstrings_count++] = geometrystring;
3689 fragstrings_list[fragstrings_count++] = fragmentstring;
3691 // if any sources were NULL, clear the respective list
3693 vertstrings_count = 0;
3694 if (!geometrystring)
3695 geomstrings_count = 0;
3696 if (!fragmentstring)
3697 fragstrings_count = 0;
3699 // compile the shader program
3700 if (vertstrings_count + geomstrings_count + fragstrings_count)
3701 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3705 qglUseProgramObjectARB(p->program);CHECKGLERROR
3706 // look up all the uniform variable names we care about, so we don't
3707 // have to look them up every time we set them
3709 p->loc_Texture_First = qglGetUniformLocationARB(p->program, "Texture_First");
3710 p->loc_Texture_Second = qglGetUniformLocationARB(p->program, "Texture_Second");
3711 p->loc_Texture_GammaRamps = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3712 p->loc_Texture_Normal = qglGetUniformLocationARB(p->program, "Texture_Normal");
3713 p->loc_Texture_Color = qglGetUniformLocationARB(p->program, "Texture_Color");
3714 p->loc_Texture_Gloss = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3715 p->loc_Texture_Glow = qglGetUniformLocationARB(p->program, "Texture_Glow");
3716 p->loc_Texture_SecondaryNormal = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3717 p->loc_Texture_SecondaryColor = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3718 p->loc_Texture_SecondaryGloss = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3719 p->loc_Texture_SecondaryGlow = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3720 p->loc_Texture_Pants = qglGetUniformLocationARB(p->program, "Texture_Pants");
3721 p->loc_Texture_Shirt = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3722 p->loc_Texture_FogHeightTexture = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3723 p->loc_Texture_FogMask = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3724 p->loc_Texture_Lightmap = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3725 p->loc_Texture_Deluxemap = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3726 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3727 p->loc_Texture_Cube = qglGetUniformLocationARB(p->program, "Texture_Cube");
3728 p->loc_Texture_Refraction = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3729 p->loc_Texture_Reflection = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3730 p->loc_Texture_ShadowMapRect = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3731 p->loc_Texture_ShadowMapCube = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3732 p->loc_Texture_ShadowMap2D = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3733 p->loc_Texture_CubeProjection = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3734 p->loc_Texture_ScreenDepth = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3735 p->loc_Texture_ScreenNormalMap = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3736 p->loc_Texture_ScreenDiffuse = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3737 p->loc_Texture_ScreenSpecular = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3738 p->loc_Texture_ReflectMask = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3739 p->loc_Texture_ReflectCube = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3740 p->loc_Alpha = qglGetUniformLocationARB(p->program, "Alpha");
3741 p->loc_BloomBlur_Parameters = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3742 p->loc_ClientTime = qglGetUniformLocationARB(p->program, "ClientTime");
3743 p->loc_Color_Ambient = qglGetUniformLocationARB(p->program, "Color_Ambient");
3744 p->loc_Color_Diffuse = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3745 p->loc_Color_Specular = qglGetUniformLocationARB(p->program, "Color_Specular");
3746 p->loc_Color_Glow = qglGetUniformLocationARB(p->program, "Color_Glow");
3747 p->loc_Color_Pants = qglGetUniformLocationARB(p->program, "Color_Pants");
3748 p->loc_Color_Shirt = qglGetUniformLocationARB(p->program, "Color_Shirt");
3749 p->loc_DeferredColor_Ambient = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3750 p->loc_DeferredColor_Diffuse = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3751 p->loc_DeferredColor_Specular = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3752 p->loc_DeferredMod_Diffuse = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3753 p->loc_DeferredMod_Specular = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3754 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3755 p->loc_EyePosition = qglGetUniformLocationARB(p->program, "EyePosition");
3756 p->loc_FogColor = qglGetUniformLocationARB(p->program, "FogColor");
3757 p->loc_FogHeightFade = qglGetUniformLocationARB(p->program, "FogHeightFade");
3758 p->loc_FogPlane = qglGetUniformLocationARB(p->program, "FogPlane");
3759 p->loc_FogPlaneViewDist = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3760 p->loc_FogRangeRecip = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3761 p->loc_LightColor = qglGetUniformLocationARB(p->program, "LightColor");
3762 p->loc_LightDir = qglGetUniformLocationARB(p->program, "LightDir");
3763 p->loc_LightPosition = qglGetUniformLocationARB(p->program, "LightPosition");
3764 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3765 p->loc_PixelSize = qglGetUniformLocationARB(p->program, "PixelSize");
3766 p->loc_ReflectColor = qglGetUniformLocationARB(p->program, "ReflectColor");
3767 p->loc_ReflectFactor = qglGetUniformLocationARB(p->program, "ReflectFactor");
3768 p->loc_ReflectOffset = qglGetUniformLocationARB(p->program, "ReflectOffset");
3769 p->loc_RefractColor = qglGetUniformLocationARB(p->program, "RefractColor");
3770 p->loc_Saturation = qglGetUniformLocationARB(p->program, "Saturation");
3771 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3772 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3773 p->loc_ScreenToDepth = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3774 p->loc_ShadowMap_Parameters = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3775 p->loc_ShadowMap_TextureScale = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3776 p->loc_SpecularPower = qglGetUniformLocationARB(p->program, "SpecularPower");
3777 p->loc_UserVec1 = qglGetUniformLocationARB(p->program, "UserVec1");
3778 p->loc_UserVec2 = qglGetUniformLocationARB(p->program, "UserVec2");
3779 p->loc_UserVec3 = qglGetUniformLocationARB(p->program, "UserVec3");
3780 p->loc_UserVec4 = qglGetUniformLocationARB(p->program, "UserVec4");
3781 p->loc_ViewTintColor = qglGetUniformLocationARB(p->program, "ViewTintColor");
3782 p->loc_ViewToLight = qglGetUniformLocationARB(p->program, "ViewToLight");
3783 p->loc_ModelToLight = qglGetUniformLocationARB(p->program, "ModelToLight");
3784 p->loc_TexMatrix = qglGetUniformLocationARB(p->program, "TexMatrix");
3785 p->loc_BackgroundTexMatrix = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3786 p->loc_ModelViewMatrix = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3787 p->loc_ModelViewProjectionMatrix = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3788 p->loc_PixelToScreenTexCoord = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3789 p->loc_ModelToReflectCube = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3790 p->loc_ShadowMapMatrix = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3791 // initialize the samplers to refer to the texture units we use
3792 if (p->loc_Texture_First >= 0) qglUniform1iARB(p->loc_Texture_First , GL20TU_FIRST);
3793 if (p->loc_Texture_Second >= 0) qglUniform1iARB(p->loc_Texture_Second , GL20TU_SECOND);
3794 if (p->loc_Texture_GammaRamps >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps , GL20TU_GAMMARAMPS);
3795 if (p->loc_Texture_Normal >= 0) qglUniform1iARB(p->loc_Texture_Normal , GL20TU_NORMAL);
3796 if (p->loc_Texture_Color >= 0) qglUniform1iARB(p->loc_Texture_Color , GL20TU_COLOR);
3797 if (p->loc_Texture_Gloss >= 0) qglUniform1iARB(p->loc_Texture_Gloss , GL20TU_GLOSS);
3798 if (p->loc_Texture_Glow >= 0) qglUniform1iARB(p->loc_Texture_Glow , GL20TU_GLOW);
3799 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3800 if (p->loc_Texture_SecondaryColor >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3801 if (p->loc_Texture_SecondaryGloss >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3802 if (p->loc_Texture_SecondaryGlow >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow , GL20TU_SECONDARY_GLOW);
3803 if (p->loc_Texture_Pants >= 0) qglUniform1iARB(p->loc_Texture_Pants , GL20TU_PANTS);
3804 if (p->loc_Texture_Shirt >= 0) qglUniform1iARB(p->loc_Texture_Shirt , GL20TU_SHIRT);
3805 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3806 if (p->loc_Texture_FogMask >= 0) qglUniform1iARB(p->loc_Texture_FogMask , GL20TU_FOGMASK);
3807 if (p->loc_Texture_Lightmap >= 0) qglUniform1iARB(p->loc_Texture_Lightmap , GL20TU_LIGHTMAP);
3808 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap , GL20TU_DELUXEMAP);
3809 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation , GL20TU_ATTENUATION);
3810 if (p->loc_Texture_Cube >= 0) qglUniform1iARB(p->loc_Texture_Cube , GL20TU_CUBE);
3811 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction , GL20TU_REFRACTION);
3812 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection , GL20TU_REFLECTION);
3813 if (p->loc_Texture_ShadowMapRect >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3814 if (p->loc_Texture_ShadowMapCube >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube , GL20TU_SHADOWMAPCUBE);
3815 if (p->loc_Texture_ShadowMap2D >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3816 if (p->loc_Texture_CubeProjection >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3817 if (p->loc_Texture_ScreenDepth >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth , GL20TU_SCREENDEPTH);
3818 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3819 if (p->loc_Texture_ScreenDiffuse >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse , GL20TU_SCREENDIFFUSE);
3820 if (p->loc_Texture_ScreenSpecular >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3821 if (p->loc_Texture_ReflectMask >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask , GL20TU_REFLECTMASK);
3822 if (p->loc_Texture_ReflectCube >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube , GL20TU_REFLECTCUBE);
3824 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3827 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
3831 Mem_Free(vertexstring);
3833 Mem_Free(geometrystring);
3835 Mem_Free(fragmentstring);
3838 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3840 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3841 if (r_glsl_permutation != perm)
3843 r_glsl_permutation = perm;
3844 if (!r_glsl_permutation->program)
3846 if (!r_glsl_permutation->compiled)
3847 R_GLSL_CompilePermutation(perm, mode, permutation);
3848 if (!r_glsl_permutation->program)
3850 // remove features until we find a valid permutation
3852 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3854 // reduce i more quickly whenever it would not remove any bits
3855 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3856 if (!(permutation & j))
3859 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3860 if (!r_glsl_permutation->compiled)
3861 R_GLSL_CompilePermutation(perm, mode, permutation);
3862 if (r_glsl_permutation->program)
3865 if (i >= SHADERPERMUTATION_COUNT)
3867 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3868 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3869 qglUseProgramObjectARB(0);CHECKGLERROR
3870 return; // no bit left to clear, entire mode is broken
3875 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3877 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3878 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3879 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3883 #include <Cg/cgGL.h>
3884 struct r_cg_permutation_s;
3885 typedef struct r_cg_permutation_s
3887 /// hash lookup data
3888 struct r_cg_permutation_s *hashnext;
3890 unsigned int permutation;
3892 /// indicates if we have tried compiling this permutation already
3894 /// 0 if compilation failed
3897 /// locations of detected parameters in programs, or NULL if not found
3898 CGparameter vp_EyePosition;
3899 CGparameter vp_FogPlane;
3900 CGparameter vp_LightDir;
3901 CGparameter vp_LightPosition;
3902 CGparameter vp_ModelToLight;
3903 CGparameter vp_TexMatrix;
3904 CGparameter vp_BackgroundTexMatrix;
3905 CGparameter vp_ModelViewProjectionMatrix;
3906 CGparameter vp_ModelViewMatrix;
3907 CGparameter vp_ShadowMapMatrix;
3909 CGparameter fp_Texture_First;
3910 CGparameter fp_Texture_Second;
3911 CGparameter fp_Texture_GammaRamps;
3912 CGparameter fp_Texture_Normal;
3913 CGparameter fp_Texture_Color;
3914 CGparameter fp_Texture_Gloss;
3915 CGparameter fp_Texture_Glow;
3916 CGparameter fp_Texture_SecondaryNormal;
3917 CGparameter fp_Texture_SecondaryColor;
3918 CGparameter fp_Texture_SecondaryGloss;
3919 CGparameter fp_Texture_SecondaryGlow;
3920 CGparameter fp_Texture_Pants;
3921 CGparameter fp_Texture_Shirt;
3922 CGparameter fp_Texture_FogHeightTexture;
3923 CGparameter fp_Texture_FogMask;
3924 CGparameter fp_Texture_Lightmap;
3925 CGparameter fp_Texture_Deluxemap;
3926 CGparameter fp_Texture_Attenuation;
3927 CGparameter fp_Texture_Cube;
3928 CGparameter fp_Texture_Refraction;
3929 CGparameter fp_Texture_Reflection;
3930 CGparameter fp_Texture_ShadowMapRect;
3931 CGparameter fp_Texture_ShadowMapCube;
3932 CGparameter fp_Texture_ShadowMap2D;
3933 CGparameter fp_Texture_CubeProjection;
3934 CGparameter fp_Texture_ScreenDepth;
3935 CGparameter fp_Texture_ScreenNormalMap;
3936 CGparameter fp_Texture_ScreenDiffuse;
3937 CGparameter fp_Texture_ScreenSpecular;
3938 CGparameter fp_Texture_ReflectMask;
3939 CGparameter fp_Texture_ReflectCube;
3940 CGparameter fp_Alpha;
3941 CGparameter fp_BloomBlur_Parameters;
3942 CGparameter fp_ClientTime;
3943 CGparameter fp_Color_Ambient;
3944 CGparameter fp_Color_Diffuse;
3945 CGparameter fp_Color_Specular;
3946 CGparameter fp_Color_Glow;
3947 CGparameter fp_Color_Pants;
3948 CGparameter fp_Color_Shirt;
3949 CGparameter fp_DeferredColor_Ambient;
3950 CGparameter fp_DeferredColor_Diffuse;
3951 CGparameter fp_DeferredColor_Specular;
3952 CGparameter fp_DeferredMod_Diffuse;
3953 CGparameter fp_DeferredMod_Specular;
3954 CGparameter fp_DistortScaleRefractReflect;
3955 CGparameter fp_EyePosition;
3956 CGparameter fp_FogColor;
3957 CGparameter fp_FogHeightFade;
3958 CGparameter fp_FogPlane;
3959 CGparameter fp_FogPlaneViewDist;
3960 CGparameter fp_FogRangeRecip;
3961 CGparameter fp_LightColor;
3962 CGparameter fp_LightDir;
3963 CGparameter fp_LightPosition;
3964 CGparameter fp_OffsetMapping_Scale;
3965 CGparameter fp_PixelSize;
3966 CGparameter fp_ReflectColor;
3967 CGparameter fp_ReflectFactor;
3968 CGparameter fp_ReflectOffset;
3969 CGparameter fp_RefractColor;
3970 CGparameter fp_Saturation;
3971 CGparameter fp_ScreenCenterRefractReflect;
3972 CGparameter fp_ScreenScaleRefractReflect;
3973 CGparameter fp_ScreenToDepth;
3974 CGparameter fp_ShadowMap_Parameters;
3975 CGparameter fp_ShadowMap_TextureScale;
3976 CGparameter fp_SpecularPower;
3977 CGparameter fp_UserVec1;
3978 CGparameter fp_UserVec2;
3979 CGparameter fp_UserVec3;
3980 CGparameter fp_UserVec4;
3981 CGparameter fp_ViewTintColor;
3982 CGparameter fp_ViewToLight;
3983 CGparameter fp_PixelToScreenTexCoord;
3984 CGparameter fp_ModelToReflectCube;
3988 /// information about each possible shader permutation
3989 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3990 /// currently selected permutation
3991 r_cg_permutation_t *r_cg_permutation;
3992 /// storage for permutations linked in the hash table
3993 memexpandablearray_t r_cg_permutationarray;
3995 #define CHECKCGERROR {CGerror err = cgGetError(), err2 = err;if (err){Con_Printf("%s:%i CG error %i: %s : %s\n", __FILE__, __LINE__, err, cgGetErrorString(err), cgGetLastErrorString(&err2));if (err == 1) Con_Printf("last listing:\n%s\n", cgGetLastListing(vid.cgcontext));}}
3997 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
3999 //unsigned int hashdepth = 0;
4000 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4001 r_cg_permutation_t *p;
4002 for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4004 if (p->mode == mode && p->permutation == permutation)
4006 //if (hashdepth > 10)
4007 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4012 p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4014 p->permutation = permutation;
4015 p->hashnext = r_cg_permutationhash[mode][hashindex];
4016 r_cg_permutationhash[mode][hashindex] = p;
4017 //if (hashdepth > 10)
4018 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4022 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4025 if (!filename || !filename[0])
4027 if (!strcmp(filename, "cg/default.cg"))
4029 if (!cgshaderstring)
4031 cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4033 Con_DPrintf("Loading shaders from file %s...\n", filename);
4035 cgshaderstring = (char *)builtincgshaderstring;
4037 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4038 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4039 return shaderstring;
4041 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4044 if (printfromdisknotice)
4045 Con_DPrintf("from disk %s... ", filename);
4046 return shaderstring;
4048 return shaderstring;
4051 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4053 // TODO: load or create .fp and .vp shader files
4056 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4059 shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4060 int vertstrings_count = 0, vertstring_length = 0;
4061 int geomstrings_count = 0, geomstring_length = 0;
4062 int fragstrings_count = 0, fragstring_length = 0;
4064 char *vertexstring, *geometrystring, *fragmentstring;
4065 char *vertstring, *geomstring, *fragstring;
4066 const char *vertstrings_list[32+3];
4067 const char *geomstrings_list[32+3];
4068 const char *fragstrings_list[32+3];
4069 char permutationname[256];
4070 char cachename[256];
4071 CGprofile vertexProfile;
4072 CGprofile fragmentProfile;
4080 permutationname[0] = 0;
4082 vertexstring = R_CG_GetText(modeinfo->vertexfilename, true);
4083 geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4084 fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4086 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4087 strlcat(cachename, "cg/", sizeof(cachename));
4089 // the first pretext is which type of shader to compile as
4090 // (later these will all be bound together as a program object)
4091 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4092 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4093 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4095 // the second pretext is the mode (for example a light source)
4096 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4097 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4098 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4099 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4100 strlcat(cachename, modeinfo->name, sizeof(cachename));
4102 // now add all the permutation pretexts
4103 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4105 if (permutation & (1<<i))
4107 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4108 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4109 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4110 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4111 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4115 // keep line numbers correct
4116 vertstrings_list[vertstrings_count++] = "\n";
4117 geomstrings_list[geomstrings_count++] = "\n";
4118 fragstrings_list[fragstrings_count++] = "\n";
4122 // replace spaces in the cachename with _ characters
4123 for (i = 0;cachename[i];i++)
4124 if (cachename[i] == ' ')
4127 // now append the shader text itself
4128 vertstrings_list[vertstrings_count++] = vertexstring;
4129 geomstrings_list[geomstrings_count++] = geometrystring;
4130 fragstrings_list[fragstrings_count++] = fragmentstring;
4132 // if any sources were NULL, clear the respective list
4134 vertstrings_count = 0;
4135 if (!geometrystring)
4136 geomstrings_count = 0;
4137 if (!fragmentstring)
4138 fragstrings_count = 0;
4140 vertstring_length = 0;
4141 for (i = 0;i < vertstrings_count;i++)
4142 vertstring_length += strlen(vertstrings_list[i]);
4143 vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4144 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4145 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4147 geomstring_length = 0;
4148 for (i = 0;i < geomstrings_count;i++)
4149 geomstring_length += strlen(geomstrings_list[i]);
4150 geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4151 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4152 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4154 fragstring_length = 0;
4155 for (i = 0;i < fragstrings_count;i++)
4156 fragstring_length += strlen(fragstrings_list[i]);
4157 fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4158 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4159 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4163 //vertexProfile = CG_PROFILE_ARBVP1;
4164 //fragmentProfile = CG_PROFILE_ARBFP1;
4165 vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4166 fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4167 //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4168 //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4169 //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4172 // try to load the cached shader, or generate one
4173 R_CG_CacheShader(p, cachename, vertstring, fragstring);
4175 // if caching failed, do a dynamic compile for now
4177 if (vertstring[0] && !p->vprogram)
4178 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4180 if (fragstring[0] && !p->fprogram)
4181 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4184 // look up all the uniform variable names we care about, so we don't
4185 // have to look them up every time we set them
4189 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4190 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4191 p->vp_EyePosition = cgGetNamedParameter(p->vprogram, "EyePosition");
4192 p->vp_FogPlane = cgGetNamedParameter(p->vprogram, "FogPlane");
4193 p->vp_LightDir = cgGetNamedParameter(p->vprogram, "LightDir");
4194 p->vp_LightPosition = cgGetNamedParameter(p->vprogram, "LightPosition");
4195 p->vp_ModelToLight = cgGetNamedParameter(p->vprogram, "ModelToLight");
4196 p->vp_TexMatrix = cgGetNamedParameter(p->vprogram, "TexMatrix");
4197 p->vp_BackgroundTexMatrix = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4198 p->vp_ModelViewProjectionMatrix = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4199 p->vp_ModelViewMatrix = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4200 p->vp_ShadowMapMatrix = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4206 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4207 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4208 p->fp_Texture_First = cgGetNamedParameter(p->fprogram, "Texture_First");
4209 p->fp_Texture_Second = cgGetNamedParameter(p->fprogram, "Texture_Second");
4210 p->fp_Texture_GammaRamps = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4211 p->fp_Texture_Normal = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4212 p->fp_Texture_Color = cgGetNamedParameter(p->fprogram, "Texture_Color");
4213 p->fp_Texture_Gloss = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4214 p->fp_Texture_Glow = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4215 p->fp_Texture_SecondaryNormal = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4216 p->fp_Texture_SecondaryColor = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4217 p->fp_Texture_SecondaryGloss = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4218 p->fp_Texture_SecondaryGlow = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4219 p->fp_Texture_Pants = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4220 p->fp_Texture_Shirt = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4221 p->fp_Texture_FogHeightTexture = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4222 p->fp_Texture_FogMask = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4223 p->fp_Texture_Lightmap = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4224 p->fp_Texture_Deluxemap = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4225 p->fp_Texture_Attenuation = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4226 p->fp_Texture_Cube = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4227 p->fp_Texture_Refraction = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4228 p->fp_Texture_Reflection = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4229 p->fp_Texture_ShadowMapRect = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4230 p->fp_Texture_ShadowMapCube = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4231 p->fp_Texture_ShadowMap2D = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4232 p->fp_Texture_CubeProjection = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4233 p->fp_Texture_ScreenDepth = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4234 p->fp_Texture_ScreenNormalMap = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4235 p->fp_Texture_ScreenDiffuse = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4236 p->fp_Texture_ScreenSpecular = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4237 p->fp_Texture_ReflectMask = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4238 p->fp_Texture_ReflectCube = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4239 p->fp_Alpha = cgGetNamedParameter(p->fprogram, "Alpha");
4240 p->fp_BloomBlur_Parameters = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4241 p->fp_ClientTime = cgGetNamedParameter(p->fprogram, "ClientTime");
4242 p->fp_Color_Ambient = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4243 p->fp_Color_Diffuse = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4244 p->fp_Color_Specular = cgGetNamedParameter(p->fprogram, "Color_Specular");
4245 p->fp_Color_Glow = cgGetNamedParameter(p->fprogram, "Color_Glow");
4246 p->fp_Color_Pants = cgGetNamedParameter(p->fprogram, "Color_Pants");
4247 p->fp_Color_Shirt = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4248 p->fp_DeferredColor_Ambient = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4249 p->fp_DeferredColor_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4250 p->fp_DeferredColor_Specular = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4251 p->fp_DeferredMod_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4252 p->fp_DeferredMod_Specular = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4253 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4254 p->fp_EyePosition = cgGetNamedParameter(p->fprogram, "EyePosition");
4255 p->fp_FogColor = cgGetNamedParameter(p->fprogram, "FogColor");
4256 p->fp_FogHeightFade = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4257 p->fp_FogPlane = cgGetNamedParameter(p->fprogram, "FogPlane");
4258 p->fp_FogPlaneViewDist = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4259 p->fp_FogRangeRecip = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4260 p->fp_LightColor = cgGetNamedParameter(p->fprogram, "LightColor");
4261 p->fp_LightDir = cgGetNamedParameter(p->fprogram, "LightDir");
4262 p->fp_LightPosition = cgGetNamedParameter(p->fprogram, "LightPosition");
4263 p->fp_OffsetMapping_Scale = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4264 p->fp_PixelSize = cgGetNamedParameter(p->fprogram, "PixelSize");
4265 p->fp_ReflectColor = cgGetNamedParameter(p->fprogram, "ReflectColor");
4266 p->fp_ReflectFactor = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4267 p->fp_ReflectOffset = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4268 p->fp_RefractColor = cgGetNamedParameter(p->fprogram, "RefractColor");
4269 p->fp_Saturation = cgGetNamedParameter(p->fprogram, "Saturation");
4270 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4271 p->fp_ScreenScaleRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4272 p->fp_ScreenToDepth = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4273 p->fp_ShadowMap_Parameters = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4274 p->fp_ShadowMap_TextureScale = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4275 p->fp_SpecularPower = cgGetNamedParameter(p->fprogram, "SpecularPower");
4276 p->fp_UserVec1 = cgGetNamedParameter(p->fprogram, "UserVec1");
4277 p->fp_UserVec2 = cgGetNamedParameter(p->fprogram, "UserVec2");
4278 p->fp_UserVec3 = cgGetNamedParameter(p->fprogram, "UserVec3");
4279 p->fp_UserVec4 = cgGetNamedParameter(p->fprogram, "UserVec4");
4280 p->fp_ViewTintColor = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4281 p->fp_ViewToLight = cgGetNamedParameter(p->fprogram, "ViewToLight");
4282 p->fp_PixelToScreenTexCoord = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4283 p->fp_ModelToReflectCube = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4287 if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4288 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4290 Con_Printf("^1CG shader %s failed! some features may not work properly.\n", permutationname);
4294 Mem_Free(vertstring);
4296 Mem_Free(geomstring);
4298 Mem_Free(fragstring);
4300 Mem_Free(vertexstring);
4302 Mem_Free(geometrystring);
4304 Mem_Free(fragmentstring);
4307 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4309 r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4312 if (r_cg_permutation != perm)
4314 r_cg_permutation = perm;
4315 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4317 if (!r_cg_permutation->compiled)
4318 R_CG_CompilePermutation(perm, mode, permutation);
4319 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4321 // remove features until we find a valid permutation
4323 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4325 // reduce i more quickly whenever it would not remove any bits
4326 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4327 if (!(permutation & j))
4330 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4331 if (!r_cg_permutation->compiled)
4332 R_CG_CompilePermutation(perm, mode, permutation);
4333 if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4336 if (i >= SHADERPERMUTATION_COUNT)
4338 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4339 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4340 return; // no bit left to clear, entire mode is broken
4346 if (r_cg_permutation->vprogram)
4348 cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4349 cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4350 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4354 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4355 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4357 if (r_cg_permutation->fprogram)
4359 cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4360 cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4361 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4365 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4366 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4370 if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4371 if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4372 if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4375 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4377 cgGLSetTextureParameter(param, R_GetTexture(tex));
4378 cgGLEnableTextureParameter(param);
4382 void R_GLSL_Restart_f(void)
4384 unsigned int i, limit;
4385 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4386 Mem_Free(glslshaderstring);
4387 glslshaderstring = NULL;
4388 if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4389 Mem_Free(cgshaderstring);
4390 cgshaderstring = NULL;
4391 switch(vid.renderpath)
4393 case RENDERPATH_GL20:
4395 r_glsl_permutation_t *p;
4396 r_glsl_permutation = NULL;
4397 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4398 for (i = 0;i < limit;i++)
4400 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4402 GL_Backend_FreeProgram(p->program);
4403 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4406 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4409 case RENDERPATH_CGGL:
4412 r_cg_permutation_t *p;
4413 r_cg_permutation = NULL;
4414 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4415 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4416 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4417 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4418 limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4419 for (i = 0;i < limit;i++)
4421 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4424 cgDestroyProgram(p->vprogram);
4426 cgDestroyProgram(p->fprogram);
4427 Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4430 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4434 case RENDERPATH_GL13:
4435 case RENDERPATH_GL11:
4440 void R_GLSL_DumpShader_f(void)
4445 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4448 FS_Print(file, "/* The engine may define the following macros:\n");
4449 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4450 for (i = 0;i < SHADERMODE_COUNT;i++)
4451 FS_Print(file, glslshadermodeinfo[i].pretext);
4452 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4453 FS_Print(file, shaderpermutationinfo[i].pretext);
4454 FS_Print(file, "*/\n");
4455 FS_Print(file, builtinshaderstring);
4457 Con_Printf("glsl/default.glsl written\n");
4460 Con_Printf("failed to write to glsl/default.glsl\n");
4463 file = FS_OpenRealFile("cg/default.cg", "w", false);
4466 FS_Print(file, "/* The engine may define the following macros:\n");
4467 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4468 for (i = 0;i < SHADERMODE_COUNT;i++)
4469 FS_Print(file, cgshadermodeinfo[i].pretext);
4470 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4471 FS_Print(file, shaderpermutationinfo[i].pretext);
4472 FS_Print(file, "*/\n");
4473 FS_Print(file, builtincgshaderstring);
4475 Con_Printf("cg/default.cg written\n");
4478 Con_Printf("failed to write to cg/default.cg\n");
4482 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4485 texturemode = GL_MODULATE;
4486 switch (vid.renderpath)
4488 case RENDERPATH_GL20:
4489 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4490 if (r_glsl_permutation->loc_Texture_First ) R_Mesh_TexBind(GL20TU_FIRST , first );
4491 if (r_glsl_permutation->loc_Texture_Second) R_Mesh_TexBind(GL20TU_SECOND, second);
4493 case RENDERPATH_CGGL:
4496 R_SetupShader_SetPermutationCG(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4497 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
4498 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
4501 case RENDERPATH_GL13:
4502 R_Mesh_TexBind(0, first );
4503 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4504 R_Mesh_TexBind(1, second);
4506 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4508 case RENDERPATH_GL11:
4509 R_Mesh_TexBind(0, first );
4514 void R_SetupShader_DepthOrShadow(void)
4516 switch (vid.renderpath)
4518 case RENDERPATH_GL20:
4519 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4521 case RENDERPATH_CGGL:
4523 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
4526 case RENDERPATH_GL13:
4527 R_Mesh_TexBind(0, 0);
4528 R_Mesh_TexBind(1, 0);
4530 case RENDERPATH_GL11:
4531 R_Mesh_TexBind(0, 0);
4536 void R_SetupShader_ShowDepth(void)
4538 switch (vid.renderpath)
4540 case RENDERPATH_GL20:
4541 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4543 case RENDERPATH_CGGL:
4545 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
4548 case RENDERPATH_GL13:
4550 case RENDERPATH_GL11:
4555 extern qboolean r_shadow_usingdeferredprepass;
4556 extern cvar_t r_shadow_deferred_8bitrange;
4557 extern rtexture_t *r_shadow_attenuationgradienttexture;
4558 extern rtexture_t *r_shadow_attenuation2dtexture;
4559 extern rtexture_t *r_shadow_attenuation3dtexture;
4560 extern qboolean r_shadow_usingshadowmaprect;
4561 extern qboolean r_shadow_usingshadowmapcube;
4562 extern qboolean r_shadow_usingshadowmap2d;
4563 extern qboolean r_shadow_usingshadowmaportho;
4564 extern float r_shadow_shadowmap_texturescale[2];
4565 extern float r_shadow_shadowmap_parameters[4];
4566 extern qboolean r_shadow_shadowmapvsdct;
4567 extern qboolean r_shadow_shadowmapsampler;
4568 extern int r_shadow_shadowmappcf;
4569 extern rtexture_t *r_shadow_shadowmaprectangletexture;
4570 extern rtexture_t *r_shadow_shadowmap2dtexture;
4571 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
4572 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4573 extern matrix4x4_t r_shadow_shadowmapmatrix;
4574 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4575 extern int r_shadow_prepass_width;
4576 extern int r_shadow_prepass_height;
4577 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4578 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4579 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4580 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4581 extern cvar_t gl_mesh_separatearrays;
4582 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)
4584 // select a permutation of the lighting shader appropriate to this
4585 // combination of texture, entity, light source, and fogging, only use the
4586 // minimum features necessary to avoid wasting rendering time in the
4587 // fragment shader on features that are not being used
4588 unsigned int permutation = 0;
4589 unsigned int mode = 0;
4591 if (rsurfacepass == RSURFPASS_BACKGROUND)
4593 // distorted background
4594 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4595 mode = SHADERMODE_WATER;
4596 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4597 mode = SHADERMODE_REFRACTION;
4600 mode = SHADERMODE_GENERIC;
4601 permutation |= SHADERPERMUTATION_DIFFUSE;
4603 GL_AlphaTest(false);
4604 GL_BlendFunc(GL_ONE, GL_ZERO);
4606 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4608 if (r_glsl_offsetmapping.integer)
4610 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4611 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4612 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4613 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4614 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4616 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4617 if (r_glsl_offsetmapping_reliefmapping.integer)
4618 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4621 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4622 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4623 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4624 permutation |= SHADERPERMUTATION_ALPHAKILL;
4625 // normalmap (deferred prepass), may use alpha test on diffuse
4626 mode = SHADERMODE_DEFERREDGEOMETRY;
4627 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4628 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4629 GL_AlphaTest(false);
4630 GL_BlendFunc(GL_ONE, GL_ZERO);
4632 else if (rsurfacepass == RSURFPASS_RTLIGHT)
4634 if (r_glsl_offsetmapping.integer)
4636 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4637 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4638 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4639 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4640 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4642 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4643 if (r_glsl_offsetmapping_reliefmapping.integer)
4644 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4647 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4648 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4650 mode = SHADERMODE_LIGHTSOURCE;
4651 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4652 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4653 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4654 permutation |= SHADERPERMUTATION_CUBEFILTER;
4655 if (diffusescale > 0)
4656 permutation |= SHADERPERMUTATION_DIFFUSE;
4657 if (specularscale > 0)
4659 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4660 if (r_shadow_glossexact.integer)
4661 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4663 if (r_refdef.fogenabled)
4664 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4665 if (rsurface.texture->colormapping)
4666 permutation |= SHADERPERMUTATION_COLORMAPPING;
4667 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
4669 if (r_shadow_usingshadowmaprect)
4670 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4671 if (r_shadow_usingshadowmap2d)
4672 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4673 if (r_shadow_usingshadowmapcube)
4674 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
4675 else if(r_shadow_shadowmapvsdct)
4676 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
4678 if (r_shadow_shadowmapsampler)
4679 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4680 if (r_shadow_shadowmappcf > 1)
4681 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4682 else if (r_shadow_shadowmappcf)
4683 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4685 if (rsurface.texture->reflectmasktexture)
4686 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4687 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4688 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
4690 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4692 if (r_glsl_offsetmapping.integer)
4694 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4695 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4696 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4697 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4698 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4700 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4701 if (r_glsl_offsetmapping_reliefmapping.integer)
4702 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4705 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4706 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4707 // unshaded geometry (fullbright or ambient model lighting)
4708 mode = SHADERMODE_FLATCOLOR;
4709 ambientscale = diffusescale = specularscale = 0;
4710 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4711 permutation |= SHADERPERMUTATION_GLOW;
4712 if (r_refdef.fogenabled)
4713 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4714 if (rsurface.texture->colormapping)
4715 permutation |= SHADERPERMUTATION_COLORMAPPING;
4716 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4718 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4719 if (r_shadow_usingshadowmaprect)
4720 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4721 if (r_shadow_usingshadowmap2d)
4722 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4724 if (r_shadow_shadowmapsampler)
4725 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4726 if (r_shadow_shadowmappcf > 1)
4727 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4728 else if (r_shadow_shadowmappcf)
4729 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4731 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4732 permutation |= SHADERPERMUTATION_REFLECTION;
4733 if (rsurface.texture->reflectmasktexture)
4734 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4735 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4736 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4738 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
4740 if (r_glsl_offsetmapping.integer)
4742 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4743 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4744 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4745 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4746 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4748 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4749 if (r_glsl_offsetmapping_reliefmapping.integer)
4750 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4753 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4754 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4755 // directional model lighting
4756 mode = SHADERMODE_LIGHTDIRECTION;
4757 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4758 permutation |= SHADERPERMUTATION_GLOW;
4759 permutation |= SHADERPERMUTATION_DIFFUSE;
4760 if (specularscale > 0)
4762 permutation |= SHADERPERMUTATION_SPECULAR;
4763 if (r_shadow_glossexact.integer)
4764 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4766 if (r_refdef.fogenabled)
4767 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4768 if (rsurface.texture->colormapping)
4769 permutation |= SHADERPERMUTATION_COLORMAPPING;
4770 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4772 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4773 if (r_shadow_usingshadowmaprect)
4774 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4775 if (r_shadow_usingshadowmap2d)
4776 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4778 if (r_shadow_shadowmapsampler)
4779 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4780 if (r_shadow_shadowmappcf > 1)
4781 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4782 else if (r_shadow_shadowmappcf)
4783 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4785 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4786 permutation |= SHADERPERMUTATION_REFLECTION;
4787 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4788 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4789 if (rsurface.texture->reflectmasktexture)
4790 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4791 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4792 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4794 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
4796 if (r_glsl_offsetmapping.integer)
4798 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4799 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4800 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4801 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4802 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4804 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4805 if (r_glsl_offsetmapping_reliefmapping.integer)
4806 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4809 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4810 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4811 // ambient model lighting
4812 mode = SHADERMODE_LIGHTDIRECTION;
4813 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4814 permutation |= SHADERPERMUTATION_GLOW;
4815 if (r_refdef.fogenabled)
4816 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4817 if (rsurface.texture->colormapping)
4818 permutation |= SHADERPERMUTATION_COLORMAPPING;
4819 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4821 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4822 if (r_shadow_usingshadowmaprect)
4823 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4824 if (r_shadow_usingshadowmap2d)
4825 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4827 if (r_shadow_shadowmapsampler)
4828 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4829 if (r_shadow_shadowmappcf > 1)
4830 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4831 else if (r_shadow_shadowmappcf)
4832 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4834 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4835 permutation |= SHADERPERMUTATION_REFLECTION;
4836 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4837 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4838 if (rsurface.texture->reflectmasktexture)
4839 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4840 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4841 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4845 if (r_glsl_offsetmapping.integer)
4847 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4848 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4849 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4850 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4851 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4853 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4854 if (r_glsl_offsetmapping_reliefmapping.integer)
4855 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4858 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4859 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4861 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4862 permutation |= SHADERPERMUTATION_GLOW;
4863 if (r_refdef.fogenabled)
4864 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4865 if (rsurface.texture->colormapping)
4866 permutation |= SHADERPERMUTATION_COLORMAPPING;
4867 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4869 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4870 if (r_shadow_usingshadowmaprect)
4871 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4872 if (r_shadow_usingshadowmap2d)
4873 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4875 if (r_shadow_shadowmapsampler)
4876 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4877 if (r_shadow_shadowmappcf > 1)
4878 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4879 else if (r_shadow_shadowmappcf)
4880 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4882 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4883 permutation |= SHADERPERMUTATION_REFLECTION;
4884 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4885 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4886 if (rsurface.texture->reflectmasktexture)
4887 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4888 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
4890 // deluxemapping (light direction texture)
4891 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
4892 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
4894 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
4895 permutation |= SHADERPERMUTATION_DIFFUSE;
4896 if (specularscale > 0)
4898 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4899 if (r_shadow_glossexact.integer)
4900 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4903 else if (r_glsl_deluxemapping.integer >= 2)
4905 // fake deluxemapping (uniform light direction in tangentspace)
4906 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
4907 permutation |= SHADERPERMUTATION_DIFFUSE;
4908 if (specularscale > 0)
4910 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4911 if (r_shadow_glossexact.integer)
4912 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4915 else if (rsurface.uselightmaptexture)
4917 // ordinary lightmapping (q1bsp, q3bsp)
4918 mode = SHADERMODE_LIGHTMAP;
4922 // ordinary vertex coloring (q3bsp)
4923 mode = SHADERMODE_VERTEXCOLOR;
4925 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4926 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4928 switch(vid.renderpath)
4930 case RENDERPATH_GL20:
4931 if (gl_mesh_separatearrays.integer)
4933 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
4934 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
4935 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
4936 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
4937 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
4938 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
4939 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
4940 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
4944 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
4945 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
4947 R_SetupShader_SetPermutationGLSL(mode, permutation);
4948 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
4949 if (mode == SHADERMODE_LIGHTSOURCE)
4951 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
4952 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
4953 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
4954 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);
4955 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);
4956 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
4958 // additive passes are only darkened by fog, not tinted
4959 if (r_glsl_permutation->loc_FogColor >= 0)
4960 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
4961 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
4965 if (mode == SHADERMODE_FLATCOLOR)
4967 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
4969 else if (mode == SHADERMODE_LIGHTDIRECTION)
4971 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);
4972 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);
4973 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
4974 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);
4975 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
4976 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
4977 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
4981 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);
4982 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
4983 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
4984 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
4985 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
4987 // additive passes are only darkened by fog, not tinted
4988 if (r_glsl_permutation->loc_FogColor >= 0)
4990 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
4991 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
4993 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
4995 if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
4996 if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
4997 if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4fARB(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
4998 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
4999 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
5000 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5001 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5002 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5004 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5005 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5006 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5007 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5008 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5010 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5011 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3]);
5012 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5013 if (r_glsl_permutation->loc_Color_Pants >= 0)
5015 if (rsurface.texture->pantstexture)
5016 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5018 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5020 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5022 if (rsurface.texture->shirttexture)
5023 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5025 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5027 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4fARB(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5028 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5029 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5030 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5031 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5032 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2fARB(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5033 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5035 // if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_texture_white );
5036 // if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_texture_white );
5037 // if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS , r_texture_gammaramps );
5038 if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5039 if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5040 if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5041 if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5042 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5043 if (r_glsl_permutation->loc_Texture_SecondaryColor >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5044 if (r_glsl_permutation->loc_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5045 if (r_glsl_permutation->loc_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5046 if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5047 if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5048 if (r_glsl_permutation->loc_Texture_ReflectMask >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5049 if (r_glsl_permutation->loc_Texture_ReflectCube >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5050 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5051 if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5052 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , r_texture_white );
5053 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , r_texture_blanknormalmap );
5054 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5055 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION , r_texture_white );
5056 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION , r_texture_white );
5057 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5058 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5059 if (r_glsl_permutation->loc_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5060 if (r_glsl_permutation->loc_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5061 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5063 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture );
5064 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture );
5065 if (rsurface.rtlight)
5067 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5068 if (r_shadow_usingshadowmapcube)
5069 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5070 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5075 case RENDERPATH_CGGL:
5077 if (gl_mesh_separatearrays.integer)
5079 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5080 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5081 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5082 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5083 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5084 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5085 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5086 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5090 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5091 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5093 R_SetupShader_SetPermutationCG(mode, permutation);
5094 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5095 if (mode == SHADERMODE_LIGHTSOURCE)
5097 if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5098 if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5102 if (mode == SHADERMODE_LIGHTDIRECTION)
5104 if (r_cg_permutation->vp_LightDir) cgGLSetParameter3f(r_cg_permutation->vp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5107 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5108 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5109 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5110 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5111 if (r_cg_permutation->vp_FogPlane) cgGLSetParameter4f(r_cg_permutation->vp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5114 if (mode == SHADERMODE_LIGHTSOURCE)
5116 if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5117 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5118 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);CHECKCGERROR
5119 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);CHECKCGERROR
5120 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);CHECKCGERROR
5122 // additive passes are only darkened by fog, not tinted
5123 if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5124 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5128 if (mode == SHADERMODE_FLATCOLOR)
5130 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);CHECKCGERROR
5132 else if (mode == SHADERMODE_LIGHTDIRECTION)
5134 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);CHECKCGERROR
5135 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);CHECKCGERROR
5136 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5137 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5138 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5139 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);CHECKCGERROR
5140 if (r_cg_permutation->fp_LightDir) cgGLSetParameter3f(r_cg_permutation->fp_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);CHECKCGERROR
5144 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);CHECKCGERROR
5145 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);CHECKCGERROR
5146 if (r_cg_permutation->fp_Color_Specular) cgGLSetParameter3f(r_cg_permutation->fp_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);CHECKCGERROR
5147 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5148 if (r_cg_permutation->fp_DeferredMod_Specular) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5150 // additive passes are only darkened by fog, not tinted
5151 if (r_cg_permutation->fp_FogColor)
5153 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5154 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5156 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5159 if (r_cg_permutation->fp_DistortScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);CHECKCGERROR
5160 if (r_cg_permutation->fp_ScreenScaleRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);CHECKCGERROR
5161 if (r_cg_permutation->fp_ScreenCenterRefractReflect) cgGLSetParameter4f(r_cg_permutation->fp_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);CHECKCGERROR
5162 if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f);CHECKCGERROR
5163 if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f);CHECKCGERROR
5164 if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5165 if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5166 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5168 if (r_cg_permutation->fp_ShadowMap_TextureScale) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5169 if (r_cg_permutation->fp_ShadowMap_Parameters) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5170 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5171 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5172 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5173 if (r_cg_permutation->fp_Color_Pants)
5175 if (rsurface.texture->pantstexture)
5176 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5178 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5181 if (r_cg_permutation->fp_Color_Shirt)
5183 if (rsurface.texture->shirttexture)
5184 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5186 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5189 if (r_cg_permutation->fp_FogPlane) cgGLSetParameter4f(r_cg_permutation->fp_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);CHECKCGERROR
5190 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
5191 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
5192 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
5193 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
5194 if (r_cg_permutation->fp_ScreenToDepth) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
5195 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5197 // if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_texture_white );CHECKCGERROR
5198 // if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_texture_white );CHECKCGERROR
5199 // if (r_cg_permutation->fp_Texture_GammaRamps ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps , r_texture_gammaramps );CHECKCGERROR
5200 if (r_cg_permutation->fp_Texture_Normal ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal , rsurface.texture->nmaptexture );CHECKCGERROR
5201 if (r_cg_permutation->fp_Texture_Color ) CG_BindTexture(r_cg_permutation->fp_Texture_Color , rsurface.texture->basetexture );CHECKCGERROR
5202 if (r_cg_permutation->fp_Texture_Gloss ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss , rsurface.texture->glosstexture );CHECKCGERROR
5203 if (r_cg_permutation->fp_Texture_Glow ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow , rsurface.texture->glowtexture );CHECKCGERROR
5204 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture );CHECKCGERROR
5205 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );CHECKCGERROR
5206 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );CHECKCGERROR
5207 if (r_cg_permutation->fp_Texture_SecondaryGlow ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );CHECKCGERROR
5208 if (r_cg_permutation->fp_Texture_Pants ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants , rsurface.texture->pantstexture );CHECKCGERROR
5209 if (r_cg_permutation->fp_Texture_Shirt ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt , rsurface.texture->shirttexture );CHECKCGERROR
5210 if (r_cg_permutation->fp_Texture_ReflectMask ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask , rsurface.texture->reflectmasktexture );CHECKCGERROR
5211 if (r_cg_permutation->fp_Texture_ReflectCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectCube , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);CHECKCGERROR
5212 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture );CHECKCGERROR
5213 if (r_cg_permutation->fp_Texture_FogMask ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask , r_texture_fogattenuation );CHECKCGERROR
5214 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , r_texture_white );CHECKCGERROR
5215 if (r_cg_permutation->fp_Texture_Deluxemap ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap , r_texture_blanknormalmap );CHECKCGERROR
5216 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5217 if (r_cg_permutation->fp_Texture_Refraction ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction , r_texture_white );CHECKCGERROR
5218 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , r_texture_white );CHECKCGERROR
5219 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5220 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5221 if (r_cg_permutation->fp_Texture_ScreenDiffuse ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );CHECKCGERROR
5222 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );CHECKCGERROR
5223 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5225 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5226 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5227 if (rsurface.rtlight)
5229 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5230 if (r_shadow_usingshadowmapcube)
5231 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5232 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5239 case RENDERPATH_GL13:
5240 case RENDERPATH_GL11:
5245 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5247 // select a permutation of the lighting shader appropriate to this
5248 // combination of texture, entity, light source, and fogging, only use the
5249 // minimum features necessary to avoid wasting rendering time in the
5250 // fragment shader on features that are not being used
5251 unsigned int permutation = 0;
5252 unsigned int mode = 0;
5253 const float *lightcolorbase = rtlight->currentcolor;
5254 float ambientscale = rtlight->ambientscale;
5255 float diffusescale = rtlight->diffusescale;
5256 float specularscale = rtlight->specularscale;
5257 // this is the location of the light in view space
5258 vec3_t viewlightorigin;
5259 // this transforms from view space (camera) to light space (cubemap)
5260 matrix4x4_t viewtolight;
5261 matrix4x4_t lighttoview;
5262 float viewtolight16f[16];
5263 float range = 1.0f / r_shadow_deferred_8bitrange.value;
5265 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5266 if (rtlight->currentcubemap != r_texture_whitecube)
5267 permutation |= SHADERPERMUTATION_CUBEFILTER;
5268 if (diffusescale > 0)
5269 permutation |= SHADERPERMUTATION_DIFFUSE;
5270 if (specularscale > 0)
5272 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5273 if (r_shadow_glossexact.integer)
5274 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5276 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5278 if (r_shadow_usingshadowmaprect)
5279 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5280 if (r_shadow_usingshadowmap2d)
5281 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5282 if (r_shadow_usingshadowmapcube)
5283 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5284 else if(r_shadow_shadowmapvsdct)
5285 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5287 if (r_shadow_shadowmapsampler)
5288 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5289 if (r_shadow_shadowmappcf > 1)
5290 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5291 else if (r_shadow_shadowmappcf)
5292 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5294 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5295 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5296 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5297 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5298 switch(vid.renderpath)
5300 case RENDERPATH_GL20:
5301 R_SetupShader_SetPermutationGLSL(mode, permutation);
5302 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5303 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
5304 if (r_glsl_permutation->loc_DeferredColor_Ambient >= 0) qglUniform3fARB( r_glsl_permutation->loc_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
5305 if (r_glsl_permutation->loc_DeferredColor_Diffuse >= 0) qglUniform3fARB( r_glsl_permutation->loc_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
5306 if (r_glsl_permutation->loc_DeferredColor_Specular >= 0) qglUniform3fARB( r_glsl_permutation->loc_DeferredColor_Specular , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5307 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2fARB( r_glsl_permutation->loc_ShadowMap_TextureScale , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5308 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4fARB( r_glsl_permutation->loc_ShadowMap_Parameters , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5309 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB( r_glsl_permutation->loc_SpecularPower , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5310 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2fARB( r_glsl_permutation->loc_ScreenToDepth , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5311 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5313 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5314 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5315 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5316 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5317 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
5318 if (r_shadow_usingshadowmapcube)
5319 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5320 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
5321 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5323 case RENDERPATH_CGGL:
5325 R_SetupShader_SetPermutationCG(mode, permutation);
5326 if (r_cg_permutation->fp_LightPosition ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
5327 if (r_cg_permutation->fp_ViewToLight ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
5328 if (r_cg_permutation->fp_DeferredColor_Ambient ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);CHECKCGERROR
5329 if (r_cg_permutation->fp_DeferredColor_Diffuse ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);CHECKCGERROR
5330 if (r_cg_permutation->fp_DeferredColor_Specular ) cgGLSetParameter3f(r_cg_permutation->fp_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);CHECKCGERROR
5331 if (r_cg_permutation->fp_ShadowMap_TextureScale ) cgGLSetParameter2f(r_cg_permutation->fp_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);CHECKCGERROR
5332 if (r_cg_permutation->fp_ShadowMap_Parameters ) cgGLSetParameter4f(r_cg_permutation->fp_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);CHECKCGERROR
5333 if (r_cg_permutation->fp_SpecularPower ) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5334 if (r_cg_permutation->fp_ScreenToDepth ) cgGLSetParameter2f(r_cg_permutation->fp_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);CHECKCGERROR
5335 if (r_cg_permutation->fp_PixelToScreenTexCoord ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5337 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5338 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5339 if (r_cg_permutation->fp_Texture_ScreenNormalMap ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5340 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5341 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5342 if (r_shadow_usingshadowmapcube)
5343 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5344 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5345 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5348 case RENDERPATH_GL13:
5349 case RENDERPATH_GL11:
5354 #define SKINFRAME_HASH 1024
5358 int loadsequence; // incremented each level change
5359 memexpandablearray_t array;
5360 skinframe_t *hash[SKINFRAME_HASH];
5363 r_skinframe_t r_skinframe;
5365 void R_SkinFrame_PrepareForPurge(void)
5367 r_skinframe.loadsequence++;
5368 // wrap it without hitting zero
5369 if (r_skinframe.loadsequence >= 200)
5370 r_skinframe.loadsequence = 1;
5373 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5377 // mark the skinframe as used for the purging code
5378 skinframe->loadsequence = r_skinframe.loadsequence;
5381 void R_SkinFrame_Purge(void)
5385 for (i = 0;i < SKINFRAME_HASH;i++)
5387 for (s = r_skinframe.hash[i];s;s = s->next)
5389 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5391 if (s->merged == s->base)
5393 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5394 R_PurgeTexture(s->stain );s->stain = NULL;
5395 R_PurgeTexture(s->merged);s->merged = NULL;
5396 R_PurgeTexture(s->base );s->base = NULL;
5397 R_PurgeTexture(s->pants );s->pants = NULL;
5398 R_PurgeTexture(s->shirt );s->shirt = NULL;
5399 R_PurgeTexture(s->nmap );s->nmap = NULL;
5400 R_PurgeTexture(s->gloss );s->gloss = NULL;
5401 R_PurgeTexture(s->glow );s->glow = NULL;
5402 R_PurgeTexture(s->fog );s->fog = NULL;
5403 R_PurgeTexture(s->reflect);s->reflect = NULL;
5404 s->loadsequence = 0;
5410 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5412 char basename[MAX_QPATH];
5414 Image_StripImageExtension(name, basename, sizeof(basename));
5416 if( last == NULL ) {
5418 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5419 item = r_skinframe.hash[hashindex];
5424 // linearly search through the hash bucket
5425 for( ; item ; item = item->next ) {
5426 if( !strcmp( item->basename, basename ) ) {
5433 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5437 char basename[MAX_QPATH];
5439 Image_StripImageExtension(name, basename, sizeof(basename));
5441 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5442 for (item = r_skinframe.hash[hashindex];item;item = item->next)
5443 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5447 rtexture_t *dyntexture;
5448 // check whether its a dynamic texture
5449 dyntexture = CL_GetDynTexture( basename );
5450 if (!add && !dyntexture)
5452 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5453 memset(item, 0, sizeof(*item));
5454 strlcpy(item->basename, basename, sizeof(item->basename));
5455 item->base = dyntexture; // either NULL or dyntexture handle
5456 item->textureflags = textureflags;
5457 item->comparewidth = comparewidth;
5458 item->compareheight = compareheight;
5459 item->comparecrc = comparecrc;
5460 item->next = r_skinframe.hash[hashindex];
5461 r_skinframe.hash[hashindex] = item;
5463 else if( item->base == NULL )
5465 rtexture_t *dyntexture;
5466 // check whether its a dynamic texture
5467 // 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]
5468 dyntexture = CL_GetDynTexture( basename );
5469 item->base = dyntexture; // either NULL or dyntexture handle
5472 R_SkinFrame_MarkUsed(item);
5476 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5478 unsigned long long avgcolor[5], wsum; \
5486 for(pix = 0; pix < cnt; ++pix) \
5489 for(comp = 0; comp < 3; ++comp) \
5491 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5494 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5496 for(comp = 0; comp < 3; ++comp) \
5497 avgcolor[comp] += getpixel * w; \
5500 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5501 avgcolor[4] += getpixel; \
5503 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
5505 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
5506 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
5507 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
5508 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
5511 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
5514 unsigned char *pixels;
5515 unsigned char *bumppixels;
5516 unsigned char *basepixels = NULL;
5517 int basepixels_width = 0;
5518 int basepixels_height = 0;
5519 skinframe_t *skinframe;
5520 rtexture_t *ddsbase = NULL;
5521 qboolean ddshasalpha = false;
5522 float ddsavgcolor[4];
5523 char basename[MAX_QPATH];
5525 if (cls.state == ca_dedicated)
5528 // return an existing skinframe if already loaded
5529 // if loading of the first image fails, don't make a new skinframe as it
5530 // would cause all future lookups of this to be missing
5531 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
5532 if (skinframe && skinframe->base)
5535 Image_StripImageExtension(name, basename, sizeof(basename));
5537 // check for DDS texture file first
5538 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor)))
5540 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer);
5541 if (basepixels == NULL)
5545 if (developer_loading.integer)
5546 Con_Printf("loading skin \"%s\"\n", name);
5548 // we've got some pixels to store, so really allocate this new texture now
5550 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
5551 skinframe->stain = NULL;
5552 skinframe->merged = NULL;
5553 skinframe->base = NULL;
5554 skinframe->pants = NULL;
5555 skinframe->shirt = NULL;
5556 skinframe->nmap = NULL;
5557 skinframe->gloss = NULL;
5558 skinframe->glow = NULL;
5559 skinframe->fog = NULL;
5560 skinframe->reflect = NULL;
5561 skinframe->hasalpha = false;
5565 skinframe->base = ddsbase;
5566 skinframe->hasalpha = ddshasalpha;
5567 VectorCopy(ddsavgcolor, skinframe->avgcolor);
5568 if (r_loadfog && skinframe->hasalpha)
5569 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL);
5570 //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]);
5574 basepixels_width = image_width;
5575 basepixels_height = image_height;
5576 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5577 if (textureflags & TEXF_ALPHA)
5579 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
5581 if (basepixels[j] < 255)
5583 skinframe->hasalpha = true;
5587 if (r_loadfog && skinframe->hasalpha)
5589 // has transparent pixels
5590 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5591 for (j = 0;j < image_width * image_height * 4;j += 4)
5596 pixels[j+3] = basepixels[j+3];
5598 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5602 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
5603 //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]);
5604 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
5605 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true);
5606 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
5607 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true);
5612 if (r_loadnormalmap)
5613 skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL);
5614 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL);
5616 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL);
5617 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL);
5618 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL);
5619 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL);
5622 // _norm is the name used by tenebrae and has been adopted as standard
5623 if (r_loadnormalmap && skinframe->nmap == NULL)
5625 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false)) != NULL)
5627 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5631 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false)) != NULL)
5633 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5634 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
5635 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5637 Mem_Free(bumppixels);
5639 else if (r_shadow_bumpscale_basetexture.value > 0)
5641 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
5642 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
5643 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | skinframe->textureflags) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5646 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
5647 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true);
5650 // _luma is supported only for tenebrae compatibility
5651 // _glow is the preferred name
5652 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer))))
5654 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5655 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
5656 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true);
5657 Mem_Free(pixels);pixels = NULL;
5660 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5662 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5663 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
5664 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true);
5669 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5671 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5672 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
5673 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true);
5678 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5680 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5681 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
5682 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true);
5687 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer)))
5689 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, skinframe->textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), NULL);
5690 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
5691 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true);
5697 Mem_Free(basepixels);
5702 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
5703 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
5706 unsigned char *temp1, *temp2;
5707 skinframe_t *skinframe;
5709 if (cls.state == ca_dedicated)
5712 // if already loaded just return it, otherwise make a new skinframe
5713 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
5714 if (skinframe && skinframe->base)
5717 skinframe->stain = NULL;
5718 skinframe->merged = NULL;
5719 skinframe->base = NULL;
5720 skinframe->pants = NULL;
5721 skinframe->shirt = NULL;
5722 skinframe->nmap = NULL;
5723 skinframe->gloss = NULL;
5724 skinframe->glow = NULL;
5725 skinframe->fog = NULL;
5726 skinframe->reflect = NULL;
5727 skinframe->hasalpha = false;
5729 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5733 if (developer_loading.integer)
5734 Con_Printf("loading 32bit skin \"%s\"\n", name);
5736 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
5738 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5739 temp2 = temp1 + width * height * 4;
5740 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5741 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
5744 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, NULL);
5745 if (textureflags & TEXF_ALPHA)
5747 for (i = 3;i < width * height * 4;i += 4)
5749 if (skindata[i] < 255)
5751 skinframe->hasalpha = true;
5755 if (r_loadfog && skinframe->hasalpha)
5757 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
5758 memcpy(fogpixels, skindata, width * height * 4);
5759 for (i = 0;i < width * height * 4;i += 4)
5760 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
5761 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, NULL);
5762 Mem_Free(fogpixels);
5766 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
5767 //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]);
5772 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
5776 skinframe_t *skinframe;
5778 if (cls.state == ca_dedicated)
5781 // if already loaded just return it, otherwise make a new skinframe
5782 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
5783 if (skinframe && skinframe->base)
5786 skinframe->stain = NULL;
5787 skinframe->merged = NULL;
5788 skinframe->base = NULL;
5789 skinframe->pants = NULL;
5790 skinframe->shirt = NULL;
5791 skinframe->nmap = NULL;
5792 skinframe->gloss = NULL;
5793 skinframe->glow = NULL;
5794 skinframe->fog = NULL;
5795 skinframe->reflect = NULL;
5796 skinframe->hasalpha = false;
5798 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5802 if (developer_loading.integer)
5803 Con_Printf("loading quake skin \"%s\"\n", name);
5805 // 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)
5806 skinframe->qpixels = Mem_Alloc(r_main_mempool, width*height);
5807 memcpy(skinframe->qpixels, skindata, width*height);
5808 skinframe->qwidth = width;
5809 skinframe->qheight = height;
5812 for (i = 0;i < width * height;i++)
5813 featuresmask |= palette_featureflags[skindata[i]];
5815 skinframe->hasalpha = false;
5816 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
5817 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
5818 skinframe->qgeneratemerged = true;
5819 skinframe->qgeneratebase = skinframe->qhascolormapping;
5820 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
5822 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
5823 //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]);
5828 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
5832 unsigned char *skindata;
5834 if (!skinframe->qpixels)
5837 if (!skinframe->qhascolormapping)
5838 colormapped = false;
5842 if (!skinframe->qgeneratebase)
5847 if (!skinframe->qgeneratemerged)
5851 width = skinframe->qwidth;
5852 height = skinframe->qheight;
5853 skindata = skinframe->qpixels;
5855 if (skinframe->qgeneratenmap)
5857 unsigned char *temp1, *temp2;
5858 skinframe->qgeneratenmap = false;
5859 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5860 temp2 = temp1 + width * height * 4;
5861 // use either a custom palette or the quake palette
5862 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
5863 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5864 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, NULL);
5868 if (skinframe->qgenerateglow)
5870 skinframe->qgenerateglow = false;
5871 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette_bgra_onlyfullbrights); // glow
5876 skinframe->qgeneratebase = false;
5877 skinframe->base = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
5878 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette_bgra_pantsaswhite);
5879 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette_bgra_shirtaswhite);
5883 skinframe->qgeneratemerged = false;
5884 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
5887 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
5889 Mem_Free(skinframe->qpixels);
5890 skinframe->qpixels = NULL;
5894 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)
5897 skinframe_t *skinframe;
5899 if (cls.state == ca_dedicated)
5902 // if already loaded just return it, otherwise make a new skinframe
5903 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
5904 if (skinframe && skinframe->base)
5907 skinframe->stain = NULL;
5908 skinframe->merged = NULL;
5909 skinframe->base = NULL;
5910 skinframe->pants = NULL;
5911 skinframe->shirt = NULL;
5912 skinframe->nmap = NULL;
5913 skinframe->gloss = NULL;
5914 skinframe->glow = NULL;
5915 skinframe->fog = NULL;
5916 skinframe->reflect = NULL;
5917 skinframe->hasalpha = false;
5919 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5923 if (developer_loading.integer)
5924 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
5926 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, palette);
5927 if (textureflags & TEXF_ALPHA)
5929 for (i = 0;i < width * height;i++)
5931 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
5933 skinframe->hasalpha = true;
5937 if (r_loadfog && skinframe->hasalpha)
5938 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, alphapalette);
5941 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
5942 //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]);
5947 skinframe_t *R_SkinFrame_LoadMissing(void)
5949 skinframe_t *skinframe;
5951 if (cls.state == ca_dedicated)
5954 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
5955 skinframe->stain = NULL;
5956 skinframe->merged = NULL;
5957 skinframe->base = NULL;
5958 skinframe->pants = NULL;
5959 skinframe->shirt = NULL;
5960 skinframe->nmap = NULL;
5961 skinframe->gloss = NULL;
5962 skinframe->glow = NULL;
5963 skinframe->fog = NULL;
5964 skinframe->reflect = NULL;
5965 skinframe->hasalpha = false;
5967 skinframe->avgcolor[0] = rand() / RAND_MAX;
5968 skinframe->avgcolor[1] = rand() / RAND_MAX;
5969 skinframe->avgcolor[2] = rand() / RAND_MAX;
5970 skinframe->avgcolor[3] = 1;
5975 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
5976 typedef struct suffixinfo_s
5979 qboolean flipx, flipy, flipdiagonal;
5982 static suffixinfo_t suffix[3][6] =
5985 {"px", false, false, false},
5986 {"nx", false, false, false},
5987 {"py", false, false, false},
5988 {"ny", false, false, false},
5989 {"pz", false, false, false},
5990 {"nz", false, false, false}
5993 {"posx", false, false, false},
5994 {"negx", false, false, false},
5995 {"posy", false, false, false},
5996 {"negy", false, false, false},
5997 {"posz", false, false, false},
5998 {"negz", false, false, false}
6001 {"rt", true, false, true},
6002 {"lf", false, true, true},
6003 {"ft", true, true, false},
6004 {"bk", false, false, false},
6005 {"up", true, false, true},
6006 {"dn", true, false, true}
6010 static int componentorder[4] = {0, 1, 2, 3};
6012 rtexture_t *R_LoadCubemap(const char *basename)
6014 int i, j, cubemapsize;
6015 unsigned char *cubemappixels, *image_buffer;
6016 rtexture_t *cubemaptexture;
6018 // must start 0 so the first loadimagepixels has no requested width/height
6020 cubemappixels = NULL;
6021 cubemaptexture = NULL;
6022 // keep trying different suffix groups (posx, px, rt) until one loads
6023 for (j = 0;j < 3 && !cubemappixels;j++)
6025 // load the 6 images in the suffix group
6026 for (i = 0;i < 6;i++)
6028 // generate an image name based on the base and and suffix
6029 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6031 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer)))
6033 // an image loaded, make sure width and height are equal
6034 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6036 // if this is the first image to load successfully, allocate the cubemap memory
6037 if (!cubemappixels && image_width >= 1)
6039 cubemapsize = image_width;
6040 // note this clears to black, so unavailable sides are black
6041 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6043 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6045 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);
6048 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6050 Mem_Free(image_buffer);
6054 // if a cubemap loaded, upload it
6057 if (developer_loading.integer)
6058 Con_Printf("loading cubemap \"%s\"\n", basename);
6060 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR, NULL);
6061 Mem_Free(cubemappixels);
6065 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6066 if (developer_loading.integer)
6068 Con_Printf("(tried tried images ");
6069 for (j = 0;j < 3;j++)
6070 for (i = 0;i < 6;i++)
6071 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6072 Con_Print(" and was unable to find any of them).\n");
6075 return cubemaptexture;
6078 rtexture_t *R_GetCubemap(const char *basename)
6081 for (i = 0;i < r_texture_numcubemaps;i++)
6082 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6083 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6084 if (i >= MAX_CUBEMAPS)
6085 return r_texture_whitecube;
6086 r_texture_numcubemaps++;
6087 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6088 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6089 return r_texture_cubemaps[i].texture;
6092 void R_FreeCubemaps(void)
6095 for (i = 0;i < r_texture_numcubemaps;i++)
6097 if (developer_loading.integer)
6098 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6099 if (r_texture_cubemaps[i].texture)
6100 R_FreeTexture(r_texture_cubemaps[i].texture);
6102 r_texture_numcubemaps = 0;
6105 void R_Main_FreeViewCache(void)
6107 if (r_refdef.viewcache.entityvisible)
6108 Mem_Free(r_refdef.viewcache.entityvisible);
6109 if (r_refdef.viewcache.world_pvsbits)
6110 Mem_Free(r_refdef.viewcache.world_pvsbits);
6111 if (r_refdef.viewcache.world_leafvisible)
6112 Mem_Free(r_refdef.viewcache.world_leafvisible);
6113 if (r_refdef.viewcache.world_surfacevisible)
6114 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6115 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6118 void R_Main_ResizeViewCache(void)
6120 int numentities = r_refdef.scene.numentities;
6121 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6122 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6123 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6124 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6125 if (r_refdef.viewcache.maxentities < numentities)
6127 r_refdef.viewcache.maxentities = numentities;
6128 if (r_refdef.viewcache.entityvisible)
6129 Mem_Free(r_refdef.viewcache.entityvisible);
6130 r_refdef.viewcache.entityvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6132 if (r_refdef.viewcache.world_numclusters != numclusters)
6134 r_refdef.viewcache.world_numclusters = numclusters;
6135 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6136 if (r_refdef.viewcache.world_pvsbits)
6137 Mem_Free(r_refdef.viewcache.world_pvsbits);
6138 r_refdef.viewcache.world_pvsbits = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6140 if (r_refdef.viewcache.world_numleafs != numleafs)
6142 r_refdef.viewcache.world_numleafs = numleafs;
6143 if (r_refdef.viewcache.world_leafvisible)
6144 Mem_Free(r_refdef.viewcache.world_leafvisible);
6145 r_refdef.viewcache.world_leafvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6147 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6149 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6150 if (r_refdef.viewcache.world_surfacevisible)
6151 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6152 r_refdef.viewcache.world_surfacevisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6156 extern rtexture_t *loadingscreentexture;
6157 void gl_main_start(void)
6159 loadingscreentexture = NULL;
6160 r_texture_blanknormalmap = NULL;
6161 r_texture_white = NULL;
6162 r_texture_grey128 = NULL;
6163 r_texture_black = NULL;
6164 r_texture_whitecube = NULL;
6165 r_texture_normalizationcube = NULL;
6166 r_texture_fogattenuation = NULL;
6167 r_texture_fogheighttexture = NULL;
6168 r_texture_gammaramps = NULL;
6169 r_texture_numcubemaps = 0;
6171 r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
6172 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6174 switch(vid.renderpath)
6176 case RENDERPATH_GL20:
6177 case RENDERPATH_CGGL:
6178 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6179 Cvar_SetValueQuick(&gl_combine, 1);
6180 Cvar_SetValueQuick(&r_glsl, 1);
6181 r_loadnormalmap = true;
6185 case RENDERPATH_GL13:
6186 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6187 Cvar_SetValueQuick(&gl_combine, 1);
6188 Cvar_SetValueQuick(&r_glsl, 0);
6189 r_loadnormalmap = false;
6190 r_loadgloss = false;
6193 case RENDERPATH_GL11:
6194 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6195 Cvar_SetValueQuick(&gl_combine, 0);
6196 Cvar_SetValueQuick(&r_glsl, 0);
6197 r_loadnormalmap = false;
6198 r_loadgloss = false;
6204 R_FrameData_Reset();
6208 memset(r_queries, 0, sizeof(r_queries));
6210 r_qwskincache = NULL;
6211 r_qwskincache_size = 0;
6213 // set up r_skinframe loading system for textures
6214 memset(&r_skinframe, 0, sizeof(r_skinframe));
6215 r_skinframe.loadsequence = 1;
6216 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6218 r_main_texturepool = R_AllocTexturePool();
6219 R_BuildBlankTextures();
6221 if (vid.support.arb_texture_cube_map)
6224 R_BuildNormalizationCube();
6226 r_texture_fogattenuation = NULL;
6227 r_texture_fogheighttexture = NULL;
6228 r_texture_gammaramps = NULL;
6229 //r_texture_fogintensity = NULL;
6230 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6231 memset(&r_waterstate, 0, sizeof(r_waterstate));
6232 r_glsl_permutation = NULL;
6233 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6234 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6235 glslshaderstring = NULL;
6237 r_cg_permutation = NULL;
6238 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6239 Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
6240 cgshaderstring = NULL;
6242 memset(&r_svbsp, 0, sizeof (r_svbsp));
6244 r_refdef.fogmasktable_density = 0;
6247 void gl_main_shutdown(void)
6250 R_FrameData_Reset();
6252 R_Main_FreeViewCache();
6255 qglDeleteQueriesARB(r_maxqueries, r_queries);
6259 memset(r_queries, 0, sizeof(r_queries));
6261 r_qwskincache = NULL;
6262 r_qwskincache_size = 0;
6264 // clear out the r_skinframe state
6265 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6266 memset(&r_skinframe, 0, sizeof(r_skinframe));
6269 Mem_Free(r_svbsp.nodes);
6270 memset(&r_svbsp, 0, sizeof (r_svbsp));
6271 R_FreeTexturePool(&r_main_texturepool);
6272 loadingscreentexture = NULL;
6273 r_texture_blanknormalmap = NULL;
6274 r_texture_white = NULL;
6275 r_texture_grey128 = NULL;
6276 r_texture_black = NULL;
6277 r_texture_whitecube = NULL;
6278 r_texture_normalizationcube = NULL;
6279 r_texture_fogattenuation = NULL;
6280 r_texture_fogheighttexture = NULL;
6281 r_texture_gammaramps = NULL;
6282 r_texture_numcubemaps = 0;
6283 //r_texture_fogintensity = NULL;
6284 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6285 memset(&r_waterstate, 0, sizeof(r_waterstate));
6286 r_glsl_permutation = NULL;
6287 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6288 glslshaderstring = NULL;
6290 r_cg_permutation = NULL;
6291 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6292 cgshaderstring = NULL;
6297 extern void CL_ParseEntityLump(char *entitystring);
6298 void gl_main_newmap(void)
6300 // FIXME: move this code to client
6302 char *entities, entname[MAX_QPATH];
6304 Mem_Free(r_qwskincache);
6305 r_qwskincache = NULL;
6306 r_qwskincache_size = 0;
6309 strlcpy(entname, cl.worldmodel->name, sizeof(entname));
6310 l = (int)strlen(entname) - 4;
6311 if (l >= 0 && !strcmp(entname + l, ".bsp"))
6313 memcpy(entname + l, ".ent", 5);
6314 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6316 CL_ParseEntityLump(entities);
6321 if (cl.worldmodel->brush.entities)
6322 CL_ParseEntityLump(cl.worldmodel->brush.entities);
6324 R_Main_FreeViewCache();
6326 R_FrameData_Reset();
6329 void GL_Main_Init(void)
6331 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6333 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6334 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6335 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6336 if (gamemode == GAME_NEHAHRA)
6338 Cvar_RegisterVariable (&gl_fogenable);
6339 Cvar_RegisterVariable (&gl_fogdensity);
6340 Cvar_RegisterVariable (&gl_fogred);
6341 Cvar_RegisterVariable (&gl_foggreen);
6342 Cvar_RegisterVariable (&gl_fogblue);
6343 Cvar_RegisterVariable (&gl_fogstart);
6344 Cvar_RegisterVariable (&gl_fogend);
6345 Cvar_RegisterVariable (&gl_skyclip);
6347 Cvar_RegisterVariable(&r_motionblur);
6348 Cvar_RegisterVariable(&r_motionblur_maxblur);
6349 Cvar_RegisterVariable(&r_motionblur_bmin);
6350 Cvar_RegisterVariable(&r_motionblur_vmin);
6351 Cvar_RegisterVariable(&r_motionblur_vmax);
6352 Cvar_RegisterVariable(&r_motionblur_vcoeff);
6353 Cvar_RegisterVariable(&r_motionblur_randomize);
6354 Cvar_RegisterVariable(&r_damageblur);
6355 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6356 Cvar_RegisterVariable(&r_equalize_entities_minambient);
6357 Cvar_RegisterVariable(&r_equalize_entities_by);
6358 Cvar_RegisterVariable(&r_equalize_entities_to);
6359 Cvar_RegisterVariable(&r_depthfirst);
6360 Cvar_RegisterVariable(&r_useinfinitefarclip);
6361 Cvar_RegisterVariable(&r_farclip_base);
6362 Cvar_RegisterVariable(&r_farclip_world);
6363 Cvar_RegisterVariable(&r_nearclip);
6364 Cvar_RegisterVariable(&r_showbboxes);
6365 Cvar_RegisterVariable(&r_showsurfaces);
6366 Cvar_RegisterVariable(&r_showtris);
6367 Cvar_RegisterVariable(&r_shownormals);
6368 Cvar_RegisterVariable(&r_showlighting);
6369 Cvar_RegisterVariable(&r_showshadowvolumes);
6370 Cvar_RegisterVariable(&r_showcollisionbrushes);
6371 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6372 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6373 Cvar_RegisterVariable(&r_showdisabledepthtest);
6374 Cvar_RegisterVariable(&r_drawportals);
6375 Cvar_RegisterVariable(&r_drawentities);
6376 Cvar_RegisterVariable(&r_cullentities_trace);
6377 Cvar_RegisterVariable(&r_cullentities_trace_samples);
6378 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6379 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6380 Cvar_RegisterVariable(&r_cullentities_trace_delay);
6381 Cvar_RegisterVariable(&r_drawviewmodel);
6382 Cvar_RegisterVariable(&r_drawexteriormodel);
6383 Cvar_RegisterVariable(&r_speeds);
6384 Cvar_RegisterVariable(&r_fullbrights);
6385 Cvar_RegisterVariable(&r_wateralpha);
6386 Cvar_RegisterVariable(&r_dynamic);
6387 Cvar_RegisterVariable(&r_fullbright);
6388 Cvar_RegisterVariable(&r_shadows);
6389 Cvar_RegisterVariable(&r_shadows_darken);
6390 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6391 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6392 Cvar_RegisterVariable(&r_shadows_throwdistance);
6393 Cvar_RegisterVariable(&r_shadows_throwdirection);
6394 Cvar_RegisterVariable(&r_shadows_focus);
6395 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6396 Cvar_RegisterVariable(&r_q1bsp_skymasking);
6397 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6398 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6399 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6400 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6401 Cvar_RegisterVariable(&r_fog_exp2);
6402 Cvar_RegisterVariable(&r_drawfog);
6403 Cvar_RegisterVariable(&r_transparentdepthmasking);
6404 Cvar_RegisterVariable(&r_texture_dds_load);
6405 Cvar_RegisterVariable(&r_texture_dds_save);
6406 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6407 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6408 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6409 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6410 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6411 Cvar_RegisterVariable(&r_textureunits);
6412 Cvar_RegisterVariable(&gl_combine);
6413 Cvar_RegisterVariable(&r_glsl);
6414 Cvar_RegisterVariable(&r_glsl_deluxemapping);
6415 Cvar_RegisterVariable(&r_glsl_offsetmapping);
6416 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6417 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6418 Cvar_RegisterVariable(&r_glsl_postprocess);
6419 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6420 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6421 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6422 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6423 Cvar_RegisterVariable(&r_water);
6424 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6425 Cvar_RegisterVariable(&r_water_clippingplanebias);
6426 Cvar_RegisterVariable(&r_water_refractdistort);
6427 Cvar_RegisterVariable(&r_water_reflectdistort);
6428 Cvar_RegisterVariable(&r_lerpsprites);
6429 Cvar_RegisterVariable(&r_lerpmodels);
6430 Cvar_RegisterVariable(&r_lerplightstyles);
6431 Cvar_RegisterVariable(&r_waterscroll);
6432 Cvar_RegisterVariable(&r_bloom);
6433 Cvar_RegisterVariable(&r_bloom_colorscale);
6434 Cvar_RegisterVariable(&r_bloom_brighten);
6435 Cvar_RegisterVariable(&r_bloom_blur);
6436 Cvar_RegisterVariable(&r_bloom_resolution);
6437 Cvar_RegisterVariable(&r_bloom_colorexponent);
6438 Cvar_RegisterVariable(&r_bloom_colorsubtract);
6439 Cvar_RegisterVariable(&r_hdr);
6440 Cvar_RegisterVariable(&r_hdr_scenebrightness);
6441 Cvar_RegisterVariable(&r_hdr_glowintensity);
6442 Cvar_RegisterVariable(&r_hdr_range);
6443 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6444 Cvar_RegisterVariable(&developer_texturelogging);
6445 Cvar_RegisterVariable(&gl_lightmaps);
6446 Cvar_RegisterVariable(&r_test);
6447 Cvar_RegisterVariable(&r_glsl_saturation);
6448 Cvar_RegisterVariable(&r_framedatasize);
6449 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
6450 Cvar_SetValue("r_fullbrights", 0);
6451 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap);
6453 Cvar_RegisterVariable(&r_track_sprites);
6454 Cvar_RegisterVariable(&r_track_sprites_flags);
6455 Cvar_RegisterVariable(&r_track_sprites_scalew);
6456 Cvar_RegisterVariable(&r_track_sprites_scaleh);
6457 Cvar_RegisterVariable(&r_overheadsprites_perspective);
6458 Cvar_RegisterVariable(&r_overheadsprites_pushback);
6461 extern void R_Textures_Init(void);
6462 extern void GL_Draw_Init(void);
6463 extern void GL_Main_Init(void);
6464 extern void R_Shadow_Init(void);
6465 extern void R_Sky_Init(void);
6466 extern void GL_Surf_Init(void);
6467 extern void R_Particles_Init(void);
6468 extern void R_Explosion_Init(void);
6469 extern void gl_backend_init(void);
6470 extern void Sbar_Init(void);
6471 extern void R_LightningBeams_Init(void);
6472 extern void Mod_RenderInit(void);
6473 extern void Font_Init(void);
6475 void Render_Init(void)
6488 R_LightningBeams_Init();
6497 extern char *ENGINE_EXTENSIONS;
6500 gl_renderer = (const char *)qglGetString(GL_RENDERER);
6501 gl_vendor = (const char *)qglGetString(GL_VENDOR);
6502 gl_version = (const char *)qglGetString(GL_VERSION);
6503 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
6507 if (!gl_platformextensions)
6508 gl_platformextensions = "";
6510 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
6511 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
6512 Con_Printf("GL_VERSION: %s\n", gl_version);
6513 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
6514 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
6516 VID_CheckExtensions();
6518 // LordHavoc: report supported extensions
6519 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
6521 // clear to black (loading plaque will be seen over this)
6523 qglClearColor(0,0,0,1);CHECKGLERROR
6524 qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
6527 int R_CullBox(const vec3_t mins, const vec3_t maxs)
6531 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
6533 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
6536 p = r_refdef.view.frustum + i;
6541 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6545 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6549 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6553 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6557 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6561 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6565 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6569 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6577 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
6581 for (i = 0;i < numplanes;i++)
6588 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6592 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6596 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6600 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6604 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6608 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6612 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6616 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6624 //==================================================================================
6626 // LordHavoc: this stores temporary data used within the same frame
6628 qboolean r_framedata_failed;
6629 static size_t r_framedata_size;
6630 static size_t r_framedata_current;
6631 static void *r_framedata_base;
6633 void R_FrameData_Reset(void)
6635 if (r_framedata_base)
6636 Mem_Free(r_framedata_base);
6637 r_framedata_base = NULL;
6638 r_framedata_size = 0;
6639 r_framedata_current = 0;
6640 r_framedata_failed = false;
6643 void R_FrameData_NewFrame(void)
6646 if (r_framedata_failed)
6647 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
6648 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
6649 wantedsize = bound(65536, wantedsize, 128*1024*1024);
6650 if (r_framedata_size != wantedsize)
6652 r_framedata_size = wantedsize;
6653 if (r_framedata_base)
6654 Mem_Free(r_framedata_base);
6655 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
6657 r_framedata_current = 0;
6658 r_framedata_failed = false;
6661 void *R_FrameData_Alloc(size_t size)
6665 // align to 16 byte boundary
6666 size = (size + 15) & ~15;
6667 data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
6668 r_framedata_current += size;
6671 if (r_framedata_current > r_framedata_size)
6672 r_framedata_failed = true;
6674 // return NULL on everything after a failure
6675 if (r_framedata_failed)
6681 void *R_FrameData_Store(size_t size, void *data)
6683 void *d = R_FrameData_Alloc(size);
6685 memcpy(d, data, size);
6689 //==================================================================================
6691 // LordHavoc: animcache originally written by Echon, rewritten since then
6694 * Animation cache prevents re-generating mesh data for an animated model
6695 * multiple times in one frame for lighting, shadowing, reflections, etc.
6698 void R_AnimCache_Free(void)
6702 void R_AnimCache_ClearCache(void)
6705 entity_render_t *ent;
6707 for (i = 0;i < r_refdef.scene.numentities;i++)
6709 ent = r_refdef.scene.entities[i];
6710 ent->animcache_vertex3f = NULL;
6711 ent->animcache_normal3f = NULL;
6712 ent->animcache_svector3f = NULL;
6713 ent->animcache_tvector3f = NULL;
6714 ent->animcache_vertexposition = NULL;
6715 ent->animcache_vertexmesh = NULL;
6716 ent->animcache_vertexpositionbuffer = NULL;
6717 ent->animcache_vertexmeshbuffer = NULL;
6721 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
6724 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
6725 ent->animcache_vertexmesh = R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
6726 if (!ent->animcache_vertexposition)
6727 ent->animcache_vertexposition = R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
6728 if (ent->animcache_vertexposition)
6730 for (i = 0;i < numvertices;i++)
6731 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexposition[i].vertex3f);
6732 // TODO: upload vertex buffer?
6734 if (ent->animcache_vertexmesh)
6736 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
6737 for (i = 0;i < numvertices;i++)
6738 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexmesh[i].vertex3f);
6739 if (ent->animcache_svector3f)
6740 for (i = 0;i < numvertices;i++)
6741 VectorCopy(ent->animcache_svector3f + 3*i, ent->animcache_vertexmesh[i].svector3f);
6742 if (ent->animcache_tvector3f)
6743 for (i = 0;i < numvertices;i++)
6744 VectorCopy(ent->animcache_tvector3f + 3*i, ent->animcache_vertexmesh[i].tvector3f);
6745 if (ent->animcache_normal3f)
6746 for (i = 0;i < numvertices;i++)
6747 VectorCopy(ent->animcache_normal3f + 3*i, ent->animcache_vertexmesh[i].normal3f);
6748 // TODO: upload vertex buffer?
6752 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
6754 dp_model_t *model = ent->model;
6756 // see if it's already cached this frame
6757 if (ent->animcache_vertex3f)
6759 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
6760 if (wantnormals || wanttangents)
6762 if (ent->animcache_normal3f)
6763 wantnormals = false;
6764 if (ent->animcache_svector3f)
6765 wanttangents = false;
6766 if (wantnormals || wanttangents)
6768 numvertices = model->surfmesh.num_vertices;
6770 ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6773 ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6774 ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6776 if (!r_framedata_failed)
6778 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
6779 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6786 // see if this ent is worth caching
6787 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
6789 // get some memory for this entity and generate mesh data
6790 numvertices = model->surfmesh.num_vertices;
6791 ent->animcache_vertex3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6793 ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6796 ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6797 ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6799 if (!r_framedata_failed)
6801 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
6802 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6805 return !r_framedata_failed;
6808 void R_AnimCache_CacheVisibleEntities(void)
6811 qboolean wantnormals = true;
6812 qboolean wanttangents = !r_showsurfaces.integer;
6814 switch(vid.renderpath)
6816 case RENDERPATH_GL20:
6817 case RENDERPATH_CGGL:
6819 case RENDERPATH_GL13:
6820 case RENDERPATH_GL11:
6821 wanttangents = false;
6825 if (r_shownormals.integer)
6826 wanttangents = wantnormals = true;
6828 // TODO: thread this
6829 // NOTE: R_PrepareRTLights() also caches entities
6831 for (i = 0;i < r_refdef.scene.numentities;i++)
6832 if (r_refdef.viewcache.entityvisible[i])
6833 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
6836 //==================================================================================
6838 static void R_View_UpdateEntityLighting (void)
6841 entity_render_t *ent;
6842 vec3_t tempdiffusenormal, avg;
6843 vec_t f, fa, fd, fdd;
6844 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
6846 for (i = 0;i < r_refdef.scene.numentities;i++)
6848 ent = r_refdef.scene.entities[i];
6850 // skip unseen models
6851 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
6855 if (ent->model && ent->model->brush.num_leafs)
6857 // TODO: use modellight for r_ambient settings on world?
6858 VectorSet(ent->modellight_ambient, 0, 0, 0);
6859 VectorSet(ent->modellight_diffuse, 0, 0, 0);
6860 VectorSet(ent->modellight_lightdir, 0, 0, 1);
6864 // fetch the lighting from the worldmodel data
6865 VectorClear(ent->modellight_ambient);
6866 VectorClear(ent->modellight_diffuse);
6867 VectorClear(tempdiffusenormal);
6868 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6871 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
6872 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
6873 if(ent->flags & RENDER_EQUALIZE)
6875 // first fix up ambient lighting...
6876 if(r_equalize_entities_minambient.value > 0)
6878 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
6881 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
6882 if(fa < r_equalize_entities_minambient.value * fd)
6885 // fa'/fd' = minambient
6886 // fa'+0.25*fd' = fa+0.25*fd
6888 // fa' = fd' * minambient
6889 // fd'*(0.25+minambient) = fa+0.25*fd
6891 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
6892 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
6894 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
6895 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
6896 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
6897 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
6902 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
6904 VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
6905 f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
6908 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
6909 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
6910 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
6916 VectorSet(ent->modellight_ambient, 1, 1, 1);
6918 // move the light direction into modelspace coordinates for lighting code
6919 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
6920 if(VectorLength2(ent->modellight_lightdir) == 0)
6921 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
6922 VectorNormalize(ent->modellight_lightdir);
6926 #define MAX_LINEOFSIGHTTRACES 64
6928 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
6931 vec3_t boxmins, boxmaxs;
6934 dp_model_t *model = r_refdef.scene.worldmodel;
6936 if (!model || !model->brush.TraceLineOfSight)
6939 // expand the box a little
6940 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
6941 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
6942 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
6943 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
6944 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
6945 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
6947 // return true if eye is inside enlarged box
6948 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
6952 VectorCopy(eye, start);
6953 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
6954 if (model->brush.TraceLineOfSight(model, start, end))
6957 // try various random positions
6958 for (i = 0;i < numsamples;i++)
6960 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
6961 if (model->brush.TraceLineOfSight(model, start, end))
6969 static void R_View_UpdateEntityVisible (void)
6974 entity_render_t *ent;
6976 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
6977 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
6978 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
6979 : RENDER_EXTERIORMODEL;
6980 if (!r_drawviewmodel.integer)
6981 renderimask |= RENDER_VIEWMODEL;
6982 if (!r_drawexteriormodel.integer)
6983 renderimask |= RENDER_EXTERIORMODEL;
6984 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
6986 // worldmodel can check visibility
6987 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
6988 for (i = 0;i < r_refdef.scene.numentities;i++)
6990 ent = r_refdef.scene.entities[i];
6991 if (!(ent->flags & renderimask))
6992 if (!R_CullBox(ent->mins, ent->maxs) || (ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
6993 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))
6994 r_refdef.viewcache.entityvisible[i] = true;
6996 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
6997 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
6999 for (i = 0;i < r_refdef.scene.numentities;i++)
7001 ent = r_refdef.scene.entities[i];
7002 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7004 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7006 continue; // temp entities do pvs only
7007 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7008 ent->last_trace_visibility = realtime;
7009 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7010 r_refdef.viewcache.entityvisible[i] = 0;
7017 // no worldmodel or it can't check visibility
7018 for (i = 0;i < r_refdef.scene.numentities;i++)
7020 ent = r_refdef.scene.entities[i];
7021 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));
7026 /// only used if skyrendermasked, and normally returns false
7027 int R_DrawBrushModelsSky (void)
7030 entity_render_t *ent;
7033 for (i = 0;i < r_refdef.scene.numentities;i++)
7035 if (!r_refdef.viewcache.entityvisible[i])
7037 ent = r_refdef.scene.entities[i];
7038 if (!ent->model || !ent->model->DrawSky)
7040 ent->model->DrawSky(ent);
7046 static void R_DrawNoModel(entity_render_t *ent);
7047 static void R_DrawModels(void)
7050 entity_render_t *ent;
7052 for (i = 0;i < r_refdef.scene.numentities;i++)
7054 if (!r_refdef.viewcache.entityvisible[i])
7056 ent = r_refdef.scene.entities[i];
7057 r_refdef.stats.entities++;
7058 if (ent->model && ent->model->Draw != NULL)
7059 ent->model->Draw(ent);
7065 static void R_DrawModelsDepth(void)
7068 entity_render_t *ent;
7070 for (i = 0;i < r_refdef.scene.numentities;i++)
7072 if (!r_refdef.viewcache.entityvisible[i])
7074 ent = r_refdef.scene.entities[i];
7075 if (ent->model && ent->model->DrawDepth != NULL)
7076 ent->model->DrawDepth(ent);
7080 static void R_DrawModelsDebug(void)
7083 entity_render_t *ent;
7085 for (i = 0;i < r_refdef.scene.numentities;i++)
7087 if (!r_refdef.viewcache.entityvisible[i])
7089 ent = r_refdef.scene.entities[i];
7090 if (ent->model && ent->model->DrawDebug != NULL)
7091 ent->model->DrawDebug(ent);
7095 static void R_DrawModelsAddWaterPlanes(void)
7098 entity_render_t *ent;
7100 for (i = 0;i < r_refdef.scene.numentities;i++)
7102 if (!r_refdef.viewcache.entityvisible[i])
7104 ent = r_refdef.scene.entities[i];
7105 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7106 ent->model->DrawAddWaterPlanes(ent);
7110 static void R_View_SetFrustum(void)
7113 double slopex, slopey;
7114 vec3_t forward, left, up, origin;
7116 // we can't trust r_refdef.view.forward and friends in reflected scenes
7117 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7120 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7121 r_refdef.view.frustum[0].normal[1] = 0 - 0;
7122 r_refdef.view.frustum[0].normal[2] = -1 - 0;
7123 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7124 r_refdef.view.frustum[1].normal[1] = 0 + 0;
7125 r_refdef.view.frustum[1].normal[2] = -1 + 0;
7126 r_refdef.view.frustum[2].normal[0] = 0 - 0;
7127 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7128 r_refdef.view.frustum[2].normal[2] = -1 - 0;
7129 r_refdef.view.frustum[3].normal[0] = 0 + 0;
7130 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7131 r_refdef.view.frustum[3].normal[2] = -1 + 0;
7135 zNear = r_refdef.nearclip;
7136 nudge = 1.0 - 1.0 / (1<<23);
7137 r_refdef.view.frustum[4].normal[0] = 0 - 0;
7138 r_refdef.view.frustum[4].normal[1] = 0 - 0;
7139 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7140 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7141 r_refdef.view.frustum[5].normal[0] = 0 + 0;
7142 r_refdef.view.frustum[5].normal[1] = 0 + 0;
7143 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7144 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7150 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7151 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7152 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7153 r_refdef.view.frustum[0].dist = m[15] - m[12];
7155 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7156 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7157 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7158 r_refdef.view.frustum[1].dist = m[15] + m[12];
7160 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7161 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7162 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7163 r_refdef.view.frustum[2].dist = m[15] - m[13];
7165 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7166 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7167 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7168 r_refdef.view.frustum[3].dist = m[15] + m[13];
7170 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7171 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7172 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7173 r_refdef.view.frustum[4].dist = m[15] - m[14];
7175 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7176 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7177 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7178 r_refdef.view.frustum[5].dist = m[15] + m[14];
7181 if (r_refdef.view.useperspective)
7183 slopex = 1.0 / r_refdef.view.frustum_x;
7184 slopey = 1.0 / r_refdef.view.frustum_y;
7185 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
7186 VectorMA(forward, slopex, left, r_refdef.view.frustum[1].normal);
7187 VectorMA(forward, -slopey, up , r_refdef.view.frustum[2].normal);
7188 VectorMA(forward, slopey, up , r_refdef.view.frustum[3].normal);
7189 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7191 // Leaving those out was a mistake, those were in the old code, and they
7192 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7193 // I couldn't reproduce it after adding those normalizations. --blub
7194 VectorNormalize(r_refdef.view.frustum[0].normal);
7195 VectorNormalize(r_refdef.view.frustum[1].normal);
7196 VectorNormalize(r_refdef.view.frustum[2].normal);
7197 VectorNormalize(r_refdef.view.frustum[3].normal);
7199 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7200 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, -1024 * r_refdef.view.frustum_x, left, -1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[0]);
7201 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, 1024 * r_refdef.view.frustum_x, left, -1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[1]);
7202 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, -1024 * r_refdef.view.frustum_x, left, 1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[2]);
7203 VectorMAMAMAM(1, r_refdef.view.origin, 1024, forward, 1024 * r_refdef.view.frustum_x, left, 1024 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[3]);
7205 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7206 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7207 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7208 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7209 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7213 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7214 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7215 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7216 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7217 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7218 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7219 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7220 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7221 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7222 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7224 r_refdef.view.numfrustumplanes = 5;
7226 if (r_refdef.view.useclipplane)
7228 r_refdef.view.numfrustumplanes = 6;
7229 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7232 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7233 PlaneClassify(r_refdef.view.frustum + i);
7235 // LordHavoc: note to all quake engine coders, Quake had a special case
7236 // for 90 degrees which assumed a square view (wrong), so I removed it,
7237 // Quake2 has it disabled as well.
7239 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7240 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7241 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7242 //PlaneClassify(&frustum[0]);
7244 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7245 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7246 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7247 //PlaneClassify(&frustum[1]);
7249 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7250 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7251 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7252 //PlaneClassify(&frustum[2]);
7254 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7255 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7256 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7257 //PlaneClassify(&frustum[3]);
7260 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7261 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7262 //PlaneClassify(&frustum[4]);
7265 void R_View_Update(void)
7267 R_Main_ResizeViewCache();
7268 R_View_SetFrustum();
7269 R_View_WorldVisibility(r_refdef.view.useclipplane);
7270 R_View_UpdateEntityVisible();
7271 R_View_UpdateEntityLighting();
7274 void R_SetupView(qboolean allowwaterclippingplane)
7276 const float *customclipplane = NULL;
7278 if (r_refdef.view.useclipplane && allowwaterclippingplane)
7280 // LordHavoc: couldn't figure out how to make this approach the
7281 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7282 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7283 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7284 dist = r_refdef.view.clipplane.dist;
7285 plane[0] = r_refdef.view.clipplane.normal[0];
7286 plane[1] = r_refdef.view.clipplane.normal[1];
7287 plane[2] = r_refdef.view.clipplane.normal[2];
7289 customclipplane = plane;
7292 if (!r_refdef.view.useperspective)
7293 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);
7294 else if (vid.stencil && r_useinfinitefarclip.integer)
7295 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);
7297 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);
7298 R_SetViewport(&r_refdef.view.viewport);
7301 void R_EntityMatrix(const matrix4x4_t *matrix)
7303 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7305 gl_modelmatrixchanged = false;
7306 gl_modelmatrix = *matrix;
7307 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
7308 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
7309 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
7310 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
7312 switch(vid.renderpath)
7314 case RENDERPATH_GL20:
7315 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
7316 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
7317 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7319 case RENDERPATH_CGGL:
7322 if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
7323 if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
7324 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7327 case RENDERPATH_GL13:
7328 case RENDERPATH_GL11:
7329 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7335 void R_ResetViewRendering2D(void)
7337 r_viewport_t viewport;
7340 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
7341 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);
7342 R_SetViewport(&viewport);
7343 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
7344 GL_Color(1, 1, 1, 1);
7345 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7346 GL_BlendFunc(GL_ONE, GL_ZERO);
7347 GL_AlphaTest(false);
7348 GL_ScissorTest(false);
7349 GL_DepthMask(false);
7350 GL_DepthRange(0, 1);
7351 GL_DepthTest(false);
7352 R_EntityMatrix(&identitymatrix);
7353 R_Mesh_ResetTextureState();
7354 GL_PolygonOffset(0, 0);
7355 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7356 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7357 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7358 qglStencilMask(~0);CHECKGLERROR
7359 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7360 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7361 GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
7364 void R_ResetViewRendering3D(void)
7369 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7370 GL_Color(1, 1, 1, 1);
7371 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7372 GL_BlendFunc(GL_ONE, GL_ZERO);
7373 GL_AlphaTest(false);
7374 GL_ScissorTest(true);
7376 GL_DepthRange(0, 1);
7378 R_EntityMatrix(&identitymatrix);
7379 R_Mesh_ResetTextureState();
7380 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7381 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7382 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7383 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7384 qglStencilMask(~0);CHECKGLERROR
7385 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7386 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7387 GL_CullFace(r_refdef.view.cullface_back);
7392 R_RenderView_UpdateViewVectors
7395 static void R_RenderView_UpdateViewVectors(void)
7397 // break apart the view matrix into vectors for various purposes
7398 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
7399 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
7400 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
7401 VectorNegate(r_refdef.view.left, r_refdef.view.right);
7402 // make an inverted copy of the view matrix for tracking sprites
7403 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
7406 void R_RenderScene(void);
7407 void R_RenderWaterPlanes(void);
7409 static void R_Water_StartFrame(void)
7412 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
7413 r_waterstate_waterplane_t *p;
7415 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
7418 switch(vid.renderpath)
7420 case RENDERPATH_GL20:
7421 case RENDERPATH_CGGL:
7423 case RENDERPATH_GL13:
7424 case RENDERPATH_GL11:
7428 // set waterwidth and waterheight to the water resolution that will be
7429 // used (often less than the screen resolution for faster rendering)
7430 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
7431 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
7433 // calculate desired texture sizes
7434 // can't use water if the card does not support the texture size
7435 if (!r_water.integer || r_showsurfaces.integer)
7436 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
7437 else if (vid.support.arb_texture_non_power_of_two)
7439 texturewidth = waterwidth;
7440 textureheight = waterheight;
7441 camerawidth = waterwidth;
7442 cameraheight = waterheight;
7446 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
7447 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
7448 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
7449 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
7452 // allocate textures as needed
7453 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
7455 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7456 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
7458 if (p->texture_refraction)
7459 R_FreeTexture(p->texture_refraction);
7460 p->texture_refraction = NULL;
7461 if (p->texture_reflection)
7462 R_FreeTexture(p->texture_reflection);
7463 p->texture_reflection = NULL;
7464 if (p->texture_camera)
7465 R_FreeTexture(p->texture_camera);
7466 p->texture_camera = NULL;
7468 memset(&r_waterstate, 0, sizeof(r_waterstate));
7469 r_waterstate.texturewidth = texturewidth;
7470 r_waterstate.textureheight = textureheight;
7471 r_waterstate.camerawidth = camerawidth;
7472 r_waterstate.cameraheight = cameraheight;
7475 if (r_waterstate.texturewidth)
7477 r_waterstate.enabled = true;
7479 // when doing a reduced render (HDR) we want to use a smaller area
7480 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
7481 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
7483 // set up variables that will be used in shader setup
7484 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7485 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7486 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7487 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7490 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7491 r_waterstate.numwaterplanes = 0;
7494 void R_Water_AddWaterPlane(msurface_t *surface)
7496 int triangleindex, planeindex;
7503 r_waterstate_waterplane_t *p;
7504 texture_t *t = R_GetCurrentTexture(surface->texture);
7505 cam_ent = t->camera_entity;
7506 if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
7509 // just use the first triangle with a valid normal for any decisions
7510 VectorClear(normal);
7511 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7513 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
7514 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
7515 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
7516 TriangleNormal(vert[0], vert[1], vert[2], normal);
7517 if (VectorLength2(normal) >= 0.001)
7521 VectorCopy(normal, plane.normal);
7522 VectorNormalize(plane.normal);
7523 plane.dist = DotProduct(vert[0], plane.normal);
7524 PlaneClassify(&plane);
7525 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
7527 // skip backfaces (except if nocullface is set)
7528 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
7530 VectorNegate(plane.normal, plane.normal);
7532 PlaneClassify(&plane);
7536 // find a matching plane if there is one
7537 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7538 if(p->camera_entity == t->camera_entity)
7539 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
7541 if (planeindex >= r_waterstate.maxwaterplanes)
7542 return; // nothing we can do, out of planes
7544 // if this triangle does not fit any known plane rendered this frame, add one
7545 if (planeindex >= r_waterstate.numwaterplanes)
7547 // store the new plane
7548 r_waterstate.numwaterplanes++;
7550 // clear materialflags and pvs
7551 p->materialflags = 0;
7552 p->pvsvalid = false;
7553 p->camera_entity = t->camera_entity;
7555 // merge this surface's materialflags into the waterplane
7556 p->materialflags |= t->currentmaterialflags;
7557 if(!(p->materialflags & MATERIALFLAG_CAMERA))
7559 // merge this surface's PVS into the waterplane
7560 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
7561 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
7562 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
7564 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
7570 static void R_Water_ProcessPlanes(void)
7572 r_refdef_view_t originalview;
7573 r_refdef_view_t myview;
7575 r_waterstate_waterplane_t *p;
7578 originalview = r_refdef.view;
7580 // make sure enough textures are allocated
7581 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7583 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7585 if (!p->texture_refraction)
7586 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
7587 if (!p->texture_refraction)
7590 else if (p->materialflags & MATERIALFLAG_CAMERA)
7592 if (!p->texture_camera)
7593 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR, NULL);
7594 if (!p->texture_camera)
7598 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7600 if (!p->texture_reflection)
7601 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
7602 if (!p->texture_reflection)
7608 r_refdef.view = originalview;
7609 r_refdef.view.showdebug = false;
7610 r_refdef.view.width = r_waterstate.waterwidth;
7611 r_refdef.view.height = r_waterstate.waterheight;
7612 r_refdef.view.useclipplane = true;
7613 myview = r_refdef.view;
7614 r_waterstate.renderingscene = true;
7615 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7617 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7619 r_refdef.view = myview;
7620 // render reflected scene and copy into texture
7621 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
7622 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
7623 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
7624 r_refdef.view.clipplane = p->plane;
7625 // reverse the cullface settings for this render
7626 r_refdef.view.cullface_front = GL_FRONT;
7627 r_refdef.view.cullface_back = GL_BACK;
7628 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
7630 r_refdef.view.usecustompvs = true;
7632 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7634 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7637 R_ResetViewRendering3D();
7638 R_ClearScreen(r_refdef.fogenabled);
7642 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);
7645 // render the normal view scene and copy into texture
7646 // (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)
7647 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7649 r_waterstate.renderingrefraction = true;
7650 r_refdef.view = myview;
7652 r_refdef.view.clipplane = p->plane;
7653 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7654 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7656 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
7658 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7659 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
7660 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7661 R_RenderView_UpdateViewVectors();
7662 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);
7665 PlaneClassify(&r_refdef.view.clipplane);
7667 R_ResetViewRendering3D();
7668 R_ClearScreen(r_refdef.fogenabled);
7672 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);
7673 r_waterstate.renderingrefraction = false;
7675 else if (p->materialflags & MATERIALFLAG_CAMERA)
7677 r_refdef.view = myview;
7679 r_refdef.view.clipplane = p->plane;
7680 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7681 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7683 r_refdef.view.width = r_waterstate.camerawidth;
7684 r_refdef.view.height = r_waterstate.cameraheight;
7685 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
7686 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
7688 if(p->camera_entity)
7690 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7691 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7694 // reverse the cullface settings for this render
7695 r_refdef.view.cullface_front = GL_FRONT;
7696 r_refdef.view.cullface_back = GL_BACK;
7697 // also reverse the view matrix
7698 Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, -1, 1);
7699 R_RenderView_UpdateViewVectors();
7700 if(p->camera_entity)
7701 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);
7703 // camera needs no clipplane
7704 r_refdef.view.useclipplane = false;
7706 PlaneClassify(&r_refdef.view.clipplane);
7708 R_ResetViewRendering3D();
7709 R_ClearScreen(r_refdef.fogenabled);
7713 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);
7714 r_waterstate.renderingrefraction = false;
7718 r_waterstate.renderingscene = false;
7719 r_refdef.view = originalview;
7720 R_ResetViewRendering3D();
7721 R_ClearScreen(r_refdef.fogenabled);
7725 r_refdef.view = originalview;
7726 r_waterstate.renderingscene = false;
7727 Cvar_SetValueQuick(&r_water, 0);
7728 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
7732 void R_Bloom_StartFrame(void)
7734 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
7736 switch(vid.renderpath)
7738 case RENDERPATH_GL20:
7739 case RENDERPATH_CGGL:
7741 case RENDERPATH_GL13:
7742 case RENDERPATH_GL11:
7746 // set bloomwidth and bloomheight to the bloom resolution that will be
7747 // used (often less than the screen resolution for faster rendering)
7748 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
7749 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
7750 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
7751 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
7752 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
7754 // calculate desired texture sizes
7755 if (vid.support.arb_texture_non_power_of_two)
7757 screentexturewidth = r_refdef.view.width;
7758 screentextureheight = r_refdef.view.height;
7759 bloomtexturewidth = r_bloomstate.bloomwidth;
7760 bloomtextureheight = r_bloomstate.bloomheight;
7764 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
7765 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
7766 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
7767 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
7770 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))
7772 Cvar_SetValueQuick(&r_hdr, 0);
7773 Cvar_SetValueQuick(&r_bloom, 0);
7774 Cvar_SetValueQuick(&r_motionblur, 0);
7775 Cvar_SetValueQuick(&r_damageblur, 0);
7778 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)))
7779 screentexturewidth = screentextureheight = 0;
7780 if (!r_hdr.integer && !r_bloom.integer)
7781 bloomtexturewidth = bloomtextureheight = 0;
7783 // allocate textures as needed
7784 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
7786 if (r_bloomstate.texture_screen)
7787 R_FreeTexture(r_bloomstate.texture_screen);
7788 r_bloomstate.texture_screen = NULL;
7789 r_bloomstate.screentexturewidth = screentexturewidth;
7790 r_bloomstate.screentextureheight = screentextureheight;
7791 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
7792 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, NULL);
7794 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
7796 if (r_bloomstate.texture_bloom)
7797 R_FreeTexture(r_bloomstate.texture_bloom);
7798 r_bloomstate.texture_bloom = NULL;
7799 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
7800 r_bloomstate.bloomtextureheight = bloomtextureheight;
7801 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
7802 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
7805 // when doing a reduced render (HDR) we want to use a smaller area
7806 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
7807 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
7808 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
7809 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
7810 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
7812 // set up a texcoord array for the full resolution screen image
7813 // (we have to keep this around to copy back during final render)
7814 r_bloomstate.screentexcoord2f[0] = 0;
7815 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7816 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7817 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7818 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7819 r_bloomstate.screentexcoord2f[5] = 0;
7820 r_bloomstate.screentexcoord2f[6] = 0;
7821 r_bloomstate.screentexcoord2f[7] = 0;
7823 // set up a texcoord array for the reduced resolution bloom image
7824 // (which will be additive blended over the screen image)
7825 r_bloomstate.bloomtexcoord2f[0] = 0;
7826 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7827 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7828 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7829 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7830 r_bloomstate.bloomtexcoord2f[5] = 0;
7831 r_bloomstate.bloomtexcoord2f[6] = 0;
7832 r_bloomstate.bloomtexcoord2f[7] = 0;
7834 if (r_hdr.integer || r_bloom.integer)
7836 r_bloomstate.enabled = true;
7837 r_bloomstate.hdr = r_hdr.integer != 0;
7840 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);
7843 void R_Bloom_CopyBloomTexture(float colorscale)
7845 r_refdef.stats.bloom++;
7847 // scale down screen texture to the bloom texture size
7849 R_SetViewport(&r_bloomstate.viewport);
7850 GL_BlendFunc(GL_ONE, GL_ZERO);
7851 GL_Color(colorscale, colorscale, colorscale, 1);
7852 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
7853 // TODO: do boxfilter scale-down in shader?
7854 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
7855 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7856 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7858 // we now have a bloom image in the framebuffer
7859 // copy it into the bloom image texture for later processing
7860 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);
7861 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7864 void R_Bloom_CopyHDRTexture(void)
7866 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);
7867 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
7870 void R_Bloom_MakeTexture(void)
7873 float xoffset, yoffset, r, brighten;
7875 r_refdef.stats.bloom++;
7877 R_ResetViewRendering2D();
7879 // we have a bloom image in the framebuffer
7881 R_SetViewport(&r_bloomstate.viewport);
7883 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
7886 r = bound(0, r_bloom_colorexponent.value / x, 1);
7887 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
7889 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
7890 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
7891 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7892 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7894 // copy the vertically blurred bloom view to a texture
7895 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);
7896 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7899 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
7900 brighten = r_bloom_brighten.value;
7902 brighten *= r_hdr_range.value;
7903 brighten = sqrt(brighten);
7905 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
7906 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
7908 for (dir = 0;dir < 2;dir++)
7910 // blend on at multiple vertical offsets to achieve a vertical blur
7911 // TODO: do offset blends using GLSL
7912 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
7913 GL_BlendFunc(GL_ONE, GL_ZERO);
7914 for (x = -range;x <= range;x++)
7916 if (!dir){xoffset = 0;yoffset = x;}
7917 else {xoffset = x;yoffset = 0;}
7918 xoffset /= (float)r_bloomstate.bloomtexturewidth;
7919 yoffset /= (float)r_bloomstate.bloomtextureheight;
7920 // compute a texcoord array with the specified x and y offset
7921 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
7922 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7923 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7924 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7925 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7926 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
7927 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
7928 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
7929 // this r value looks like a 'dot' particle, fading sharply to
7930 // black at the edges
7931 // (probably not realistic but looks good enough)
7932 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
7933 //r = brighten/(range*2+1);
7934 r = brighten / (range * 2 + 1);
7936 r *= (1 - x*x/(float)(range*range));
7937 GL_Color(r, r, r, 1);
7938 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
7939 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7940 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7941 GL_BlendFunc(GL_ONE, GL_ONE);
7944 // copy the vertically blurred bloom view to a texture
7945 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);
7946 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7949 // apply subtract last
7950 // (just like it would be in a GLSL shader)
7951 if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
7953 GL_BlendFunc(GL_ONE, GL_ZERO);
7955 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
7956 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
7957 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7958 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7960 GL_BlendFunc(GL_ONE, GL_ONE);
7961 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
7962 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
7963 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
7964 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
7965 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7966 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7967 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
7969 // copy the darkened bloom view to a texture
7970 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);
7971 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7975 void R_HDR_RenderBloomTexture(void)
7977 int oldwidth, oldheight;
7978 float oldcolorscale;
7980 oldcolorscale = r_refdef.view.colorscale;
7981 oldwidth = r_refdef.view.width;
7982 oldheight = r_refdef.view.height;
7983 r_refdef.view.width = r_bloomstate.bloomwidth;
7984 r_refdef.view.height = r_bloomstate.bloomheight;
7986 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
7987 // TODO: add exposure compensation features
7988 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
7990 r_refdef.view.showdebug = false;
7991 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
7993 R_ResetViewRendering3D();
7995 R_ClearScreen(r_refdef.fogenabled);
7996 if (r_timereport_active)
7997 R_TimeReport("HDRclear");
8000 if (r_timereport_active)
8001 R_TimeReport("visibility");
8003 // only do secondary renders with HDR if r_hdr is 2 or higher
8004 r_waterstate.numwaterplanes = 0;
8005 if (r_waterstate.enabled && r_hdr.integer >= 2)
8006 R_RenderWaterPlanes();
8008 r_refdef.view.showdebug = true;
8010 r_waterstate.numwaterplanes = 0;
8012 R_ResetViewRendering2D();
8014 R_Bloom_CopyHDRTexture();
8015 R_Bloom_MakeTexture();
8017 // restore the view settings
8018 r_refdef.view.width = oldwidth;
8019 r_refdef.view.height = oldheight;
8020 r_refdef.view.colorscale = oldcolorscale;
8022 R_ResetViewRendering3D();
8024 R_ClearScreen(r_refdef.fogenabled);
8025 if (r_timereport_active)
8026 R_TimeReport("viewclear");
8029 static void R_BlendView(void)
8031 unsigned int permutation;
8032 float uservecs[4][4];
8034 switch (vid.renderpath)
8036 case RENDERPATH_GL20:
8037 case RENDERPATH_CGGL:
8039 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8040 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8041 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8042 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8043 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8045 if (r_bloomstate.texture_screen)
8047 // make sure the buffer is available
8048 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8050 R_ResetViewRendering2D();
8052 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8054 // declare variables
8056 static float avgspeed;
8058 speed = VectorLength(cl.movement_velocity);
8060 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8061 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8063 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8064 speed = bound(0, speed, 1);
8065 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8067 // calculate values into a standard alpha
8068 cl.motionbluralpha = 1 - exp(-
8070 (r_motionblur.value * speed / 80)
8072 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8075 max(0.0001, cl.time - cl.oldtime) // fps independent
8078 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8079 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8081 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8083 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8084 GL_Color(1, 1, 1, cl.motionbluralpha);
8085 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8086 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8087 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8088 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8092 // copy view into the screen texture
8093 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);
8094 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8096 else if (!r_bloomstate.texture_bloom)
8098 // we may still have to do view tint...
8099 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8101 // apply a color tint to the whole view
8102 R_ResetViewRendering2D();
8103 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8104 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8105 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8106 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8107 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8109 break; // no screen processing, no bloom, skip it
8112 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8114 // render simple bloom effect
8115 // copy the screen and shrink it and darken it for the bloom process
8116 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8117 // make the bloom texture
8118 R_Bloom_MakeTexture();
8121 #if _MSC_VER >= 1400
8122 #define sscanf sscanf_s
8124 memset(uservecs, 0, sizeof(uservecs));
8125 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8126 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8127 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8128 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8130 R_ResetViewRendering2D();
8131 GL_Color(1, 1, 1, 1);
8132 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8133 GL_BlendFunc(GL_ONE, GL_ZERO);
8135 switch(vid.renderpath)
8137 case RENDERPATH_GL20:
8138 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8139 if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8140 if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8141 if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8142 if (r_glsl_permutation->loc_ViewTintColor >= 0) qglUniform4fARB(r_glsl_permutation->loc_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8143 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8144 if (r_glsl_permutation->loc_UserVec1 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8145 if (r_glsl_permutation->loc_UserVec2 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8146 if (r_glsl_permutation->loc_UserVec3 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8147 if (r_glsl_permutation->loc_UserVec4 >= 0) qglUniform4fARB(r_glsl_permutation->loc_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8148 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
8149 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8151 case RENDERPATH_CGGL:
8153 R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8154 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_bloomstate.texture_screen);CHECKCGERROR
8155 if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_bloomstate.texture_bloom );CHECKCGERROR
8156 if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps );CHECKCGERROR
8157 if (r_cg_permutation->fp_ViewTintColor ) cgGLSetParameter4f( r_cg_permutation->fp_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);CHECKCGERROR
8158 if (r_cg_permutation->fp_PixelSize ) cgGLSetParameter2f( r_cg_permutation->fp_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8159 if (r_cg_permutation->fp_UserVec1 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);CHECKCGERROR
8160 if (r_cg_permutation->fp_UserVec2 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);CHECKCGERROR
8161 if (r_cg_permutation->fp_UserVec3 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);CHECKCGERROR
8162 if (r_cg_permutation->fp_UserVec4 ) cgGLSetParameter4f( r_cg_permutation->fp_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);CHECKCGERROR
8163 if (r_cg_permutation->fp_Saturation ) cgGLSetParameter1f( r_cg_permutation->fp_Saturation , r_glsl_saturation.value);CHECKCGERROR
8164 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8170 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8171 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8173 case RENDERPATH_GL13:
8174 case RENDERPATH_GL11:
8175 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8177 // apply a color tint to the whole view
8178 R_ResetViewRendering2D();
8179 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8180 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8181 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8182 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8183 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8189 matrix4x4_t r_waterscrollmatrix;
8191 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
8193 if (r_refdef.fog_density)
8195 r_refdef.fogcolor[0] = r_refdef.fog_red;
8196 r_refdef.fogcolor[1] = r_refdef.fog_green;
8197 r_refdef.fogcolor[2] = r_refdef.fog_blue;
8199 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
8200 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
8201 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
8202 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
8206 VectorCopy(r_refdef.fogcolor, fogvec);
8207 // color.rgb *= ContrastBoost * SceneBrightness;
8208 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
8209 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
8210 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
8211 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
8216 void R_UpdateVariables(void)
8220 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
8222 r_refdef.farclip = r_farclip_base.value;
8223 if (r_refdef.scene.worldmodel)
8224 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
8225 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
8227 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
8228 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
8229 r_refdef.polygonfactor = 0;
8230 r_refdef.polygonoffset = 0;
8231 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8232 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8234 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
8235 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
8236 r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
8237 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
8238 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
8239 if (r_showsurfaces.integer)
8241 r_refdef.scene.rtworld = false;
8242 r_refdef.scene.rtworldshadows = false;
8243 r_refdef.scene.rtdlight = false;
8244 r_refdef.scene.rtdlightshadows = false;
8245 r_refdef.lightmapintensity = 0;
8248 if (gamemode == GAME_NEHAHRA)
8250 if (gl_fogenable.integer)
8252 r_refdef.oldgl_fogenable = true;
8253 r_refdef.fog_density = gl_fogdensity.value;
8254 r_refdef.fog_red = gl_fogred.value;
8255 r_refdef.fog_green = gl_foggreen.value;
8256 r_refdef.fog_blue = gl_fogblue.value;
8257 r_refdef.fog_alpha = 1;
8258 r_refdef.fog_start = 0;
8259 r_refdef.fog_end = gl_skyclip.value;
8260 r_refdef.fog_height = 1<<30;
8261 r_refdef.fog_fadedepth = 128;
8263 else if (r_refdef.oldgl_fogenable)
8265 r_refdef.oldgl_fogenable = false;
8266 r_refdef.fog_density = 0;
8267 r_refdef.fog_red = 0;
8268 r_refdef.fog_green = 0;
8269 r_refdef.fog_blue = 0;
8270 r_refdef.fog_alpha = 0;
8271 r_refdef.fog_start = 0;
8272 r_refdef.fog_end = 0;
8273 r_refdef.fog_height = 1<<30;
8274 r_refdef.fog_fadedepth = 128;
8278 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
8279 r_refdef.fog_start = max(0, r_refdef.fog_start);
8280 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
8282 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
8284 if (r_refdef.fog_density && r_drawfog.integer)
8286 r_refdef.fogenabled = true;
8287 // this is the point where the fog reaches 0.9986 alpha, which we
8288 // consider a good enough cutoff point for the texture
8289 // (0.9986 * 256 == 255.6)
8290 if (r_fog_exp2.integer)
8291 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
8293 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
8294 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
8295 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
8296 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
8297 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
8298 R_BuildFogHeightTexture();
8299 // fog color was already set
8300 // update the fog texture
8301 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)
8302 R_BuildFogTexture();
8303 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
8304 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
8307 r_refdef.fogenabled = false;
8309 switch(vid.renderpath)
8311 case RENDERPATH_GL20:
8312 case RENDERPATH_CGGL:
8313 if(v_glslgamma.integer && !vid_gammatables_trivial)
8315 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
8317 // build GLSL gamma texture
8318 #define RAMPWIDTH 256
8319 unsigned short ramp[RAMPWIDTH * 3];
8320 unsigned char rampbgr[RAMPWIDTH][4];
8323 r_texture_gammaramps_serial = vid_gammatables_serial;
8325 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
8326 for(i = 0; i < RAMPWIDTH; ++i)
8328 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8329 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8330 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
8333 if (r_texture_gammaramps)
8335 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
8339 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, NULL);
8345 // remove GLSL gamma texture
8348 case RENDERPATH_GL13:
8349 case RENDERPATH_GL11:
8354 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
8355 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
8361 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
8362 if( scenetype != r_currentscenetype ) {
8363 // store the old scenetype
8364 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
8365 r_currentscenetype = scenetype;
8366 // move in the new scene
8367 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
8376 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
8378 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
8379 if( scenetype == r_currentscenetype ) {
8380 return &r_refdef.scene;
8382 return &r_scenes_store[ scenetype ];
8391 void R_RenderView(void)
8393 if (r_timereport_active)
8394 R_TimeReport("start");
8395 r_textureframe++; // used only by R_GetCurrentTexture
8396 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
8398 if (!r_drawentities.integer)
8399 r_refdef.scene.numentities = 0;
8401 R_AnimCache_ClearCache();
8402 R_FrameData_NewFrame();
8404 if (r_refdef.view.isoverlay)
8406 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
8407 GL_Clear( GL_DEPTH_BUFFER_BIT );
8408 R_TimeReport("depthclear");
8410 r_refdef.view.showdebug = false;
8412 r_waterstate.enabled = false;
8413 r_waterstate.numwaterplanes = 0;
8421 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
8422 return; //Host_Error ("R_RenderView: NULL worldmodel");
8424 r_refdef.view.colorscale = r_hdr_scenebrightness.value;
8426 R_RenderView_UpdateViewVectors();
8428 R_Shadow_UpdateWorldLightSelection();
8430 R_Bloom_StartFrame();
8431 R_Water_StartFrame();
8434 if (r_timereport_active)
8435 R_TimeReport("viewsetup");
8437 R_ResetViewRendering3D();
8439 if (r_refdef.view.clear || r_refdef.fogenabled)
8441 R_ClearScreen(r_refdef.fogenabled);
8442 if (r_timereport_active)
8443 R_TimeReport("viewclear");
8445 r_refdef.view.clear = true;
8447 // this produces a bloom texture to be used in R_BlendView() later
8448 if (r_hdr.integer && r_bloomstate.bloomwidth)
8450 R_HDR_RenderBloomTexture();
8451 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
8452 r_textureframe++; // used only by R_GetCurrentTexture
8455 r_refdef.view.showdebug = true;
8458 if (r_timereport_active)
8459 R_TimeReport("visibility");
8461 r_waterstate.numwaterplanes = 0;
8462 if (r_waterstate.enabled)
8463 R_RenderWaterPlanes();
8466 r_waterstate.numwaterplanes = 0;
8469 if (r_timereport_active)
8470 R_TimeReport("blendview");
8472 GL_Scissor(0, 0, vid.width, vid.height);
8473 GL_ScissorTest(false);
8477 void R_RenderWaterPlanes(void)
8479 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
8481 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
8482 if (r_timereport_active)
8483 R_TimeReport("waterworld");
8486 // don't let sound skip if going slow
8487 if (r_refdef.scene.extraupdate)
8490 R_DrawModelsAddWaterPlanes();
8491 if (r_timereport_active)
8492 R_TimeReport("watermodels");
8494 if (r_waterstate.numwaterplanes)
8496 R_Water_ProcessPlanes();
8497 if (r_timereport_active)
8498 R_TimeReport("waterscenes");
8502 extern void R_DrawLightningBeams (void);
8503 extern void VM_CL_AddPolygonsToMeshQueue (void);
8504 extern void R_DrawPortals (void);
8505 extern cvar_t cl_locs_show;
8506 static void R_DrawLocs(void);
8507 static void R_DrawEntityBBoxes(void);
8508 static void R_DrawModelDecals(void);
8509 extern void R_DrawModelShadows(void);
8510 extern void R_DrawModelShadowMaps(void);
8511 extern cvar_t cl_decals_newsystem;
8512 extern qboolean r_shadow_usingdeferredprepass;
8513 void R_RenderScene(void)
8515 qboolean shadowmapping = false;
8517 if (r_timereport_active)
8518 R_TimeReport("beginscene");
8520 r_refdef.stats.renders++;
8524 // don't let sound skip if going slow
8525 if (r_refdef.scene.extraupdate)
8528 R_MeshQueue_BeginScene();
8532 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);
8534 if (r_timereport_active)
8535 R_TimeReport("skystartframe");
8537 if (cl.csqc_vidvars.drawworld)
8539 // don't let sound skip if going slow
8540 if (r_refdef.scene.extraupdate)
8543 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
8545 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
8546 if (r_timereport_active)
8547 R_TimeReport("worldsky");
8550 if (R_DrawBrushModelsSky() && r_timereport_active)
8551 R_TimeReport("bmodelsky");
8553 if (skyrendermasked && skyrenderlater)
8555 // we have to force off the water clipping plane while rendering sky
8559 if (r_timereport_active)
8560 R_TimeReport("sky");
8564 R_AnimCache_CacheVisibleEntities();
8565 if (r_timereport_active)
8566 R_TimeReport("animation");
8568 R_Shadow_PrepareLights();
8569 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
8570 R_Shadow_PrepareModelShadows();
8571 if (r_timereport_active)
8572 R_TimeReport("preparelights");
8574 if (R_Shadow_ShadowMappingEnabled())
8575 shadowmapping = true;
8577 if (r_shadow_usingdeferredprepass)
8578 R_Shadow_DrawPrepass();
8580 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
8582 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
8583 if (r_timereport_active)
8584 R_TimeReport("worlddepth");
8586 if (r_depthfirst.integer >= 2)
8588 R_DrawModelsDepth();
8589 if (r_timereport_active)
8590 R_TimeReport("modeldepth");
8593 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
8595 R_DrawModelShadowMaps();
8596 R_ResetViewRendering3D();
8597 // don't let sound skip if going slow
8598 if (r_refdef.scene.extraupdate)
8602 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
8604 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
8605 if (r_timereport_active)
8606 R_TimeReport("world");
8609 // don't let sound skip if going slow
8610 if (r_refdef.scene.extraupdate)
8614 if (r_timereport_active)
8615 R_TimeReport("models");
8617 // don't let sound skip if going slow
8618 if (r_refdef.scene.extraupdate)
8621 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8623 R_DrawModelShadows();
8624 R_ResetViewRendering3D();
8625 // don't let sound skip if going slow
8626 if (r_refdef.scene.extraupdate)
8630 if (!r_shadow_usingdeferredprepass)
8632 R_Shadow_DrawLights();
8633 if (r_timereport_active)
8634 R_TimeReport("rtlights");
8637 // don't let sound skip if going slow
8638 if (r_refdef.scene.extraupdate)
8641 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8643 R_DrawModelShadows();
8644 R_ResetViewRendering3D();
8645 // don't let sound skip if going slow
8646 if (r_refdef.scene.extraupdate)
8650 if (cl.csqc_vidvars.drawworld)
8652 if (cl_decals_newsystem.integer)
8654 R_DrawModelDecals();
8655 if (r_timereport_active)
8656 R_TimeReport("modeldecals");
8661 if (r_timereport_active)
8662 R_TimeReport("decals");
8666 if (r_timereport_active)
8667 R_TimeReport("particles");
8670 if (r_timereport_active)
8671 R_TimeReport("explosions");
8673 R_DrawLightningBeams();
8674 if (r_timereport_active)
8675 R_TimeReport("lightning");
8678 VM_CL_AddPolygonsToMeshQueue();
8680 if (r_refdef.view.showdebug)
8682 if (cl_locs_show.integer)
8685 if (r_timereport_active)
8686 R_TimeReport("showlocs");
8689 if (r_drawportals.integer)
8692 if (r_timereport_active)
8693 R_TimeReport("portals");
8696 if (r_showbboxes.value > 0)
8698 R_DrawEntityBBoxes();
8699 if (r_timereport_active)
8700 R_TimeReport("bboxes");
8704 R_MeshQueue_RenderTransparent();
8705 if (r_timereport_active)
8706 R_TimeReport("drawtrans");
8708 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))
8710 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
8711 if (r_timereport_active)
8712 R_TimeReport("worlddebug");
8713 R_DrawModelsDebug();
8714 if (r_timereport_active)
8715 R_TimeReport("modeldebug");
8718 if (cl.csqc_vidvars.drawworld)
8720 R_Shadow_DrawCoronas();
8721 if (r_timereport_active)
8722 R_TimeReport("coronas");
8725 // don't let sound skip if going slow
8726 if (r_refdef.scene.extraupdate)
8729 R_ResetViewRendering2D();
8732 static const unsigned short bboxelements[36] =
8742 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
8745 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
8747 RSurf_ActiveWorldEntity();
8749 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8750 GL_DepthMask(false);
8751 GL_DepthRange(0, 1);
8752 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8753 R_Mesh_ResetTextureState();
8755 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
8756 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
8757 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
8758 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
8759 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
8760 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
8761 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
8762 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
8763 R_FillColors(color4f, 8, cr, cg, cb, ca);
8764 if (r_refdef.fogenabled)
8766 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
8768 f1 = RSurf_FogVertex(v);
8770 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
8771 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
8772 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
8775 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
8776 R_Mesh_ResetTextureState();
8777 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8778 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
8781 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
8785 prvm_edict_t *edict;
8786 prvm_prog_t *prog_save = prog;
8788 // this function draws bounding boxes of server entities
8792 GL_CullFace(GL_NONE);
8793 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8797 for (i = 0;i < numsurfaces;i++)
8799 edict = PRVM_EDICT_NUM(surfacelist[i]);
8800 switch ((int)edict->fields.server->solid)
8802 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
8803 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
8804 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
8805 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
8806 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
8807 default: Vector4Set(color, 0, 0, 0, 0.50);break;
8809 color[3] *= r_showbboxes.value;
8810 color[3] = bound(0, color[3], 1);
8811 GL_DepthTest(!r_showdisabledepthtest.integer);
8812 GL_CullFace(r_refdef.view.cullface_front);
8813 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
8819 static void R_DrawEntityBBoxes(void)
8822 prvm_edict_t *edict;
8824 prvm_prog_t *prog_save = prog;
8826 // this function draws bounding boxes of server entities
8832 for (i = 0;i < prog->num_edicts;i++)
8834 edict = PRVM_EDICT_NUM(i);
8835 if (edict->priv.server->free)
8837 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
8838 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
8840 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
8842 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
8843 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
8849 static const int nomodelelement3i[24] =
8861 static const unsigned short nomodelelement3s[24] =
8873 static const float nomodelvertex3f[6*3] =
8883 static const float nomodelcolor4f[6*4] =
8885 0.0f, 0.0f, 0.5f, 1.0f,
8886 0.0f, 0.0f, 0.5f, 1.0f,
8887 0.0f, 0.5f, 0.0f, 1.0f,
8888 0.0f, 0.5f, 0.0f, 1.0f,
8889 0.5f, 0.0f, 0.0f, 1.0f,
8890 0.5f, 0.0f, 0.0f, 1.0f
8893 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
8899 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);
8901 // this is only called once per entity so numsurfaces is always 1, and
8902 // surfacelist is always {0}, so this code does not handle batches
8904 if (rsurface.ent_flags & RENDER_ADDITIVE)
8906 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
8907 GL_DepthMask(false);
8909 else if (rsurface.colormod[3] < 1)
8911 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8912 GL_DepthMask(false);
8916 GL_BlendFunc(GL_ONE, GL_ZERO);
8919 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
8920 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
8921 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
8922 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
8923 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8924 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
8925 for (i = 0, c = color4f;i < 6;i++, c += 4)
8927 c[0] *= rsurface.colormod[0];
8928 c[1] *= rsurface.colormod[1];
8929 c[2] *= rsurface.colormod[2];
8930 c[3] *= rsurface.colormod[3];
8932 if (r_refdef.fogenabled)
8934 for (i = 0, c = color4f;i < 6;i++, c += 4)
8936 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
8938 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
8939 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
8940 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
8943 R_Mesh_ResetTextureState();
8944 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
8945 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
8948 void R_DrawNoModel(entity_render_t *ent)
8951 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
8952 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
8953 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
8955 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
8958 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
8960 vec3_t right1, right2, diff, normal;
8962 VectorSubtract (org2, org1, normal);
8964 // calculate 'right' vector for start
8965 VectorSubtract (r_refdef.view.origin, org1, diff);
8966 CrossProduct (normal, diff, right1);
8967 VectorNormalize (right1);
8969 // calculate 'right' vector for end
8970 VectorSubtract (r_refdef.view.origin, org2, diff);
8971 CrossProduct (normal, diff, right2);
8972 VectorNormalize (right2);
8974 vert[ 0] = org1[0] + width * right1[0];
8975 vert[ 1] = org1[1] + width * right1[1];
8976 vert[ 2] = org1[2] + width * right1[2];
8977 vert[ 3] = org1[0] - width * right1[0];
8978 vert[ 4] = org1[1] - width * right1[1];
8979 vert[ 5] = org1[2] - width * right1[2];
8980 vert[ 6] = org2[0] - width * right2[0];
8981 vert[ 7] = org2[1] - width * right2[1];
8982 vert[ 8] = org2[2] - width * right2[2];
8983 vert[ 9] = org2[0] + width * right2[0];
8984 vert[10] = org2[1] + width * right2[1];
8985 vert[11] = org2[2] + width * right2[2];
8988 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)
8990 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
8991 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
8992 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
8993 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
8994 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
8995 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
8996 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
8997 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
8998 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
8999 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9000 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9001 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9004 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9009 VectorSet(v, x, y, z);
9010 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9011 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9013 if (i == mesh->numvertices)
9015 if (mesh->numvertices < mesh->maxvertices)
9017 VectorCopy(v, vertex3f);
9018 mesh->numvertices++;
9020 return mesh->numvertices;
9026 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9030 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9031 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9032 e = mesh->element3i + mesh->numtriangles * 3;
9033 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9035 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9036 if (mesh->numtriangles < mesh->maxtriangles)
9041 mesh->numtriangles++;
9043 element[1] = element[2];
9047 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9051 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9052 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9053 e = mesh->element3i + mesh->numtriangles * 3;
9054 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9056 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9057 if (mesh->numtriangles < mesh->maxtriangles)
9062 mesh->numtriangles++;
9064 element[1] = element[2];
9068 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9069 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9071 int planenum, planenum2;
9074 mplane_t *plane, *plane2;
9076 double temppoints[2][256*3];
9077 // figure out how large a bounding box we need to properly compute this brush
9079 for (w = 0;w < numplanes;w++)
9080 maxdist = max(maxdist, fabs(planes[w].dist));
9081 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9082 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9083 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9087 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9088 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9090 if (planenum2 == planenum)
9092 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);
9095 if (tempnumpoints < 3)
9097 // generate elements forming a triangle fan for this polygon
9098 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9102 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)
9104 texturelayer_t *layer;
9105 layer = t->currentlayers + t->currentnumlayers++;
9107 layer->depthmask = depthmask;
9108 layer->blendfunc1 = blendfunc1;
9109 layer->blendfunc2 = blendfunc2;
9110 layer->texture = texture;
9111 layer->texmatrix = *matrix;
9112 layer->color[0] = r;
9113 layer->color[1] = g;
9114 layer->color[2] = b;
9115 layer->color[3] = a;
9118 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9121 index = parms[2] + r_refdef.scene.time * parms[3];
9122 index -= floor(index);
9126 case Q3WAVEFUNC_NONE:
9127 case Q3WAVEFUNC_NOISE:
9128 case Q3WAVEFUNC_COUNT:
9131 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
9132 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
9133 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
9134 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
9135 case Q3WAVEFUNC_TRIANGLE:
9137 f = index - floor(index);
9148 return (float)(parms[0] + parms[1] * f);
9151 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
9156 matrix4x4_t matrix, temp;
9157 switch(tcmod->tcmod)
9161 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9162 matrix = r_waterscrollmatrix;
9164 matrix = identitymatrix;
9166 case Q3TCMOD_ENTITYTRANSLATE:
9167 // this is used in Q3 to allow the gamecode to control texcoord
9168 // scrolling on the entity, which is not supported in darkplaces yet.
9169 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
9171 case Q3TCMOD_ROTATE:
9172 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
9173 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
9174 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
9177 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
9179 case Q3TCMOD_SCROLL:
9180 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
9182 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
9183 w = (int) tcmod->parms[0];
9184 h = (int) tcmod->parms[1];
9185 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
9187 idx = (int) floor(f * w * h);
9188 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
9190 case Q3TCMOD_STRETCH:
9191 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
9192 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
9194 case Q3TCMOD_TRANSFORM:
9195 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
9196 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
9197 VectorSet(tcmat + 6, 0 , 0 , 1);
9198 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
9199 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
9201 case Q3TCMOD_TURBULENT:
9202 // this is handled in the RSurf_PrepareVertices function
9203 matrix = identitymatrix;
9207 Matrix4x4_Concat(texmatrix, &matrix, &temp);
9210 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
9212 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
9213 char name[MAX_QPATH];
9214 skinframe_t *skinframe;
9215 unsigned char pixels[296*194];
9216 strlcpy(cache->name, skinname, sizeof(cache->name));
9217 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
9218 if (developer_loading.integer)
9219 Con_Printf("loading %s\n", name);
9220 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
9221 if (!skinframe || !skinframe->base)
9224 fs_offset_t filesize;
9226 f = FS_LoadFile(name, tempmempool, true, &filesize);
9229 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
9230 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
9234 cache->skinframe = skinframe;
9237 texture_t *R_GetCurrentTexture(texture_t *t)
9240 const entity_render_t *ent = rsurface.entity;
9241 dp_model_t *model = ent->model;
9242 q3shaderinfo_layer_tcmod_t *tcmod;
9244 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
9245 return t->currentframe;
9246 t->update_lastrenderframe = r_textureframe;
9247 t->update_lastrenderentity = (void *)ent;
9249 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
9250 t->camera_entity = ent->entitynumber;
9252 t->camera_entity = 0;
9254 // switch to an alternate material if this is a q1bsp animated material
9256 texture_t *texture = t;
9257 int s = rsurface.ent_skinnum;
9258 if ((unsigned int)s >= (unsigned int)model->numskins)
9260 if (model->skinscenes)
9262 if (model->skinscenes[s].framecount > 1)
9263 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
9265 s = model->skinscenes[s].firstframe;
9268 t = t + s * model->num_surfaces;
9271 // use an alternate animation if the entity's frame is not 0,
9272 // and only if the texture has an alternate animation
9273 if (rsurface.ent_alttextures && t->anim_total[1])
9274 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
9276 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
9278 texture->currentframe = t;
9281 // update currentskinframe to be a qw skin or animation frame
9282 if (rsurface.ent_qwskin >= 0)
9284 i = rsurface.ent_qwskin;
9285 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
9287 r_qwskincache_size = cl.maxclients;
9289 Mem_Free(r_qwskincache);
9290 r_qwskincache = Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
9292 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
9293 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
9294 t->currentskinframe = r_qwskincache[i].skinframe;
9295 if (t->currentskinframe == NULL)
9296 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9298 else if (t->numskinframes >= 2)
9299 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9300 if (t->backgroundnumskinframes >= 2)
9301 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
9303 t->currentmaterialflags = t->basematerialflags;
9304 t->currentalpha = rsurface.colormod[3];
9305 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
9306 t->currentalpha *= r_wateralpha.value;
9307 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
9308 t->currentalpha *= t->r_water_wateralpha;
9309 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
9310 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
9311 if (!(rsurface.ent_flags & RENDER_LIGHT))
9312 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
9313 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
9315 // pick a model lighting mode
9316 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
9317 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
9319 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
9321 if (rsurface.ent_flags & RENDER_ADDITIVE)
9322 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9323 else if (t->currentalpha < 1)
9324 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9325 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
9326 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
9327 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
9328 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
9329 if (t->backgroundnumskinframes)
9330 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
9331 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
9333 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
9334 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
9337 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
9338 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
9339 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
9341 // there is no tcmod
9342 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9344 t->currenttexmatrix = r_waterscrollmatrix;
9345 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
9347 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
9349 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
9350 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
9353 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9354 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
9355 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9356 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
9358 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
9359 if (t->currentskinframe->qpixels)
9360 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
9361 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
9362 if (!t->basetexture)
9363 t->basetexture = r_texture_notexture;
9364 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
9365 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
9366 t->nmaptexture = t->currentskinframe->nmap;
9367 if (!t->nmaptexture)
9368 t->nmaptexture = r_texture_blanknormalmap;
9369 t->glosstexture = r_texture_black;
9370 t->glowtexture = t->currentskinframe->glow;
9371 t->fogtexture = t->currentskinframe->fog;
9372 t->reflectmasktexture = t->currentskinframe->reflect;
9373 if (t->backgroundnumskinframes)
9375 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
9376 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
9377 t->backgroundglosstexture = r_texture_black;
9378 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
9379 if (!t->backgroundnmaptexture)
9380 t->backgroundnmaptexture = r_texture_blanknormalmap;
9384 t->backgroundbasetexture = r_texture_white;
9385 t->backgroundnmaptexture = r_texture_blanknormalmap;
9386 t->backgroundglosstexture = r_texture_black;
9387 t->backgroundglowtexture = NULL;
9389 t->specularpower = r_shadow_glossexponent.value;
9390 // TODO: store reference values for these in the texture?
9391 t->specularscale = 0;
9392 if (r_shadow_gloss.integer > 0)
9394 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
9396 if (r_shadow_glossintensity.value > 0)
9398 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
9399 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
9400 t->specularscale = r_shadow_glossintensity.value;
9403 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
9405 t->glosstexture = r_texture_white;
9406 t->backgroundglosstexture = r_texture_white;
9407 t->specularscale = r_shadow_gloss2intensity.value;
9408 t->specularpower = r_shadow_gloss2exponent.value;
9411 t->specularscale *= t->specularscalemod;
9412 t->specularpower *= t->specularpowermod;
9414 // lightmaps mode looks bad with dlights using actual texturing, so turn
9415 // off the colormap and glossmap, but leave the normalmap on as it still
9416 // accurately represents the shading involved
9417 if (gl_lightmaps.integer)
9419 t->basetexture = r_texture_grey128;
9420 t->pantstexture = r_texture_black;
9421 t->shirttexture = r_texture_black;
9422 t->nmaptexture = r_texture_blanknormalmap;
9423 t->glosstexture = r_texture_black;
9424 t->glowtexture = NULL;
9425 t->fogtexture = NULL;
9426 t->reflectmasktexture = NULL;
9427 t->backgroundbasetexture = NULL;
9428 t->backgroundnmaptexture = r_texture_blanknormalmap;
9429 t->backgroundglosstexture = r_texture_black;
9430 t->backgroundglowtexture = NULL;
9431 t->specularscale = 0;
9432 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
9435 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
9436 VectorClear(t->dlightcolor);
9437 t->currentnumlayers = 0;
9438 if (t->currentmaterialflags & MATERIALFLAG_WALL)
9440 int blendfunc1, blendfunc2;
9442 if (t->currentmaterialflags & MATERIALFLAG_ADD)
9444 blendfunc1 = GL_SRC_ALPHA;
9445 blendfunc2 = GL_ONE;
9447 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
9449 blendfunc1 = GL_SRC_ALPHA;
9450 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
9452 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
9454 blendfunc1 = t->customblendfunc[0];
9455 blendfunc2 = t->customblendfunc[1];
9459 blendfunc1 = GL_ONE;
9460 blendfunc2 = GL_ZERO;
9462 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
9463 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
9465 // fullbright is not affected by r_refdef.lightmapintensity
9466 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]);
9467 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9468 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]);
9469 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9470 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]);
9474 vec3_t ambientcolor;
9476 // set the color tint used for lights affecting this surface
9477 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
9479 // q3bsp has no lightmap updates, so the lightstylevalue that
9480 // would normally be baked into the lightmap must be
9481 // applied to the color
9482 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
9483 if (model->type == mod_brushq3)
9484 colorscale *= r_refdef.scene.rtlightstylevalue[0];
9485 colorscale *= r_refdef.lightmapintensity;
9486 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
9487 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
9488 // basic lit geometry
9489 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]);
9490 // add pants/shirt if needed
9491 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9492 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]);
9493 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9494 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]);
9495 // now add ambient passes if needed
9496 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
9498 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]);
9499 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9500 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]);
9501 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9502 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]);
9505 if (t->glowtexture != NULL && !gl_lightmaps.integer)
9506 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]);
9507 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
9509 // if this is opaque use alpha blend which will darken the earlier
9512 // if this is an alpha blended material, all the earlier passes
9513 // were darkened by fog already, so we only need to add the fog
9514 // color ontop through the fog mask texture
9516 // if this is an additive blended material, all the earlier passes
9517 // were darkened by fog already, and we should not add fog color
9518 // (because the background was not darkened, there is no fog color
9519 // that was lost behind it).
9520 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]);
9524 return t->currentframe;
9527 rsurfacestate_t rsurface;
9529 void R_Mesh_ResizeArrays(int newvertices)
9531 unsigned char *base;
9533 if (rsurface.array_size >= newvertices)
9535 if (rsurface.array_base)
9536 Mem_Free(rsurface.array_base);
9537 rsurface.array_size = (newvertices + 1023) & ~1023;
9539 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9540 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9541 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9542 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9543 size += rsurface.array_size * sizeof(float[3]);
9544 size += rsurface.array_size * sizeof(float[3]);
9545 size += rsurface.array_size * sizeof(float[3]);
9546 size += rsurface.array_size * sizeof(float[3]);
9547 size += rsurface.array_size * sizeof(float[3]);
9548 size += rsurface.array_size * sizeof(float[3]);
9549 size += rsurface.array_size * sizeof(float[3]);
9550 size += rsurface.array_size * sizeof(float[3]);
9551 size += rsurface.array_size * sizeof(float[4]);
9552 size += rsurface.array_size * sizeof(float[2]);
9553 size += rsurface.array_size * sizeof(float[2]);
9554 size += rsurface.array_size * sizeof(float[4]);
9555 size += rsurface.array_size * sizeof(int[3]);
9556 size += rsurface.array_size * sizeof(unsigned short[3]);
9557 rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
9558 rsurface.array_modelvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9559 rsurface.array_batchvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9560 rsurface.array_modelvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9561 rsurface.array_batchvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9562 rsurface.array_modelvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9563 rsurface.array_modelsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9564 rsurface.array_modeltvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9565 rsurface.array_modelnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9566 rsurface.array_batchvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9567 rsurface.array_batchsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9568 rsurface.array_batchtvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9569 rsurface.array_batchnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9570 rsurface.array_batchlightmapcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9571 rsurface.array_batchtexcoordtexture2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9572 rsurface.array_batchtexcoordlightmap2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9573 rsurface.array_passcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9574 rsurface.array_batchelement3i = (int *)base;base += rsurface.array_size * sizeof(int[3]);
9575 rsurface.array_batchelement3s = (unsigned short *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
9578 void RSurf_ActiveWorldEntity(void)
9580 dp_model_t *model = r_refdef.scene.worldmodel;
9581 //if (rsurface.entity == r_refdef.scene.worldentity)
9583 rsurface.entity = r_refdef.scene.worldentity;
9584 rsurface.skeleton = NULL;
9585 rsurface.ent_skinnum = 0;
9586 rsurface.ent_qwskin = -1;
9587 rsurface.ent_shadertime = 0;
9588 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
9589 if (rsurface.array_size < model->surfmesh.num_vertices)
9590 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9591 rsurface.matrix = identitymatrix;
9592 rsurface.inversematrix = identitymatrix;
9593 rsurface.matrixscale = 1;
9594 rsurface.inversematrixscale = 1;
9595 R_EntityMatrix(&identitymatrix);
9596 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
9597 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
9598 rsurface.fograngerecip = r_refdef.fograngerecip;
9599 rsurface.fogheightfade = r_refdef.fogheightfade;
9600 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
9601 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9602 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9603 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9604 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9605 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9606 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9607 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
9608 rsurface.colormod[3] = 1;
9609 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);
9610 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9611 rsurface.frameblend[0].lerp = 1;
9612 rsurface.ent_alttextures = false;
9613 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9614 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9615 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9616 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9617 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9618 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9619 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9620 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9621 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9622 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9623 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9624 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9625 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9626 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9627 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9628 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9629 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9630 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9631 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9632 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9633 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9634 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9635 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9636 rsurface.modelelement3i = model->surfmesh.data_element3i;
9637 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9638 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9639 rsurface.modelelement3s = model->surfmesh.data_element3s;
9640 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9641 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9642 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9643 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9644 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9645 rsurface.modelsurfaces = model->data_surfaces;
9646 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9647 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9648 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9649 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9650 rsurface.modelgeneratedvertex = false;
9651 rsurface.batchgeneratedvertex = false;
9652 rsurface.batchfirstvertex = 0;
9653 rsurface.batchnumvertices = 0;
9654 rsurface.batchfirsttriangle = 0;
9655 rsurface.batchnumtriangles = 0;
9656 rsurface.batchvertex3f = NULL;
9657 rsurface.batchvertex3f_vertexbuffer = NULL;
9658 rsurface.batchvertex3f_bufferoffset = 0;
9659 rsurface.batchsvector3f = NULL;
9660 rsurface.batchsvector3f_vertexbuffer = NULL;
9661 rsurface.batchsvector3f_bufferoffset = 0;
9662 rsurface.batchtvector3f = NULL;
9663 rsurface.batchtvector3f_vertexbuffer = NULL;
9664 rsurface.batchtvector3f_bufferoffset = 0;
9665 rsurface.batchnormal3f = NULL;
9666 rsurface.batchnormal3f_vertexbuffer = NULL;
9667 rsurface.batchnormal3f_bufferoffset = 0;
9668 rsurface.batchlightmapcolor4f = NULL;
9669 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9670 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9671 rsurface.batchtexcoordtexture2f = NULL;
9672 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9673 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9674 rsurface.batchtexcoordlightmap2f = NULL;
9675 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9676 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9677 rsurface.batchvertexmesh = NULL;
9678 rsurface.batchvertexmeshbuffer = NULL;
9679 rsurface.batchvertexposition = NULL;
9680 rsurface.batchvertexpositionbuffer = NULL;
9681 rsurface.batchelement3i = NULL;
9682 rsurface.batchelement3i_indexbuffer = NULL;
9683 rsurface.batchelement3i_bufferoffset = 0;
9684 rsurface.batchelement3s = NULL;
9685 rsurface.batchelement3s_indexbuffer = NULL;
9686 rsurface.batchelement3s_bufferoffset = 0;
9687 rsurface.passcolor4f = NULL;
9688 rsurface.passcolor4f_vertexbuffer = NULL;
9689 rsurface.passcolor4f_bufferoffset = 0;
9692 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
9694 dp_model_t *model = ent->model;
9695 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
9697 rsurface.entity = (entity_render_t *)ent;
9698 rsurface.skeleton = ent->skeleton;
9699 rsurface.ent_skinnum = ent->skinnum;
9700 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;
9701 rsurface.ent_shadertime = ent->shadertime;
9702 rsurface.ent_flags = ent->flags;
9703 if (rsurface.array_size < model->surfmesh.num_vertices)
9704 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9705 rsurface.matrix = ent->matrix;
9706 rsurface.inversematrix = ent->inversematrix;
9707 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9708 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9709 R_EntityMatrix(&rsurface.matrix);
9710 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9711 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9712 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9713 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
9714 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
9715 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9716 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
9717 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
9718 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
9719 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
9720 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
9721 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
9722 rsurface.colormod[3] = ent->alpha;
9723 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
9724 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
9725 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
9726 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9727 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9728 if (ent->model->brush.submodel && !prepass)
9730 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
9731 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
9733 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
9735 if (ent->animcache_vertex3f && !r_framedata_failed)
9737 rsurface.modelvertex3f = ent->animcache_vertex3f;
9738 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
9739 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
9740 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
9741 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
9742 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
9743 rsurface.modelvertexposition = ent->animcache_vertexposition;
9744 rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
9746 else if (wanttangents)
9748 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9749 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
9750 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
9751 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9752 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
9753 rsurface.modelvertexmesh = NULL;
9754 rsurface.modelvertexmeshbuffer = NULL;
9755 rsurface.modelvertexposition = NULL;
9756 rsurface.modelvertexpositionbuffer = NULL;
9758 else if (wantnormals)
9760 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9761 rsurface.modelsvector3f = NULL;
9762 rsurface.modeltvector3f = NULL;
9763 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9764 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
9765 rsurface.modelvertexmesh = NULL;
9766 rsurface.modelvertexmeshbuffer = NULL;
9767 rsurface.modelvertexposition = NULL;
9768 rsurface.modelvertexpositionbuffer = NULL;
9772 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9773 rsurface.modelsvector3f = NULL;
9774 rsurface.modeltvector3f = NULL;
9775 rsurface.modelnormal3f = NULL;
9776 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
9777 rsurface.modelvertexmesh = NULL;
9778 rsurface.modelvertexmeshbuffer = NULL;
9779 rsurface.modelvertexposition = NULL;
9780 rsurface.modelvertexpositionbuffer = NULL;
9782 rsurface.modelvertex3f_vertexbuffer = 0;
9783 rsurface.modelvertex3f_bufferoffset = 0;
9784 rsurface.modelsvector3f_vertexbuffer = 0;
9785 rsurface.modelsvector3f_bufferoffset = 0;
9786 rsurface.modeltvector3f_vertexbuffer = 0;
9787 rsurface.modeltvector3f_bufferoffset = 0;
9788 rsurface.modelnormal3f_vertexbuffer = 0;
9789 rsurface.modelnormal3f_bufferoffset = 0;
9790 rsurface.modelgeneratedvertex = true;
9794 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9795 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9796 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9797 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9798 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9799 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9800 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9801 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9802 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9803 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9804 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9805 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9806 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9807 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9808 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9809 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9810 rsurface.modelgeneratedvertex = false;
9812 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9813 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9814 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9815 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9816 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9817 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9818 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9819 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9820 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9821 rsurface.modelelement3i = model->surfmesh.data_element3i;
9822 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9823 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9824 rsurface.modelelement3s = model->surfmesh.data_element3s;
9825 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9826 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9827 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9828 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9829 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9830 rsurface.modelsurfaces = model->data_surfaces;
9831 rsurface.batchgeneratedvertex = false;
9832 rsurface.batchfirstvertex = 0;
9833 rsurface.batchnumvertices = 0;
9834 rsurface.batchfirsttriangle = 0;
9835 rsurface.batchnumtriangles = 0;
9836 rsurface.batchvertex3f = NULL;
9837 rsurface.batchvertex3f_vertexbuffer = NULL;
9838 rsurface.batchvertex3f_bufferoffset = 0;
9839 rsurface.batchsvector3f = NULL;
9840 rsurface.batchsvector3f_vertexbuffer = NULL;
9841 rsurface.batchsvector3f_bufferoffset = 0;
9842 rsurface.batchtvector3f = NULL;
9843 rsurface.batchtvector3f_vertexbuffer = NULL;
9844 rsurface.batchtvector3f_bufferoffset = 0;
9845 rsurface.batchnormal3f = NULL;
9846 rsurface.batchnormal3f_vertexbuffer = NULL;
9847 rsurface.batchnormal3f_bufferoffset = 0;
9848 rsurface.batchlightmapcolor4f = NULL;
9849 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9850 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9851 rsurface.batchtexcoordtexture2f = NULL;
9852 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9853 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9854 rsurface.batchtexcoordlightmap2f = NULL;
9855 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9856 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9857 rsurface.batchvertexmesh = NULL;
9858 rsurface.batchvertexmeshbuffer = NULL;
9859 rsurface.batchvertexposition = NULL;
9860 rsurface.batchvertexpositionbuffer = NULL;
9861 rsurface.batchelement3i = NULL;
9862 rsurface.batchelement3i_indexbuffer = NULL;
9863 rsurface.batchelement3i_bufferoffset = 0;
9864 rsurface.batchelement3s = NULL;
9865 rsurface.batchelement3s_indexbuffer = NULL;
9866 rsurface.batchelement3s_bufferoffset = 0;
9867 rsurface.passcolor4f = NULL;
9868 rsurface.passcolor4f_vertexbuffer = NULL;
9869 rsurface.passcolor4f_bufferoffset = 0;
9872 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)
9876 rsurface.entity = r_refdef.scene.worldentity;
9877 rsurface.skeleton = NULL;
9878 rsurface.ent_skinnum = 0;
9879 rsurface.ent_qwskin = -1;
9880 rsurface.ent_shadertime = shadertime;
9881 rsurface.ent_flags = entflags;
9882 rsurface.modelnumvertices = numvertices;
9883 rsurface.modelnumtriangles = numtriangles;
9884 if (rsurface.array_size < rsurface.modelnumvertices)
9885 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
9886 rsurface.matrix = *matrix;
9887 rsurface.inversematrix = *inversematrix;
9888 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9889 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9890 R_EntityMatrix(&rsurface.matrix);
9891 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9892 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9893 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9894 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
9895 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
9896 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9897 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9898 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9899 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9900 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9901 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9902 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
9903 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);
9904 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9905 rsurface.frameblend[0].lerp = 1;
9906 rsurface.ent_alttextures = false;
9907 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9908 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9911 rsurface.modelvertex3f = vertex3f;
9912 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
9913 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
9914 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
9916 else if (wantnormals)
9918 rsurface.modelvertex3f = vertex3f;
9919 rsurface.modelsvector3f = NULL;
9920 rsurface.modeltvector3f = NULL;
9921 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
9925 rsurface.modelvertex3f = vertex3f;
9926 rsurface.modelsvector3f = NULL;
9927 rsurface.modeltvector3f = NULL;
9928 rsurface.modelnormal3f = NULL;
9930 rsurface.modelvertexmesh = NULL;
9931 rsurface.modelvertexmeshbuffer = NULL;
9932 rsurface.modelvertexposition = NULL;
9933 rsurface.modelvertexpositionbuffer = NULL;
9934 rsurface.modelvertex3f_vertexbuffer = 0;
9935 rsurface.modelvertex3f_bufferoffset = 0;
9936 rsurface.modelsvector3f_vertexbuffer = 0;
9937 rsurface.modelsvector3f_bufferoffset = 0;
9938 rsurface.modeltvector3f_vertexbuffer = 0;
9939 rsurface.modeltvector3f_bufferoffset = 0;
9940 rsurface.modelnormal3f_vertexbuffer = 0;
9941 rsurface.modelnormal3f_bufferoffset = 0;
9942 rsurface.modelgeneratedvertex = true;
9943 rsurface.modellightmapcolor4f = color4f;
9944 rsurface.modellightmapcolor4f_vertexbuffer = 0;
9945 rsurface.modellightmapcolor4f_bufferoffset = 0;
9946 rsurface.modeltexcoordtexture2f = texcoord2f;
9947 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
9948 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
9949 rsurface.modeltexcoordlightmap2f = NULL;
9950 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
9951 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
9952 rsurface.modelelement3i = element3i;
9953 rsurface.modelelement3i_indexbuffer = NULL;
9954 rsurface.modelelement3i_bufferoffset = 0;
9955 rsurface.modelelement3s = element3s;
9956 rsurface.modelelement3s_indexbuffer = NULL;
9957 rsurface.modelelement3s_bufferoffset = 0;
9958 rsurface.modellightmapoffsets = NULL;
9959 rsurface.modelsurfaces = NULL;
9960 rsurface.batchgeneratedvertex = false;
9961 rsurface.batchfirstvertex = 0;
9962 rsurface.batchnumvertices = 0;
9963 rsurface.batchfirsttriangle = 0;
9964 rsurface.batchnumtriangles = 0;
9965 rsurface.batchvertex3f = NULL;
9966 rsurface.batchvertex3f_vertexbuffer = NULL;
9967 rsurface.batchvertex3f_bufferoffset = 0;
9968 rsurface.batchsvector3f = NULL;
9969 rsurface.batchsvector3f_vertexbuffer = NULL;
9970 rsurface.batchsvector3f_bufferoffset = 0;
9971 rsurface.batchtvector3f = NULL;
9972 rsurface.batchtvector3f_vertexbuffer = NULL;
9973 rsurface.batchtvector3f_bufferoffset = 0;
9974 rsurface.batchnormal3f = NULL;
9975 rsurface.batchnormal3f_vertexbuffer = NULL;
9976 rsurface.batchnormal3f_bufferoffset = 0;
9977 rsurface.batchlightmapcolor4f = NULL;
9978 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9979 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9980 rsurface.batchtexcoordtexture2f = NULL;
9981 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9982 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9983 rsurface.batchtexcoordlightmap2f = NULL;
9984 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9985 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9986 rsurface.batchvertexmesh = NULL;
9987 rsurface.batchvertexmeshbuffer = NULL;
9988 rsurface.batchvertexposition = NULL;
9989 rsurface.batchvertexpositionbuffer = NULL;
9990 rsurface.batchelement3i = NULL;
9991 rsurface.batchelement3i_indexbuffer = NULL;
9992 rsurface.batchelement3i_bufferoffset = 0;
9993 rsurface.batchelement3s = NULL;
9994 rsurface.batchelement3s_indexbuffer = NULL;
9995 rsurface.batchelement3s_bufferoffset = 0;
9996 rsurface.passcolor4f = NULL;
9997 rsurface.passcolor4f_vertexbuffer = NULL;
9998 rsurface.passcolor4f_bufferoffset = 0;
10000 if (rsurface.modelnumvertices && rsurface.modelelement3i)
10002 if ((wantnormals || wanttangents) && !normal3f)
10004 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10005 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10007 if (wanttangents && !svector3f)
10009 Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f, r_smoothnormals_areaweighting.integer != 0);
10010 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10011 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10015 // now convert arrays into vertexmesh structs
10016 for (i = 0;i < numvertices;i++)
10018 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
10019 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
10020 if (rsurface.modelsvector3f)
10021 VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
10022 if (rsurface.modeltvector3f)
10023 VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
10024 if (rsurface.modelnormal3f)
10025 VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
10026 if (rsurface.modellightmapcolor4f)
10027 Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
10028 if (rsurface.modeltexcoordtexture2f)
10029 Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
10030 if (rsurface.modeltexcoordlightmap2f)
10031 Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
10035 float RSurf_FogPoint(const float *v)
10037 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10038 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10039 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10040 float FogHeightFade = r_refdef.fogheightfade;
10042 unsigned int fogmasktableindex;
10043 if (r_refdef.fogplaneviewabove)
10044 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10046 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10047 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10048 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10051 float RSurf_FogVertex(const float *v)
10053 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10054 float FogPlaneViewDist = rsurface.fogplaneviewdist;
10055 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10056 float FogHeightFade = rsurface.fogheightfade;
10058 unsigned int fogmasktableindex;
10059 if (r_refdef.fogplaneviewabove)
10060 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10062 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10063 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10064 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10067 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10070 for (i = 0;i < numelements;i++)
10071 outelement3i[i] = inelement3i[i] + adjust;
10074 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10075 extern cvar_t gl_vbo;
10076 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10084 int surfacefirsttriangle;
10085 int surfacenumtriangles;
10086 int surfacefirstvertex;
10087 int surfaceendvertex;
10088 int surfacenumvertices;
10089 int surfaceadjustvertex;
10093 qboolean dynamicvertex;
10097 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10098 float waveparms[4];
10099 q3shaderinfo_deform_t *deform;
10100 const msurface_t *surface, *firstsurface;
10101 r_vertexposition_t *vertexposition;
10102 r_vertexmesh_t *vertexmesh;
10103 if (!texturenumsurfaces)
10105 // find vertex range of this surface batch
10107 firstsurface = texturesurfacelist[0];
10108 firsttriangle = firstsurface->num_firsttriangle;
10110 firstvertex = endvertex = firstsurface->num_firstvertex;
10111 for (i = 0;i < texturenumsurfaces;i++)
10113 surface = texturesurfacelist[i];
10114 if (surface != firstsurface + i)
10116 surfacefirstvertex = surface->num_firstvertex;
10117 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10118 surfacenumtriangles = surface->num_triangles;
10119 if (firstvertex > surfacefirstvertex)
10120 firstvertex = surfacefirstvertex;
10121 if (endvertex < surfaceendvertex)
10122 endvertex = surfaceendvertex;
10123 numtriangles += surfacenumtriangles;
10128 // we now know the vertex range used, and if there are any gaps in it
10129 rsurface.batchfirstvertex = firstvertex;
10130 rsurface.batchnumvertices = endvertex - firstvertex;
10131 rsurface.batchfirsttriangle = firsttriangle;
10132 rsurface.batchnumtriangles = numtriangles;
10134 // this variable holds flags for which properties have been updated that
10135 // may require regenerating vertexmesh or vertexposition arrays...
10138 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10139 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
10140 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10142 switch (deform->deform)
10145 case Q3DEFORM_PROJECTIONSHADOW:
10146 case Q3DEFORM_TEXT0:
10147 case Q3DEFORM_TEXT1:
10148 case Q3DEFORM_TEXT2:
10149 case Q3DEFORM_TEXT3:
10150 case Q3DEFORM_TEXT4:
10151 case Q3DEFORM_TEXT5:
10152 case Q3DEFORM_TEXT6:
10153 case Q3DEFORM_TEXT7:
10154 case Q3DEFORM_NONE:
10156 case Q3DEFORM_AUTOSPRITE:
10157 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10158 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10160 case Q3DEFORM_AUTOSPRITE2:
10161 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10162 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10164 case Q3DEFORM_NORMAL:
10165 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10166 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10168 case Q3DEFORM_WAVE:
10169 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10170 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10172 case Q3DEFORM_BULGE:
10173 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10174 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10176 case Q3DEFORM_MOVE:
10177 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10178 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
10182 switch(rsurface.texture->tcgen.tcgen)
10185 case Q3TCGEN_TEXTURE:
10187 case Q3TCGEN_LIGHTMAP:
10188 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
10189 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
10191 case Q3TCGEN_VECTOR:
10192 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10193 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10195 case Q3TCGEN_ENVIRONMENT:
10196 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
10197 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10200 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10202 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10203 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10206 // check if any dynamic vertex processing must occur
10207 dynamicvertex = false;
10209 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10211 dynamicvertex = true;
10212 batchneed |= BATCHNEED_NOGAPS;
10213 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
10216 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
10218 dynamicvertex = true;
10219 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10220 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
10223 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
10225 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
10226 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
10227 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
10228 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
10229 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
10230 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
10231 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
10234 // when the model data has no vertex buffer (dynamic mesh), we need to
10236 if (!rsurface.modelvertexmeshbuffer || (!gl_vbo.integer && !vid.forcevbo))
10237 batchneed |= BATCHNEED_NOGAPS;
10239 // if needsupdate, we have to do a dynamic vertex batch for sure
10240 if (needsupdate & batchneed)
10241 dynamicvertex = true;
10243 // see if we need to build vertexmesh from arrays
10244 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10245 dynamicvertex = true;
10247 // see if we need to build vertexposition from arrays
10248 if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
10249 dynamicvertex = true;
10251 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
10252 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
10253 dynamicvertex = true;
10255 // if there is a chance of animated vertex colors, it's a dynamic batch
10256 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10257 dynamicvertex = true;
10259 rsurface.batchvertex3f = rsurface.modelvertex3f;
10260 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
10261 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10262 rsurface.batchsvector3f = rsurface.modelsvector3f;
10263 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
10264 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10265 rsurface.batchtvector3f = rsurface.modeltvector3f;
10266 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
10267 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10268 rsurface.batchnormal3f = rsurface.modelnormal3f;
10269 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
10270 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10271 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
10272 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
10273 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
10274 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
10275 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
10276 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
10277 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
10278 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
10279 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
10280 rsurface.batchvertexposition = rsurface.modelvertexposition;
10281 rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
10282 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
10283 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
10284 rsurface.batchelement3i = rsurface.modelelement3i;
10285 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
10286 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
10287 rsurface.batchelement3s = rsurface.modelelement3s;
10288 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
10289 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
10291 // if any dynamic vertex processing has to occur in software, we copy the
10292 // entire surface list together before processing to rebase the vertices
10293 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
10295 // if any gaps exist and we do not have a static vertex buffer, we have to
10296 // copy the surface list together to avoid wasting upload bandwidth on the
10297 // vertices in the gaps.
10299 // if gaps exist and we have a static vertex buffer, we still have to
10300 // combine the index buffer ranges into one dynamic index buffer.
10302 // in all cases we end up with data that can be drawn in one call.
10304 if (!dynamicvertex)
10306 // static vertex data, just set pointers...
10307 rsurface.batchgeneratedvertex = false;
10308 // if there are gaps, we want to build a combined index buffer,
10309 // otherwise use the original static buffer with an appropriate offset
10314 for (i = 0;i < texturenumsurfaces;i++)
10316 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10317 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10318 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
10319 numtriangles += surfacenumtriangles;
10321 rsurface.batchelement3i = rsurface.array_batchelement3i;
10322 rsurface.batchelement3i_indexbuffer = NULL;
10323 rsurface.batchelement3i_bufferoffset = 0;
10324 rsurface.batchelement3s = NULL;
10325 rsurface.batchelement3s_indexbuffer = NULL;
10326 rsurface.batchelement3s_bufferoffset = 0;
10327 if (endvertex <= 65536)
10329 rsurface.batchelement3s = rsurface.array_batchelement3s;
10330 for (i = 0;i < numtriangles*3;i++)
10331 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10333 rsurface.batchfirsttriangle = firsttriangle;
10334 rsurface.batchnumtriangles = numtriangles;
10339 // something needs software processing, do it for real...
10340 // we only directly handle interleaved array data in this case...
10341 rsurface.batchgeneratedvertex = true;
10343 // now copy the vertex data into a combined array and make an index array
10344 // (this is what Quake3 does all the time)
10345 //if (gaps || rsurface.batchfirstvertex)
10347 rsurface.batchvertexposition = NULL;
10348 rsurface.batchvertexpositionbuffer = NULL;
10349 rsurface.batchvertexmesh = NULL;
10350 rsurface.batchvertexmeshbuffer = NULL;
10351 rsurface.batchvertex3f = NULL;
10352 rsurface.batchvertex3f_vertexbuffer = NULL;
10353 rsurface.batchvertex3f_bufferoffset = 0;
10354 rsurface.batchsvector3f = NULL;
10355 rsurface.batchsvector3f_vertexbuffer = NULL;
10356 rsurface.batchsvector3f_bufferoffset = 0;
10357 rsurface.batchtvector3f = NULL;
10358 rsurface.batchtvector3f_vertexbuffer = NULL;
10359 rsurface.batchtvector3f_bufferoffset = 0;
10360 rsurface.batchnormal3f = NULL;
10361 rsurface.batchnormal3f_vertexbuffer = NULL;
10362 rsurface.batchnormal3f_bufferoffset = 0;
10363 rsurface.batchlightmapcolor4f = NULL;
10364 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10365 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10366 rsurface.batchtexcoordtexture2f = NULL;
10367 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10368 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10369 rsurface.batchtexcoordlightmap2f = NULL;
10370 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10371 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10372 rsurface.batchelement3i = rsurface.array_batchelement3i;
10373 rsurface.batchelement3i_indexbuffer = NULL;
10374 rsurface.batchelement3i_bufferoffset = 0;
10375 rsurface.batchelement3s = NULL;
10376 rsurface.batchelement3s_indexbuffer = NULL;
10377 rsurface.batchelement3s_bufferoffset = 0;
10378 // we'll only be setting up certain arrays as needed
10379 if (batchneed & BATCHNEED_VERTEXPOSITION)
10380 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
10381 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10382 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10383 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10384 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10385 if (batchneed & BATCHNEED_ARRAY_NORMAL)
10386 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10387 if (batchneed & BATCHNEED_ARRAY_VECTOR)
10389 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10390 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10392 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
10393 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10394 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
10395 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10396 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
10397 rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
10400 for (i = 0;i < texturenumsurfaces;i++)
10402 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
10403 surfacenumvertices = texturesurfacelist[i]->num_vertices;
10404 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10405 surfaceadjustvertex = numvertices - surfacefirstvertex;
10406 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10407 // copy only the data requested
10408 if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
10409 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
10410 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
10411 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
10412 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
10414 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10415 memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10416 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
10417 memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10418 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
10420 memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10421 memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10423 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
10424 memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
10425 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
10426 memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10427 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
10428 memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10430 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
10431 numvertices += surfacenumvertices;
10432 numtriangles += surfacenumtriangles;
10435 // generate a 16bit index array as well if possible
10436 // (in general, dynamic batches fit)
10437 if (numvertices <= 65536)
10439 rsurface.batchelement3s = rsurface.array_batchelement3s;
10440 for (i = 0;i < numtriangles*3;i++)
10441 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10444 // since we've copied everything, the batch now starts at 0
10445 rsurface.batchfirstvertex = 0;
10446 rsurface.batchnumvertices = numvertices;
10447 rsurface.batchfirsttriangle = 0;
10448 rsurface.batchnumtriangles = numtriangles;
10451 // q1bsp surfaces rendered in vertex color mode have to have colors
10452 // calculated based on lightstyles
10453 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10455 // generate color arrays for the surfaces in this list
10459 const int *offsets;
10460 const unsigned char *lm;
10462 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10463 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10464 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10465 for (i = 0;i < texturenumsurfaces;i++)
10467 surface = texturesurfacelist[i];
10468 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
10469 surfacenumvertices = surface->num_vertices;
10470 if (surface->lightmapinfo->samples)
10472 for (j = 0;j < surfacenumvertices;j++)
10474 lm = surface->lightmapinfo->samples + offsets[j];
10475 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
10476 VectorScale(lm, scale, c);
10477 if (surface->lightmapinfo->styles[1] != 255)
10479 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
10481 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
10482 VectorMA(c, scale, lm, c);
10483 if (surface->lightmapinfo->styles[2] != 255)
10486 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
10487 VectorMA(c, scale, lm, c);
10488 if (surface->lightmapinfo->styles[3] != 255)
10491 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
10492 VectorMA(c, scale, lm, c);
10499 Vector4Set(rsurface.array_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);
10505 for (j = 0;j < surfacenumvertices;j++)
10507 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
10514 // if vertices are deformed (sprite flares and things in maps, possibly
10515 // water waves, bulges and other deformations), modify the copied vertices
10517 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10519 switch (deform->deform)
10522 case Q3DEFORM_PROJECTIONSHADOW:
10523 case Q3DEFORM_TEXT0:
10524 case Q3DEFORM_TEXT1:
10525 case Q3DEFORM_TEXT2:
10526 case Q3DEFORM_TEXT3:
10527 case Q3DEFORM_TEXT4:
10528 case Q3DEFORM_TEXT5:
10529 case Q3DEFORM_TEXT6:
10530 case Q3DEFORM_TEXT7:
10531 case Q3DEFORM_NONE:
10533 case Q3DEFORM_AUTOSPRITE:
10534 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10535 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10536 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10537 VectorNormalize(newforward);
10538 VectorNormalize(newright);
10539 VectorNormalize(newup);
10540 // a single autosprite surface can contain multiple sprites...
10541 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10543 VectorClear(center);
10544 for (i = 0;i < 4;i++)
10545 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10546 VectorScale(center, 0.25f, center);
10547 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
10548 VectorCopy(rsurface.batchsvector3f + 3*j, right);
10549 VectorCopy(rsurface.batchtvector3f + 3*j, up);
10550 for (i = 0;i < 4;i++)
10552 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
10553 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
10556 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10557 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10558 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10559 rsurface.batchvertex3f_vertexbuffer = NULL;
10560 rsurface.batchvertex3f_bufferoffset = 0;
10561 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10562 rsurface.batchsvector3f_vertexbuffer = NULL;
10563 rsurface.batchsvector3f_bufferoffset = 0;
10564 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10565 rsurface.batchtvector3f_vertexbuffer = NULL;
10566 rsurface.batchtvector3f_bufferoffset = 0;
10567 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10568 rsurface.batchnormal3f_vertexbuffer = NULL;
10569 rsurface.batchnormal3f_bufferoffset = 0;
10571 case Q3DEFORM_AUTOSPRITE2:
10572 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10573 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10574 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10575 VectorNormalize(newforward);
10576 VectorNormalize(newright);
10577 VectorNormalize(newup);
10579 const float *v1, *v2;
10589 memset(shortest, 0, sizeof(shortest));
10590 // a single autosprite surface can contain multiple sprites...
10591 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10593 VectorClear(center);
10594 for (i = 0;i < 4;i++)
10595 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10596 VectorScale(center, 0.25f, center);
10597 // find the two shortest edges, then use them to define the
10598 // axis vectors for rotating around the central axis
10599 for (i = 0;i < 6;i++)
10601 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
10602 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
10603 l = VectorDistance2(v1, v2);
10604 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
10605 if (v1[2] != v2[2])
10606 l += (1.0f / 1024.0f);
10607 if (shortest[0].length2 > l || i == 0)
10609 shortest[1] = shortest[0];
10610 shortest[0].length2 = l;
10611 shortest[0].v1 = v1;
10612 shortest[0].v2 = v2;
10614 else if (shortest[1].length2 > l || i == 1)
10616 shortest[1].length2 = l;
10617 shortest[1].v1 = v1;
10618 shortest[1].v2 = v2;
10621 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
10622 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
10623 // this calculates the right vector from the shortest edge
10624 // and the up vector from the edge midpoints
10625 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
10626 VectorNormalize(right);
10627 VectorSubtract(end, start, up);
10628 VectorNormalize(up);
10629 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
10630 VectorSubtract(rsurface.localvieworigin, center, forward);
10631 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
10632 VectorNegate(forward, forward);
10633 VectorReflect(forward, 0, up, forward);
10634 VectorNormalize(forward);
10635 CrossProduct(up, forward, newright);
10636 VectorNormalize(newright);
10637 // rotate the quad around the up axis vector, this is made
10638 // especially easy by the fact we know the quad is flat,
10639 // so we only have to subtract the center position and
10640 // measure distance along the right vector, and then
10641 // multiply that by the newright vector and add back the
10643 // we also need to subtract the old position to undo the
10644 // displacement from the center, which we do with a
10645 // DotProduct, the subtraction/addition of center is also
10646 // optimized into DotProducts here
10647 l = DotProduct(right, center);
10648 for (i = 0;i < 4;i++)
10650 v1 = rsurface.batchvertex3f + 3*(j+i);
10651 f = DotProduct(right, v1) - l;
10652 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
10656 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10657 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10658 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10659 rsurface.batchvertex3f_vertexbuffer = NULL;
10660 rsurface.batchvertex3f_bufferoffset = 0;
10661 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10662 rsurface.batchsvector3f_vertexbuffer = NULL;
10663 rsurface.batchsvector3f_bufferoffset = 0;
10664 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10665 rsurface.batchtvector3f_vertexbuffer = NULL;
10666 rsurface.batchtvector3f_bufferoffset = 0;
10667 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10668 rsurface.batchnormal3f_vertexbuffer = NULL;
10669 rsurface.batchnormal3f_bufferoffset = 0;
10671 case Q3DEFORM_NORMAL:
10672 // deform the normals to make reflections wavey
10673 for (j = 0;j < rsurface.batchnumvertices;j++)
10676 float *normal = rsurface.array_batchnormal3f + 3*j;
10677 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
10678 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10679 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]);
10680 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]);
10681 VectorNormalize(normal);
10683 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10684 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10685 rsurface.batchsvector3f_vertexbuffer = NULL;
10686 rsurface.batchsvector3f_bufferoffset = 0;
10687 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10688 rsurface.batchtvector3f_vertexbuffer = NULL;
10689 rsurface.batchtvector3f_bufferoffset = 0;
10690 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10691 rsurface.batchnormal3f_vertexbuffer = NULL;
10692 rsurface.batchnormal3f_bufferoffset = 0;
10694 case Q3DEFORM_WAVE:
10695 // deform vertex array to make wavey water and flags and such
10696 waveparms[0] = deform->waveparms[0];
10697 waveparms[1] = deform->waveparms[1];
10698 waveparms[2] = deform->waveparms[2];
10699 waveparms[3] = deform->waveparms[3];
10700 // this is how a divisor of vertex influence on deformation
10701 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
10702 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10703 for (j = 0;j < rsurface.batchnumvertices;j++)
10705 // if the wavefunc depends on time, evaluate it per-vertex
10708 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
10709 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10711 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10713 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10714 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10715 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10716 rsurface.batchvertex3f_vertexbuffer = NULL;
10717 rsurface.batchvertex3f_bufferoffset = 0;
10718 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10719 rsurface.batchsvector3f_vertexbuffer = NULL;
10720 rsurface.batchsvector3f_bufferoffset = 0;
10721 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10722 rsurface.batchtvector3f_vertexbuffer = NULL;
10723 rsurface.batchtvector3f_bufferoffset = 0;
10724 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10725 rsurface.batchnormal3f_vertexbuffer = NULL;
10726 rsurface.batchnormal3f_bufferoffset = 0;
10728 case Q3DEFORM_BULGE:
10729 // deform vertex array to make the surface have moving bulges
10730 for (j = 0;j < rsurface.batchnumvertices;j++)
10732 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
10733 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10735 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10736 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.array_batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchsvector3f, rsurface.array_batchtvector3f, true);
10737 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10738 rsurface.batchvertex3f_vertexbuffer = NULL;
10739 rsurface.batchvertex3f_bufferoffset = 0;
10740 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10741 rsurface.batchsvector3f_vertexbuffer = NULL;
10742 rsurface.batchsvector3f_bufferoffset = 0;
10743 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10744 rsurface.batchtvector3f_vertexbuffer = NULL;
10745 rsurface.batchtvector3f_bufferoffset = 0;
10746 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10747 rsurface.batchnormal3f_vertexbuffer = NULL;
10748 rsurface.batchnormal3f_bufferoffset = 0;
10750 case Q3DEFORM_MOVE:
10751 // deform vertex array
10752 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
10753 VectorScale(deform->parms, scale, waveparms);
10754 for (j = 0;j < rsurface.batchnumvertices;j++)
10755 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
10756 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10757 rsurface.batchvertex3f_vertexbuffer = NULL;
10758 rsurface.batchvertex3f_bufferoffset = 0;
10763 // generate texcoords based on the chosen texcoord source
10764 switch(rsurface.texture->tcgen.tcgen)
10767 case Q3TCGEN_TEXTURE:
10769 case Q3TCGEN_LIGHTMAP:
10770 if (rsurface.batchtexcoordlightmap2f)
10771 memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
10772 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10773 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10774 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10776 case Q3TCGEN_VECTOR:
10777 for (j = 0;j < rsurface.batchnumvertices;j++)
10779 rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
10780 rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
10782 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10783 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10784 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10786 case Q3TCGEN_ENVIRONMENT:
10787 // make environment reflections using a spheremap
10788 for (j = 0;j < rsurface.batchnumvertices;j++)
10790 // identical to Q3A's method, but executed in worldspace so
10791 // carried models can be shiny too
10793 float viewer[3], d, reflected[3], worldreflected[3];
10795 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
10796 // VectorNormalize(viewer);
10798 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
10800 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
10801 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
10802 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
10803 // note: this is proportinal to viewer, so we can normalize later
10805 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
10806 VectorNormalize(worldreflected);
10808 // note: this sphere map only uses world x and z!
10809 // so positive and negative y will LOOK THE SAME.
10810 rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
10811 rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
10813 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10814 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10815 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10818 // the only tcmod that needs software vertex processing is turbulent, so
10819 // check for it here and apply the changes if needed
10820 // and we only support that as the first one
10821 // (handling a mixture of turbulent and other tcmods would be problematic
10822 // without punting it entirely to a software path)
10823 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10825 amplitude = rsurface.texture->tcmods[0].parms[1];
10826 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
10827 for (j = 0;j < rsurface.batchnumvertices;j++)
10829 rsurface.array_batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10830 rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10832 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10833 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10834 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10837 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10839 // convert the modified arrays to vertex structs
10840 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10841 rsurface.batchvertexmeshbuffer = NULL;
10842 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
10843 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10844 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
10845 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
10846 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10847 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
10848 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
10850 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10852 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
10853 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
10856 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
10857 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10858 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
10859 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
10860 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10861 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
10862 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
10863 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10864 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
10867 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
10869 // convert the modified arrays to vertex structs
10870 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
10871 rsurface.batchvertexpositionbuffer = NULL;
10872 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
10873 memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
10875 for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
10876 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
10880 void RSurf_DrawBatch(void)
10882 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);
10885 static void RSurf_BindLightmapForBatch(void)
10887 switch(vid.renderpath)
10889 case RENDERPATH_CGGL:
10891 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture );CHECKCGERROR
10892 if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, rsurface.deluxemaptexture);CHECKCGERROR
10895 case RENDERPATH_GL20:
10896 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture );
10897 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, rsurface.deluxemaptexture);
10899 case RENDERPATH_GL13:
10900 case RENDERPATH_GL11:
10901 R_Mesh_TexBind(0, rsurface.lightmaptexture);
10906 static void RSurf_BindReflectionForBatch(void)
10908 // pick the closest matching water plane and bind textures
10909 int planeindex, vertexindex;
10913 r_waterstate_waterplane_t *p, *bestp;
10916 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
10918 if(p->camera_entity != rsurface.texture->camera_entity)
10921 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
10923 Matrix4x4_Transform(&rsurface.matrix, v, vert);
10924 d += fabs(PlaneDiff(vert, &p->plane));
10926 if (bestd > d || !bestp)
10932 switch(vid.renderpath)
10934 case RENDERPATH_CGGL:
10936 if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
10937 else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
10938 if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
10941 case RENDERPATH_GL20:
10942 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
10943 else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
10944 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
10946 case RENDERPATH_GL13:
10947 case RENDERPATH_GL11:
10952 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
10955 for (i = 0;i < rsurface.batchnumvertices;i++)
10956 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
10957 rsurface.passcolor4f = rsurface.array_passcolor4f;
10958 rsurface.passcolor4f_vertexbuffer = 0;
10959 rsurface.passcolor4f_bufferoffset = 0;
10962 static void RSurf_DrawBatch_GL11_ApplyFog(void)
10969 if (rsurface.passcolor4f)
10971 // generate color arrays
10972 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
10974 f = RSurf_FogVertex(v);
10983 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
10985 f = RSurf_FogVertex(v);
10992 rsurface.passcolor4f = rsurface.array_passcolor4f;
10993 rsurface.passcolor4f_vertexbuffer = 0;
10994 rsurface.passcolor4f_bufferoffset = 0;
10997 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11004 if (!rsurface.passcolor4f)
11006 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
11008 f = RSurf_FogVertex(v);
11009 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11010 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11011 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11014 rsurface.passcolor4f = rsurface.array_passcolor4f;
11015 rsurface.passcolor4f_vertexbuffer = 0;
11016 rsurface.passcolor4f_bufferoffset = 0;
11019 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11024 if (!rsurface.passcolor4f)
11026 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11033 rsurface.passcolor4f = rsurface.array_passcolor4f;
11034 rsurface.passcolor4f_vertexbuffer = 0;
11035 rsurface.passcolor4f_bufferoffset = 0;
11038 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11043 if (!rsurface.passcolor4f)
11045 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11047 c2[0] = c[0] + r_refdef.scene.ambient;
11048 c2[1] = c[1] + r_refdef.scene.ambient;
11049 c2[2] = c[2] + r_refdef.scene.ambient;
11052 rsurface.passcolor4f = rsurface.array_passcolor4f;
11053 rsurface.passcolor4f_vertexbuffer = 0;
11054 rsurface.passcolor4f_bufferoffset = 0;
11057 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11060 rsurface.passcolor4f = NULL;
11061 rsurface.passcolor4f_vertexbuffer = 0;
11062 rsurface.passcolor4f_bufferoffset = 0;
11063 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11064 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11065 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11066 GL_Color(r, g, b, a);
11067 RSurf_BindLightmapForBatch();
11071 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11073 // TODO: optimize applyfog && applycolor case
11074 // just apply fog if necessary, and tint the fog color array if necessary
11075 rsurface.passcolor4f = NULL;
11076 rsurface.passcolor4f_vertexbuffer = 0;
11077 rsurface.passcolor4f_bufferoffset = 0;
11078 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11079 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11080 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11081 GL_Color(r, g, b, a);
11085 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11088 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11089 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11090 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11091 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11092 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11093 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11094 GL_Color(r, g, b, a);
11098 static void RSurf_DrawBatch_GL11_ClampColor(void)
11103 if (!rsurface.passcolor4f)
11105 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11107 c2[0] = bound(0.0f, c1[0], 1.0f);
11108 c2[1] = bound(0.0f, c1[1], 1.0f);
11109 c2[2] = bound(0.0f, c1[2], 1.0f);
11110 c2[3] = bound(0.0f, c1[3], 1.0f);
11114 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
11122 vec3_t ambientcolor;
11123 vec3_t diffusecolor;
11127 VectorCopy(rsurface.modellight_lightdir, lightdir);
11128 f = 0.5f * r_refdef.lightmapintensity;
11129 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11130 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11131 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11132 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11133 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11134 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11136 if (VectorLength2(diffusecolor) > 0)
11138 // q3-style directional shading
11139 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
11141 if ((f = DotProduct(n, lightdir)) > 0)
11142 VectorMA(ambientcolor, f, diffusecolor, c);
11144 VectorCopy(ambientcolor, c);
11151 rsurface.passcolor4f = rsurface.array_passcolor4f;
11152 rsurface.passcolor4f_vertexbuffer = 0;
11153 rsurface.passcolor4f_bufferoffset = 0;
11154 *applycolor = false;
11158 *r = ambientcolor[0];
11159 *g = ambientcolor[1];
11160 *b = ambientcolor[2];
11161 rsurface.passcolor4f = NULL;
11162 rsurface.passcolor4f_vertexbuffer = 0;
11163 rsurface.passcolor4f_bufferoffset = 0;
11167 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11169 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
11170 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11171 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11172 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11173 GL_Color(r, g, b, a);
11177 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
11183 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
11185 f = 1 - RSurf_FogVertex(v);
11193 void RSurf_SetupDepthAndCulling(void)
11195 // submodels are biased to avoid z-fighting with world surfaces that they
11196 // may be exactly overlapping (avoids z-fighting artifacts on certain
11197 // doors and things in Quake maps)
11198 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
11199 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
11200 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
11201 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11204 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11206 // transparent sky would be ridiculous
11207 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11209 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11210 skyrenderlater = true;
11211 RSurf_SetupDepthAndCulling();
11212 GL_DepthMask(true);
11213 // LordHavoc: HalfLife maps have freaky skypolys so don't use
11214 // skymasking on them, and Quake3 never did sky masking (unlike
11215 // software Quake and software Quake2), so disable the sky masking
11216 // in Quake3 maps as it causes problems with q3map2 sky tricks,
11217 // and skymasking also looks very bad when noclipping outside the
11218 // level, so don't use it then either.
11219 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
11221 R_Mesh_ResetTextureState();
11222 if (skyrendermasked)
11224 R_SetupShader_DepthOrShadow();
11225 // depth-only (masking)
11226 GL_ColorMask(0,0,0,0);
11227 // just to make sure that braindead drivers don't draw
11228 // anything despite that colormask...
11229 GL_BlendFunc(GL_ZERO, GL_ONE);
11230 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11231 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11235 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11237 GL_BlendFunc(GL_ONE, GL_ZERO);
11238 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
11239 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
11240 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
11243 if (skyrendermasked)
11244 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11246 R_Mesh_ResetTextureState();
11247 GL_Color(1, 1, 1, 1);
11250 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
11251 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
11252 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11254 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
11258 // render screenspace normalmap to texture
11259 GL_DepthMask(true);
11260 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist);
11263 else if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
11265 // render water or distortion background, then blend surface on top
11266 GL_DepthMask(true);
11267 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, texturenumsurfaces, texturesurfacelist);
11268 RSurf_BindReflectionForBatch();
11269 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11270 RSurf_BindLightmapForBatch();
11272 GL_DepthMask(false);
11273 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist);
11274 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11275 RSurf_BindLightmapForBatch();
11280 // render surface normally
11281 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11282 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist);
11283 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
11284 RSurf_BindReflectionForBatch();
11285 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11286 RSurf_BindLightmapForBatch();
11291 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11293 // OpenGL 1.3 path - anything not completely ancient
11294 qboolean applycolor;
11297 const texturelayer_t *layer;
11298 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);
11299 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11301 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11304 int layertexrgbscale;
11305 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11307 if (layerindex == 0)
11308 GL_AlphaTest(true);
11311 GL_AlphaTest(false);
11312 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11315 GL_DepthMask(layer->depthmask && writedepth);
11316 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11317 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
11319 layertexrgbscale = 4;
11320 VectorScale(layer->color, 0.25f, layercolor);
11322 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
11324 layertexrgbscale = 2;
11325 VectorScale(layer->color, 0.5f, layercolor);
11329 layertexrgbscale = 1;
11330 VectorScale(layer->color, 1.0f, layercolor);
11332 layercolor[3] = layer->color[3];
11333 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
11334 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11335 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11336 switch (layer->type)
11338 case TEXTURELAYERTYPE_LITTEXTURE:
11339 // single-pass lightmapped texture with 2x rgbscale
11340 R_Mesh_TexBind(0, r_texture_white);
11341 R_Mesh_TexMatrix(0, NULL);
11342 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11343 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11344 R_Mesh_TexBind(1, layer->texture);
11345 R_Mesh_TexMatrix(1, &layer->texmatrix);
11346 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11347 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11348 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11349 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11350 else if (rsurface.uselightmaptexture)
11351 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11353 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11355 case TEXTURELAYERTYPE_TEXTURE:
11356 // singletexture unlit texture with transparency support
11357 R_Mesh_TexBind(0, layer->texture);
11358 R_Mesh_TexMatrix(0, &layer->texmatrix);
11359 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11360 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11361 R_Mesh_TexBind(1, 0);
11362 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11363 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11365 case TEXTURELAYERTYPE_FOG:
11366 // singletexture fogging
11367 if (layer->texture)
11369 R_Mesh_TexBind(0, layer->texture);
11370 R_Mesh_TexMatrix(0, &layer->texmatrix);
11371 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11372 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11376 R_Mesh_TexBind(0, 0);
11377 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11379 R_Mesh_TexBind(1, 0);
11380 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11381 // generate a color array for the fog pass
11382 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11383 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
11387 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11391 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11393 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11394 GL_AlphaTest(false);
11398 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11400 // OpenGL 1.1 - crusty old voodoo path
11403 const texturelayer_t *layer;
11404 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);
11405 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11407 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11409 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11411 if (layerindex == 0)
11412 GL_AlphaTest(true);
11415 GL_AlphaTest(false);
11416 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11419 GL_DepthMask(layer->depthmask && writedepth);
11420 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11421 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11422 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11423 switch (layer->type)
11425 case TEXTURELAYERTYPE_LITTEXTURE:
11426 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
11428 // two-pass lit texture with 2x rgbscale
11429 // first the lightmap pass
11430 R_Mesh_TexBind(0, r_texture_white);
11431 R_Mesh_TexMatrix(0, NULL);
11432 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11433 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11434 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11435 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
11436 else if (rsurface.uselightmaptexture)
11437 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
11439 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
11440 // then apply the texture to it
11441 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
11442 R_Mesh_TexBind(0, layer->texture);
11443 R_Mesh_TexMatrix(0, &layer->texmatrix);
11444 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11445 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11446 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);
11450 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
11451 R_Mesh_TexBind(0, layer->texture);
11452 R_Mesh_TexMatrix(0, &layer->texmatrix);
11453 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11454 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11455 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11456 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);
11458 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);
11461 case TEXTURELAYERTYPE_TEXTURE:
11462 // singletexture unlit texture with transparency support
11463 R_Mesh_TexBind(0, layer->texture);
11464 R_Mesh_TexMatrix(0, &layer->texmatrix);
11465 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11466 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11467 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);
11469 case TEXTURELAYERTYPE_FOG:
11470 // singletexture fogging
11471 if (layer->texture)
11473 R_Mesh_TexBind(0, layer->texture);
11474 R_Mesh_TexMatrix(0, &layer->texmatrix);
11475 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11476 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11480 R_Mesh_TexBind(0, 0);
11481 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11483 // generate a color array for the fog pass
11484 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11485 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
11489 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11493 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11495 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11496 GL_AlphaTest(false);
11500 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11504 r_vertexgeneric_t *batchvertex;
11507 GL_AlphaTest(false);
11508 R_Mesh_ResetTextureState();
11509 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11511 if(rsurface.texture && rsurface.texture->currentskinframe)
11513 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
11514 c[3] *= rsurface.texture->currentalpha;
11524 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
11526 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
11527 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
11528 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
11531 // brighten it up (as texture value 127 means "unlit")
11532 c[0] *= 2 * r_refdef.view.colorscale;
11533 c[1] *= 2 * r_refdef.view.colorscale;
11534 c[2] *= 2 * r_refdef.view.colorscale;
11536 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
11537 c[3] *= r_wateralpha.value;
11539 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
11541 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11542 GL_DepthMask(false);
11544 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
11546 GL_BlendFunc(GL_ONE, GL_ONE);
11547 GL_DepthMask(false);
11549 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11551 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
11552 GL_DepthMask(false);
11554 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
11556 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
11557 GL_DepthMask(false);
11561 GL_BlendFunc(GL_ONE, GL_ZERO);
11562 GL_DepthMask(writedepth);
11565 if (r_showsurfaces.integer == 3)
11567 rsurface.passcolor4f = NULL;
11569 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
11571 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11573 rsurface.passcolor4f = NULL;
11574 rsurface.passcolor4f_vertexbuffer = 0;
11575 rsurface.passcolor4f_bufferoffset = 0;
11577 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11579 qboolean applycolor = true;
11582 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11584 r_refdef.lightmapintensity = 1;
11585 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
11586 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11590 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11592 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11593 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11594 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11597 if(!rsurface.passcolor4f)
11598 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
11600 RSurf_DrawBatch_GL11_ApplyAmbient();
11601 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
11602 if(r_refdef.fogenabled)
11603 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
11604 RSurf_DrawBatch_GL11_ClampColor();
11606 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
11607 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11610 else if (!r_refdef.view.showdebug)
11612 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11613 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11614 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11616 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11617 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
11619 R_Mesh_PrepareVertices_Generic_Unlock();
11622 else if (r_showsurfaces.integer == 4)
11624 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11625 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11626 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11628 unsigned char c = vi << 3;
11629 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11630 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
11632 R_Mesh_PrepareVertices_Generic_Unlock();
11635 else if (r_showsurfaces.integer == 2)
11638 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11639 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
11640 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
11642 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
11643 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
11644 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
11645 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
11646 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
11647 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
11648 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
11650 R_Mesh_PrepareVertices_Generic_Unlock();
11651 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
11655 int texturesurfaceindex;
11657 const msurface_t *surface;
11658 unsigned char surfacecolor4ub[4];
11659 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11660 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
11662 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11664 surface = texturesurfacelist[texturesurfaceindex];
11665 k = (int)(((size_t)surface) / sizeof(msurface_t));
11666 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
11667 for (j = 0;j < surface->num_vertices;j++)
11669 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11670 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
11674 R_Mesh_PrepareVertices_Generic_Unlock();
11679 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11682 RSurf_SetupDepthAndCulling();
11683 if (r_showsurfaces.integer)
11685 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11688 switch (vid.renderpath)
11690 case RENDERPATH_GL20:
11691 case RENDERPATH_CGGL:
11692 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11694 case RENDERPATH_GL13:
11695 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11697 case RENDERPATH_GL11:
11698 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11704 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11707 RSurf_SetupDepthAndCulling();
11708 if (r_showsurfaces.integer)
11710 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11713 switch (vid.renderpath)
11715 case RENDERPATH_GL20:
11716 case RENDERPATH_CGGL:
11717 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11719 case RENDERPATH_GL13:
11720 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11722 case RENDERPATH_GL11:
11723 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11729 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
11732 int texturenumsurfaces, endsurface;
11733 texture_t *texture;
11734 const msurface_t *surface;
11735 #define MAXBATCH_TRANSPARENTSURFACES 256
11736 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
11738 // if the model is static it doesn't matter what value we give for
11739 // wantnormals and wanttangents, so this logic uses only rules applicable
11740 // to a model, knowing that they are meaningless otherwise
11741 if (ent == r_refdef.scene.worldentity)
11742 RSurf_ActiveWorldEntity();
11743 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11744 RSurf_ActiveModelEntity(ent, false, false, false);
11747 switch (vid.renderpath)
11749 case RENDERPATH_GL20:
11750 case RENDERPATH_CGGL:
11751 RSurf_ActiveModelEntity(ent, true, true, false);
11753 case RENDERPATH_GL13:
11754 case RENDERPATH_GL11:
11755 RSurf_ActiveModelEntity(ent, true, false, false);
11760 if (r_transparentdepthmasking.integer)
11762 qboolean setup = false;
11763 for (i = 0;i < numsurfaces;i = j)
11766 surface = rsurface.modelsurfaces + surfacelist[i];
11767 texture = surface->texture;
11768 rsurface.texture = R_GetCurrentTexture(texture);
11769 rsurface.lightmaptexture = NULL;
11770 rsurface.deluxemaptexture = NULL;
11771 rsurface.uselightmaptexture = false;
11772 // scan ahead until we find a different texture
11773 endsurface = min(i + 1024, numsurfaces);
11774 texturenumsurfaces = 0;
11775 texturesurfacelist[texturenumsurfaces++] = surface;
11776 for (;j < endsurface;j++)
11778 surface = rsurface.modelsurfaces + surfacelist[j];
11779 if (texture != surface->texture)
11781 texturesurfacelist[texturenumsurfaces++] = surface;
11783 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
11785 // render the range of surfaces as depth
11789 GL_ColorMask(0,0,0,0);
11791 GL_DepthTest(true);
11792 GL_BlendFunc(GL_ONE, GL_ZERO);
11793 GL_DepthMask(true);
11794 GL_AlphaTest(false);
11795 R_Mesh_ResetTextureState();
11796 R_SetupShader_DepthOrShadow();
11798 RSurf_SetupDepthAndCulling();
11799 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11800 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11804 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11807 for (i = 0;i < numsurfaces;i = j)
11810 surface = rsurface.modelsurfaces + surfacelist[i];
11811 texture = surface->texture;
11812 rsurface.texture = R_GetCurrentTexture(texture);
11813 rsurface.lightmaptexture = surface->lightmaptexture;
11814 rsurface.deluxemaptexture = surface->deluxemaptexture;
11815 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11816 // scan ahead until we find a different texture
11817 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
11818 texturenumsurfaces = 0;
11819 texturesurfacelist[texturenumsurfaces++] = surface;
11820 for (;j < endsurface;j++)
11822 surface = rsurface.modelsurfaces + surfacelist[j];
11823 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
11825 texturesurfacelist[texturenumsurfaces++] = surface;
11827 // render the range of surfaces
11828 if (ent == r_refdef.scene.worldentity)
11829 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11831 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
11833 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
11834 GL_AlphaTest(false);
11837 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
11839 // transparent surfaces get pushed off into the transparent queue
11840 int surfacelistindex;
11841 const msurface_t *surface;
11842 vec3_t tempcenter, center;
11843 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
11845 surface = texturesurfacelist[surfacelistindex];
11846 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
11847 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
11848 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
11849 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
11850 if (queueentity->transparent_offset) // transparent offset
11852 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
11853 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
11854 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
11856 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
11860 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11862 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
11864 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
11866 RSurf_SetupDepthAndCulling();
11867 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11868 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11872 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
11874 const entity_render_t *queueentity = r_refdef.scene.worldentity;
11877 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
11880 if (!rsurface.texture->currentnumlayers)
11882 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11883 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11885 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11887 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
11888 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
11889 else if (!rsurface.texture->currentnumlayers)
11891 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
11893 // in the deferred case, transparent surfaces were queued during prepass
11894 if (!r_shadow_usingdeferredprepass)
11895 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11899 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
11900 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
11905 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
11908 texture_t *texture;
11909 // break the surface list down into batches by texture and use of lightmapping
11910 for (i = 0;i < numsurfaces;i = j)
11913 // texture is the base texture pointer, rsurface.texture is the
11914 // current frame/skin the texture is directing us to use (for example
11915 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
11916 // use skin 1 instead)
11917 texture = surfacelist[i]->texture;
11918 rsurface.texture = R_GetCurrentTexture(texture);
11919 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
11920 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
11921 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
11922 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
11924 // if this texture is not the kind we want, skip ahead to the next one
11925 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
11929 // simply scan ahead until we find a different texture or lightmap state
11930 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
11932 // render the range of surfaces
11933 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
11937 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
11941 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
11944 if (!rsurface.texture->currentnumlayers)
11946 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11947 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11949 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11951 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
11952 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
11953 else if (!rsurface.texture->currentnumlayers)
11955 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
11957 // in the deferred case, transparent surfaces were queued during prepass
11958 if (!r_shadow_usingdeferredprepass)
11959 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
11963 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
11964 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
11969 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
11972 texture_t *texture;
11973 // break the surface list down into batches by texture and use of lightmapping
11974 for (i = 0;i < numsurfaces;i = j)
11977 // texture is the base texture pointer, rsurface.texture is the
11978 // current frame/skin the texture is directing us to use (for example
11979 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
11980 // use skin 1 instead)
11981 texture = surfacelist[i]->texture;
11982 rsurface.texture = R_GetCurrentTexture(texture);
11983 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
11984 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
11985 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
11986 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
11988 // if this texture is not the kind we want, skip ahead to the next one
11989 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
11993 // simply scan ahead until we find a different texture or lightmap state
11994 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
11996 // render the range of surfaces
11997 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12001 float locboxvertex3f[6*4*3] =
12003 1,0,1, 1,0,0, 1,1,0, 1,1,1,
12004 0,1,1, 0,1,0, 0,0,0, 0,0,1,
12005 1,1,1, 1,1,0, 0,1,0, 0,1,1,
12006 0,0,1, 0,0,0, 1,0,0, 1,0,1,
12007 0,0,1, 1,0,1, 1,1,1, 0,1,1,
12008 1,0,0, 0,0,0, 0,1,0, 1,1,0
12011 unsigned short locboxelements[6*2*3] =
12016 12,13,14, 12,14,15,
12017 16,17,18, 16,18,19,
12021 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12024 cl_locnode_t *loc = (cl_locnode_t *)ent;
12026 float vertex3f[6*4*3];
12028 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12029 GL_DepthMask(false);
12030 GL_DepthRange(0, 1);
12031 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12032 GL_DepthTest(true);
12033 GL_CullFace(GL_NONE);
12034 R_EntityMatrix(&identitymatrix);
12036 R_Mesh_ResetTextureState();
12038 i = surfacelist[0];
12039 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12040 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12041 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12042 surfacelist[0] < 0 ? 0.5f : 0.125f);
12044 if (VectorCompare(loc->mins, loc->maxs))
12046 VectorSet(size, 2, 2, 2);
12047 VectorMA(loc->mins, -0.5f, size, mins);
12051 VectorCopy(loc->mins, mins);
12052 VectorSubtract(loc->maxs, loc->mins, size);
12055 for (i = 0;i < 6*4*3;)
12056 for (j = 0;j < 3;j++, i++)
12057 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12059 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
12060 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12061 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
12064 void R_DrawLocs(void)
12067 cl_locnode_t *loc, *nearestloc;
12069 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12070 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12072 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12073 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12077 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12079 if (decalsystem->decals)
12080 Mem_Free(decalsystem->decals);
12081 memset(decalsystem, 0, sizeof(*decalsystem));
12084 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)
12087 tridecal_t *decals;
12090 // expand or initialize the system
12091 if (decalsystem->maxdecals <= decalsystem->numdecals)
12093 decalsystem_t old = *decalsystem;
12094 qboolean useshortelements;
12095 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12096 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12097 decalsystem->decals = Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
12098 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12099 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12100 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12101 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12102 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12103 if (decalsystem->numdecals)
12104 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12106 Mem_Free(old.decals);
12107 for (i = 0;i < decalsystem->maxdecals*3;i++)
12108 decalsystem->element3i[i] = i;
12109 if (useshortelements)
12110 for (i = 0;i < decalsystem->maxdecals*3;i++)
12111 decalsystem->element3s[i] = i;
12114 // grab a decal and search for another free slot for the next one
12115 decals = decalsystem->decals;
12116 decal = decalsystem->decals + (i = decalsystem->freedecal++);
12117 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12119 decalsystem->freedecal = i;
12120 if (decalsystem->numdecals <= i)
12121 decalsystem->numdecals = i + 1;
12123 // initialize the decal
12125 decal->triangleindex = triangleindex;
12126 decal->surfaceindex = surfaceindex;
12127 decal->decalsequence = decalsequence;
12128 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
12129 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
12130 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
12131 decal->color4ub[0][3] = 255;
12132 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
12133 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
12134 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
12135 decal->color4ub[1][3] = 255;
12136 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
12137 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
12138 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
12139 decal->color4ub[2][3] = 255;
12140 decal->vertex3f[0][0] = v0[0];
12141 decal->vertex3f[0][1] = v0[1];
12142 decal->vertex3f[0][2] = v0[2];
12143 decal->vertex3f[1][0] = v1[0];
12144 decal->vertex3f[1][1] = v1[1];
12145 decal->vertex3f[1][2] = v1[2];
12146 decal->vertex3f[2][0] = v2[0];
12147 decal->vertex3f[2][1] = v2[1];
12148 decal->vertex3f[2][2] = v2[2];
12149 decal->texcoord2f[0][0] = t0[0];
12150 decal->texcoord2f[0][1] = t0[1];
12151 decal->texcoord2f[1][0] = t1[0];
12152 decal->texcoord2f[1][1] = t1[1];
12153 decal->texcoord2f[2][0] = t2[0];
12154 decal->texcoord2f[2][1] = t2[1];
12157 extern cvar_t cl_decals_bias;
12158 extern cvar_t cl_decals_models;
12159 extern cvar_t cl_decals_newsystem_intensitymultiplier;
12160 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)
12162 matrix4x4_t projection;
12163 decalsystem_t *decalsystem;
12166 const float *vertex3f;
12167 const msurface_t *surface;
12168 const msurface_t *surfaces;
12169 const int *surfacelist;
12170 const texture_t *texture;
12172 int numsurfacelist;
12173 int surfacelistindex;
12180 float localorigin[3];
12181 float localnormal[3];
12182 float localmins[3];
12183 float localmaxs[3];
12189 float planes[6][4];
12191 float points[2][9][3];
12195 decalsystem = &ent->decalsystem;
12196 model = ent->model;
12197 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
12199 R_DecalSystem_Reset(&ent->decalsystem);
12203 if (!model->brush.data_nodes && !cl_decals_models.integer)
12205 if (decalsystem->model)
12206 R_DecalSystem_Reset(decalsystem);
12210 if (decalsystem->model != model)
12211 R_DecalSystem_Reset(decalsystem);
12212 decalsystem->model = model;
12214 RSurf_ActiveModelEntity(ent, false, false, false);
12216 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
12217 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
12218 VectorNormalize(localnormal);
12219 localsize = worldsize*rsurface.inversematrixscale;
12220 localmins[0] = localorigin[0] - localsize;
12221 localmins[1] = localorigin[1] - localsize;
12222 localmins[2] = localorigin[2] - localsize;
12223 localmaxs[0] = localorigin[0] + localsize;
12224 localmaxs[1] = localorigin[1] + localsize;
12225 localmaxs[2] = localorigin[2] + localsize;
12227 //VectorCopy(localnormal, planes[4]);
12228 //VectorVectors(planes[4], planes[2], planes[0]);
12229 AnglesFromVectors(angles, localnormal, NULL, false);
12230 AngleVectors(angles, planes[0], planes[2], planes[4]);
12231 VectorNegate(planes[0], planes[1]);
12232 VectorNegate(planes[2], planes[3]);
12233 VectorNegate(planes[4], planes[5]);
12234 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
12235 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
12236 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
12237 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
12238 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
12239 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
12244 matrix4x4_t forwardprojection;
12245 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
12246 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
12251 float projectionvector[4][3];
12252 VectorScale(planes[0], ilocalsize, projectionvector[0]);
12253 VectorScale(planes[2], ilocalsize, projectionvector[1]);
12254 VectorScale(planes[4], ilocalsize, projectionvector[2]);
12255 projectionvector[0][0] = planes[0][0] * ilocalsize;
12256 projectionvector[0][1] = planes[1][0] * ilocalsize;
12257 projectionvector[0][2] = planes[2][0] * ilocalsize;
12258 projectionvector[1][0] = planes[0][1] * ilocalsize;
12259 projectionvector[1][1] = planes[1][1] * ilocalsize;
12260 projectionvector[1][2] = planes[2][1] * ilocalsize;
12261 projectionvector[2][0] = planes[0][2] * ilocalsize;
12262 projectionvector[2][1] = planes[1][2] * ilocalsize;
12263 projectionvector[2][2] = planes[2][2] * ilocalsize;
12264 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
12265 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
12266 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
12267 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
12271 dynamic = model->surfmesh.isanimated;
12272 vertex3f = rsurface.modelvertex3f;
12273 numsurfacelist = model->nummodelsurfaces;
12274 surfacelist = model->sortedmodelsurfaces;
12275 surfaces = model->data_surfaces;
12276 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
12278 surfaceindex = surfacelist[surfacelistindex];
12279 surface = surfaces + surfaceindex;
12280 // check cull box first because it rejects more than any other check
12281 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
12283 // skip transparent surfaces
12284 texture = surface->texture;
12285 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12287 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12289 numtriangles = surface->num_triangles;
12290 for (triangleindex = 0, e = model->surfmesh.data_element3i + 3*surface->num_firsttriangle;triangleindex < numtriangles;triangleindex++, e += 3)
12292 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12294 index = 3*e[cornerindex];
12295 VectorCopy(vertex3f + index, v[cornerindex]);
12298 //TriangleNormal(v[0], v[1], v[2], normal);
12299 //if (DotProduct(normal, localnormal) < 0.0f)
12301 // clip by each of the box planes formed from the projection matrix
12302 // if anything survives, we emit the decal
12303 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]);
12306 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]);
12309 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]);
12312 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]);
12315 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]);
12318 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]);
12321 // some part of the triangle survived, so we have to accept it...
12324 // dynamic always uses the original triangle
12326 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12328 index = 3*e[cornerindex];
12329 VectorCopy(vertex3f + index, v[cornerindex]);
12332 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
12334 // convert vertex positions to texcoords
12335 Matrix4x4_Transform(&projection, v[cornerindex], temp);
12336 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
12337 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
12338 // calculate distance fade from the projection origin
12339 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
12340 f = bound(0.0f, f, 1.0f);
12341 c[cornerindex][0] = r * f;
12342 c[cornerindex][1] = g * f;
12343 c[cornerindex][2] = b * f;
12344 c[cornerindex][3] = 1.0f;
12345 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
12348 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex+surface->num_firsttriangle, surfaceindex, decalsequence);
12350 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
12351 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);
12356 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
12357 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)
12359 int renderentityindex;
12360 float worldmins[3];
12361 float worldmaxs[3];
12362 entity_render_t *ent;
12364 if (!cl_decals_newsystem.integer)
12367 worldmins[0] = worldorigin[0] - worldsize;
12368 worldmins[1] = worldorigin[1] - worldsize;
12369 worldmins[2] = worldorigin[2] - worldsize;
12370 worldmaxs[0] = worldorigin[0] + worldsize;
12371 worldmaxs[1] = worldorigin[1] + worldsize;
12372 worldmaxs[2] = worldorigin[2] + worldsize;
12374 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12376 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
12378 ent = r_refdef.scene.entities[renderentityindex];
12379 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
12382 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12386 typedef struct r_decalsystem_splatqueue_s
12388 vec3_t worldorigin;
12389 vec3_t worldnormal;
12395 r_decalsystem_splatqueue_t;
12397 int r_decalsystem_numqueued = 0;
12398 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
12400 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)
12402 r_decalsystem_splatqueue_t *queue;
12404 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
12407 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
12408 VectorCopy(worldorigin, queue->worldorigin);
12409 VectorCopy(worldnormal, queue->worldnormal);
12410 Vector4Set(queue->color, r, g, b, a);
12411 Vector4Set(queue->tcrange, s1, t1, s2, t2);
12412 queue->worldsize = worldsize;
12413 queue->decalsequence = cl.decalsequence++;
12416 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
12419 r_decalsystem_splatqueue_t *queue;
12421 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
12422 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);
12423 r_decalsystem_numqueued = 0;
12426 extern cvar_t cl_decals_max;
12427 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
12430 decalsystem_t *decalsystem = &ent->decalsystem;
12437 if (!decalsystem->numdecals)
12440 if (r_showsurfaces.integer)
12443 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12445 R_DecalSystem_Reset(decalsystem);
12449 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
12450 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
12452 if (decalsystem->lastupdatetime)
12453 frametime = (cl.time - decalsystem->lastupdatetime);
12456 decalsystem->lastupdatetime = cl.time;
12457 decal = decalsystem->decals;
12458 numdecals = decalsystem->numdecals;
12460 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12462 if (decal->color4ub[0][3])
12464 decal->lived += frametime;
12465 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
12467 memset(decal, 0, sizeof(*decal));
12468 if (decalsystem->freedecal > i)
12469 decalsystem->freedecal = i;
12473 decal = decalsystem->decals;
12474 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
12477 // collapse the array by shuffling the tail decals into the gaps
12480 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
12481 decalsystem->freedecal++;
12482 if (decalsystem->freedecal == numdecals)
12484 decal[decalsystem->freedecal] = decal[--numdecals];
12487 decalsystem->numdecals = numdecals;
12489 if (numdecals <= 0)
12491 // if there are no decals left, reset decalsystem
12492 R_DecalSystem_Reset(decalsystem);
12496 extern skinframe_t *decalskinframe;
12497 static void R_DrawModelDecals_Entity(entity_render_t *ent)
12500 decalsystem_t *decalsystem = &ent->decalsystem;
12509 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
12512 numdecals = decalsystem->numdecals;
12516 if (r_showsurfaces.integer)
12519 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12521 R_DecalSystem_Reset(decalsystem);
12525 // if the model is static it doesn't matter what value we give for
12526 // wantnormals and wanttangents, so this logic uses only rules applicable
12527 // to a model, knowing that they are meaningless otherwise
12528 if (ent == r_refdef.scene.worldentity)
12529 RSurf_ActiveWorldEntity();
12531 RSurf_ActiveModelEntity(ent, false, false, false);
12533 decalsystem->lastupdatetime = cl.time;
12534 decal = decalsystem->decals;
12536 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
12538 // update vertex positions for animated models
12539 v3f = decalsystem->vertex3f;
12540 c4f = decalsystem->color4f;
12541 t2f = decalsystem->texcoord2f;
12542 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12544 if (!decal->color4ub[0][3])
12547 if (surfacevisible && !surfacevisible[decal->surfaceindex])
12550 // update color values for fading decals
12551 if (decal->lived >= cl_decals_time.value)
12553 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
12554 alpha *= (1.0f/255.0f);
12557 alpha = 1.0f/255.0f;
12559 c4f[ 0] = decal->color4ub[0][0] * alpha;
12560 c4f[ 1] = decal->color4ub[0][1] * alpha;
12561 c4f[ 2] = decal->color4ub[0][2] * alpha;
12563 c4f[ 4] = decal->color4ub[1][0] * alpha;
12564 c4f[ 5] = decal->color4ub[1][1] * alpha;
12565 c4f[ 6] = decal->color4ub[1][2] * alpha;
12567 c4f[ 8] = decal->color4ub[2][0] * alpha;
12568 c4f[ 9] = decal->color4ub[2][1] * alpha;
12569 c4f[10] = decal->color4ub[2][2] * alpha;
12572 t2f[0] = decal->texcoord2f[0][0];
12573 t2f[1] = decal->texcoord2f[0][1];
12574 t2f[2] = decal->texcoord2f[1][0];
12575 t2f[3] = decal->texcoord2f[1][1];
12576 t2f[4] = decal->texcoord2f[2][0];
12577 t2f[5] = decal->texcoord2f[2][1];
12579 // update vertex positions for animated models
12580 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
12582 e = rsurface.modelelement3i + 3*decal->triangleindex;
12583 VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
12584 VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
12585 VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
12589 VectorCopy(decal->vertex3f[0], v3f);
12590 VectorCopy(decal->vertex3f[1], v3f + 3);
12591 VectorCopy(decal->vertex3f[2], v3f + 6);
12594 if (r_refdef.fogenabled)
12596 alpha = RSurf_FogVertex(v3f);
12597 VectorScale(c4f, alpha, c4f);
12598 alpha = RSurf_FogVertex(v3f + 3);
12599 VectorScale(c4f + 4, alpha, c4f + 4);
12600 alpha = RSurf_FogVertex(v3f + 6);
12601 VectorScale(c4f + 8, alpha, c4f + 8);
12612 r_refdef.stats.drawndecals += numtris;
12614 // now render the decals all at once
12615 // (this assumes they all use one particle font texture!)
12616 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);
12617 R_Mesh_ResetTextureState();
12618 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
12619 GL_DepthMask(false);
12620 GL_DepthRange(0, 1);
12621 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
12622 GL_DepthTest(true);
12623 GL_CullFace(GL_NONE);
12624 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
12625 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
12626 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
12630 static void R_DrawModelDecals(void)
12634 // fade faster when there are too many decals
12635 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12636 for (i = 0;i < r_refdef.scene.numentities;i++)
12637 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12639 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
12640 for (i = 0;i < r_refdef.scene.numentities;i++)
12641 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12642 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
12644 R_DecalSystem_ApplySplatEntitiesQueue();
12646 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12647 for (i = 0;i < r_refdef.scene.numentities;i++)
12648 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12650 r_refdef.stats.totaldecals += numdecals;
12652 if (r_showsurfaces.integer)
12655 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
12657 for (i = 0;i < r_refdef.scene.numentities;i++)
12659 if (!r_refdef.viewcache.entityvisible[i])
12661 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12662 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
12666 extern cvar_t mod_collision_bih;
12667 void R_DrawDebugModel(void)
12669 entity_render_t *ent = rsurface.entity;
12670 int i, j, k, l, flagsmask;
12671 const msurface_t *surface;
12672 dp_model_t *model = ent->model;
12675 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
12677 R_Mesh_ResetTextureState();
12678 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12679 GL_DepthRange(0, 1);
12680 GL_DepthTest(!r_showdisabledepthtest.integer);
12681 GL_DepthMask(false);
12682 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12684 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
12688 qboolean cullbox = ent == r_refdef.scene.worldentity;
12689 const q3mbrush_t *brush;
12690 const bih_t *bih = &model->collision_bih;
12691 const bih_leaf_t *bihleaf;
12692 float vertex3f[3][3];
12693 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
12695 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
12697 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
12699 switch (bihleaf->type)
12702 brush = model->brush.data_brushes + bihleaf->itemindex;
12703 if (brush->colbrushf && brush->colbrushf->numtriangles)
12705 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);
12706 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
12707 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
12710 case BIH_COLLISIONTRIANGLE:
12711 triangleindex = bihleaf->itemindex;
12712 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
12713 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
12714 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
12715 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);
12716 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12717 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12719 case BIH_RENDERTRIANGLE:
12720 triangleindex = bihleaf->itemindex;
12721 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
12722 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
12723 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
12724 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);
12725 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12726 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12732 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12734 if (r_showtris.integer || r_shownormals.integer)
12736 if (r_showdisabledepthtest.integer)
12738 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12739 GL_DepthMask(false);
12743 GL_BlendFunc(GL_ONE, GL_ZERO);
12744 GL_DepthMask(true);
12746 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
12748 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
12750 rsurface.texture = R_GetCurrentTexture(surface->texture);
12751 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
12753 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
12754 if (r_showtris.value > 0)
12756 if (!rsurface.texture->currentlayers->depthmask)
12757 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
12758 else if (ent == r_refdef.scene.worldentity)
12759 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
12761 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
12762 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12763 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
12765 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
12768 if (r_shownormals.value < 0)
12770 qglBegin(GL_LINES);
12771 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12773 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12774 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
12775 qglVertex3f(v[0], v[1], v[2]);
12776 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
12777 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12778 qglVertex3f(v[0], v[1], v[2]);
12783 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
12785 qglBegin(GL_LINES);
12786 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12788 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12789 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
12790 qglVertex3f(v[0], v[1], v[2]);
12791 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
12792 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12793 qglVertex3f(v[0], v[1], v[2]);
12797 qglBegin(GL_LINES);
12798 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12800 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12801 GL_Color(0, r_refdef.view.colorscale, 0, 1);
12802 qglVertex3f(v[0], v[1], v[2]);
12803 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
12804 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12805 qglVertex3f(v[0], v[1], v[2]);
12809 qglBegin(GL_LINES);
12810 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12812 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12813 GL_Color(0, 0, r_refdef.view.colorscale, 1);
12814 qglVertex3f(v[0], v[1], v[2]);
12815 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
12816 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12817 qglVertex3f(v[0], v[1], v[2]);
12824 rsurface.texture = NULL;
12828 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
12829 int r_maxsurfacelist = 0;
12830 const msurface_t **r_surfacelist = NULL;
12831 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
12833 int i, j, endj, flagsmask;
12834 dp_model_t *model = r_refdef.scene.worldmodel;
12835 msurface_t *surfaces;
12836 unsigned char *update;
12837 int numsurfacelist = 0;
12841 if (r_maxsurfacelist < model->num_surfaces)
12843 r_maxsurfacelist = model->num_surfaces;
12845 Mem_Free((msurface_t**)r_surfacelist);
12846 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
12849 RSurf_ActiveWorldEntity();
12851 surfaces = model->data_surfaces;
12852 update = model->brushq1.lightmapupdateflags;
12854 // update light styles on this submodel
12855 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
12857 model_brush_lightstyleinfo_t *style;
12858 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
12860 if (style->value != r_refdef.scene.lightstylevalue[style->style])
12862 int *list = style->surfacelist;
12863 style->value = r_refdef.scene.lightstylevalue[style->style];
12864 for (j = 0;j < style->numsurfaces;j++)
12865 update[list[j]] = true;
12870 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
12874 R_DrawDebugModel();
12875 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12879 rsurface.lightmaptexture = NULL;
12880 rsurface.deluxemaptexture = NULL;
12881 rsurface.uselightmaptexture = false;
12882 rsurface.texture = NULL;
12883 rsurface.rtlight = NULL;
12884 numsurfacelist = 0;
12885 // add visible surfaces to draw list
12886 for (i = 0;i < model->nummodelsurfaces;i++)
12888 j = model->sortedmodelsurfaces[i];
12889 if (r_refdef.viewcache.world_surfacevisible[j])
12890 r_surfacelist[numsurfacelist++] = surfaces + j;
12892 // update lightmaps if needed
12893 if (model->brushq1.firstrender)
12895 model->brushq1.firstrender = false;
12896 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
12898 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
12902 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
12903 if (r_refdef.viewcache.world_surfacevisible[j])
12905 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
12907 // don't do anything if there were no surfaces
12908 if (!numsurfacelist)
12910 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12913 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
12914 GL_AlphaTest(false);
12916 // add to stats if desired
12917 if (r_speeds.integer && !skysurfaces && !depthonly)
12919 r_refdef.stats.world_surfaces += numsurfacelist;
12920 for (j = 0;j < numsurfacelist;j++)
12921 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
12924 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12927 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
12929 int i, j, endj, flagsmask;
12930 dp_model_t *model = ent->model;
12931 msurface_t *surfaces;
12932 unsigned char *update;
12933 int numsurfacelist = 0;
12937 if (r_maxsurfacelist < model->num_surfaces)
12939 r_maxsurfacelist = model->num_surfaces;
12941 Mem_Free((msurface_t **)r_surfacelist);
12942 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
12945 // if the model is static it doesn't matter what value we give for
12946 // wantnormals and wanttangents, so this logic uses only rules applicable
12947 // to a model, knowing that they are meaningless otherwise
12948 if (ent == r_refdef.scene.worldentity)
12949 RSurf_ActiveWorldEntity();
12950 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12951 RSurf_ActiveModelEntity(ent, false, false, false);
12953 RSurf_ActiveModelEntity(ent, true, true, true);
12954 else if (depthonly)
12956 switch (vid.renderpath)
12958 case RENDERPATH_GL20:
12959 case RENDERPATH_CGGL:
12960 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
12962 case RENDERPATH_GL13:
12963 case RENDERPATH_GL11:
12964 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
12970 switch (vid.renderpath)
12972 case RENDERPATH_GL20:
12973 case RENDERPATH_CGGL:
12974 RSurf_ActiveModelEntity(ent, true, true, false);
12976 case RENDERPATH_GL13:
12977 case RENDERPATH_GL11:
12978 RSurf_ActiveModelEntity(ent, true, false, false);
12983 surfaces = model->data_surfaces;
12984 update = model->brushq1.lightmapupdateflags;
12986 // update light styles
12987 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
12989 model_brush_lightstyleinfo_t *style;
12990 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
12992 if (style->value != r_refdef.scene.lightstylevalue[style->style])
12994 int *list = style->surfacelist;
12995 style->value = r_refdef.scene.lightstylevalue[style->style];
12996 for (j = 0;j < style->numsurfaces;j++)
12997 update[list[j]] = true;
13002 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13006 R_DrawDebugModel();
13007 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13011 rsurface.lightmaptexture = NULL;
13012 rsurface.deluxemaptexture = NULL;
13013 rsurface.uselightmaptexture = false;
13014 rsurface.texture = NULL;
13015 rsurface.rtlight = NULL;
13016 numsurfacelist = 0;
13017 // add visible surfaces to draw list
13018 for (i = 0;i < model->nummodelsurfaces;i++)
13019 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13020 // don't do anything if there were no surfaces
13021 if (!numsurfacelist)
13023 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13026 // update lightmaps if needed
13030 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13035 R_BuildLightMap(ent, surfaces + j);
13040 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13042 R_BuildLightMap(ent, surfaces + j);
13043 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13044 GL_AlphaTest(false);
13046 // add to stats if desired
13047 if (r_speeds.integer && !skysurfaces && !depthonly)
13049 r_refdef.stats.entities_surfaces += numsurfacelist;
13050 for (j = 0;j < numsurfacelist;j++)
13051 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13054 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13057 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13059 static texture_t texture;
13060 static msurface_t surface;
13061 const msurface_t *surfacelist = &surface;
13063 // fake enough texture and surface state to render this geometry
13065 texture.update_lastrenderframe = -1; // regenerate this texture
13066 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
13067 texture.currentskinframe = skinframe;
13068 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
13069 texture.offsetmapping = OFFSETMAPPING_OFF;
13070 texture.offsetscale = 1;
13071 texture.specularscalemod = 1;
13072 texture.specularpowermod = 1;
13074 surface.texture = &texture;
13075 surface.num_triangles = numtriangles;
13076 surface.num_firsttriangle = firsttriangle;
13077 surface.num_vertices = numvertices;
13078 surface.num_firstvertex = firstvertex;
13081 rsurface.texture = R_GetCurrentTexture(surface.texture);
13082 rsurface.lightmaptexture = NULL;
13083 rsurface.deluxemaptexture = NULL;
13084 rsurface.uselightmaptexture = false;
13085 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13088 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)
13090 static msurface_t surface;
13091 const msurface_t *surfacelist = &surface;
13093 // fake enough texture and surface state to render this geometry
13095 surface.texture = texture;
13096 surface.num_triangles = numtriangles;
13097 surface.num_firsttriangle = firsttriangle;
13098 surface.num_vertices = numvertices;
13099 surface.num_firstvertex = firstvertex;
13102 rsurface.texture = R_GetCurrentTexture(surface.texture);
13103 rsurface.lightmaptexture = NULL;
13104 rsurface.deluxemaptexture = NULL;
13105 rsurface.uselightmaptexture = false;
13106 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);