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"
33 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
36 mempool_t *r_main_mempool;
37 rtexturepool_t *r_main_texturepool;
39 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
41 static qboolean r_loadnormalmap;
42 static qboolean r_loadgloss;
44 static qboolean r_loaddds;
45 static qboolean r_savedds;
52 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
53 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
54 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
55 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
56 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)"};
57 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
58 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
59 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
61 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
62 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"};
63 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
64 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)"};
65 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
67 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"};
68 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
69 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
70 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
71 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
72 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%, 10 = 100%)"};
73 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)"};
74 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
75 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
76 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"};
77 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"};
78 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
79 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"};
80 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"};
81 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"};
82 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
83 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
84 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
85 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
86 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
87 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
88 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
89 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)"};
90 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)"};
91 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
92 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
93 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
94 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
95 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
96 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
97 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
98 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
99 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
100 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
101 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
102 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
103 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
104 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
105 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
106 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
107 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
108 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
109 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
110 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
111 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
112 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
113 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
115 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
116 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
117 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
118 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
119 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
120 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
121 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
122 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
124 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
125 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
127 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
128 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
129 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
130 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
131 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
133 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
134 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
135 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
137 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
138 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
139 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
140 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
141 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
142 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
143 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
144 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
145 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
147 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
148 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
149 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
150 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
151 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
153 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
154 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
155 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
156 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
158 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
159 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
160 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
161 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
162 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
163 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
164 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
166 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
167 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
168 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
169 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
171 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
173 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
175 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
177 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
178 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"};
179 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
180 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
181 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
182 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
183 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)"};
185 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
187 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)"};
189 extern cvar_t v_glslgamma;
191 extern qboolean v_flipped_state;
193 static struct r_bloomstate_s
198 int bloomwidth, bloomheight;
200 int screentexturewidth, screentextureheight;
201 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
203 int bloomtexturewidth, bloomtextureheight;
204 rtexture_t *texture_bloom;
206 // arrays for rendering the screen passes
207 float screentexcoord2f[8];
208 float bloomtexcoord2f[8];
209 float offsettexcoord2f[8];
211 r_viewport_t viewport;
215 r_waterstate_t r_waterstate;
217 /// shadow volume bsp struct with automatically growing nodes buffer
220 rtexture_t *r_texture_blanknormalmap;
221 rtexture_t *r_texture_white;
222 rtexture_t *r_texture_grey128;
223 rtexture_t *r_texture_black;
224 rtexture_t *r_texture_notexture;
225 rtexture_t *r_texture_whitecube;
226 rtexture_t *r_texture_normalizationcube;
227 rtexture_t *r_texture_fogattenuation;
228 rtexture_t *r_texture_fogheighttexture;
229 rtexture_t *r_texture_gammaramps;
230 unsigned int r_texture_gammaramps_serial;
231 //rtexture_t *r_texture_fogintensity;
232 rtexture_t *r_texture_reflectcube;
234 // TODO: hash lookups?
235 typedef struct cubemapinfo_s
242 int r_texture_numcubemaps;
243 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
245 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
246 unsigned int r_numqueries;
247 unsigned int r_maxqueries;
249 typedef struct r_qwskincache_s
251 char name[MAX_QPATH];
252 skinframe_t *skinframe;
256 static r_qwskincache_t *r_qwskincache;
257 static int r_qwskincache_size;
259 /// vertex coordinates for a quad that covers the screen exactly
260 extern const float r_screenvertex3f[12];
261 extern const float r_d3dscreenvertex3f[12];
262 const float r_screenvertex3f[12] =
269 const float r_d3dscreenvertex3f[12] =
277 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
280 for (i = 0;i < verts;i++)
291 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
294 for (i = 0;i < verts;i++)
304 // FIXME: move this to client?
307 if (gamemode == GAME_NEHAHRA)
309 Cvar_Set("gl_fogenable", "0");
310 Cvar_Set("gl_fogdensity", "0.2");
311 Cvar_Set("gl_fogred", "0.3");
312 Cvar_Set("gl_foggreen", "0.3");
313 Cvar_Set("gl_fogblue", "0.3");
315 r_refdef.fog_density = 0;
316 r_refdef.fog_red = 0;
317 r_refdef.fog_green = 0;
318 r_refdef.fog_blue = 0;
319 r_refdef.fog_alpha = 1;
320 r_refdef.fog_start = 0;
321 r_refdef.fog_end = 16384;
322 r_refdef.fog_height = 1<<30;
323 r_refdef.fog_fadedepth = 128;
324 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
327 static void R_BuildBlankTextures(void)
329 unsigned char data[4];
330 data[2] = 128; // normal X
331 data[1] = 128; // normal Y
332 data[0] = 255; // normal Z
333 data[3] = 128; // height
334 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
339 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
344 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
349 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
352 static void R_BuildNoTexture(void)
355 unsigned char pix[16][16][4];
356 // this makes a light grey/dark grey checkerboard texture
357 for (y = 0;y < 16;y++)
359 for (x = 0;x < 16;x++)
361 if ((y < 8) ^ (x < 8))
377 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
380 static void R_BuildWhiteCube(void)
382 unsigned char data[6*1*1*4];
383 memset(data, 255, sizeof(data));
384 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
387 static void R_BuildNormalizationCube(void)
391 vec_t s, t, intensity;
394 data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
395 for (side = 0;side < 6;side++)
397 for (y = 0;y < NORMSIZE;y++)
399 for (x = 0;x < NORMSIZE;x++)
401 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
402 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
437 intensity = 127.0f / sqrt(DotProduct(v, v));
438 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
439 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
440 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
441 data[((side*64+y)*64+x)*4+3] = 255;
445 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
449 static void R_BuildFogTexture(void)
453 unsigned char data1[FOGWIDTH][4];
454 //unsigned char data2[FOGWIDTH][4];
457 r_refdef.fogmasktable_start = r_refdef.fog_start;
458 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
459 r_refdef.fogmasktable_range = r_refdef.fogrange;
460 r_refdef.fogmasktable_density = r_refdef.fog_density;
462 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
463 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
465 d = (x * r - r_refdef.fogmasktable_start);
466 if(developer_extra.integer)
467 Con_DPrintf("%f ", d);
469 if (r_fog_exp2.integer)
470 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
472 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
473 if(developer_extra.integer)
474 Con_DPrintf(" : %f ", alpha);
475 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
476 if(developer_extra.integer)
477 Con_DPrintf(" = %f\n", alpha);
478 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
481 for (x = 0;x < FOGWIDTH;x++)
483 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
488 //data2[x][0] = 255 - b;
489 //data2[x][1] = 255 - b;
490 //data2[x][2] = 255 - b;
493 if (r_texture_fogattenuation)
495 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
496 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
500 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, -1, NULL);
501 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALLOWUPDATES, NULL);
505 static void R_BuildFogHeightTexture(void)
507 unsigned char *inpixels;
515 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
516 if (r_refdef.fogheighttexturename[0])
517 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
520 r_refdef.fog_height_tablesize = 0;
521 if (r_texture_fogheighttexture)
522 R_FreeTexture(r_texture_fogheighttexture);
523 r_texture_fogheighttexture = NULL;
524 if (r_refdef.fog_height_table2d)
525 Mem_Free(r_refdef.fog_height_table2d);
526 r_refdef.fog_height_table2d = NULL;
527 if (r_refdef.fog_height_table1d)
528 Mem_Free(r_refdef.fog_height_table1d);
529 r_refdef.fog_height_table1d = NULL;
533 r_refdef.fog_height_tablesize = size;
534 r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
535 r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
536 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
538 // LordHavoc: now the magic - what is that table2d for? it is a cooked
539 // average fog color table accounting for every fog layer between a point
540 // and the camera. (Note: attenuation is handled separately!)
541 for (y = 0;y < size;y++)
543 for (x = 0;x < size;x++)
549 for (j = x;j <= y;j++)
551 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
557 for (j = x;j >= y;j--)
559 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
564 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
565 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
566 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
567 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
570 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
573 //=======================================================================================================================================================
575 static const char *builtinshaderstring =
576 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
577 "// written by Forest 'LordHavoc' Hale\n"
578 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
580 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
583 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
584 "#define USELIGHTMAP\n"
586 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
587 "#define USEEYEVECTOR\n"
590 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
591 "# extension GL_ARB_texture_rectangle : enable\n"
594 "#ifdef USESHADOWMAP2D\n"
595 "# ifdef GL_EXT_gpu_shader4\n"
596 "# extension GL_EXT_gpu_shader4 : enable\n"
598 "# ifdef GL_ARB_texture_gather\n"
599 "# extension GL_ARB_texture_gather : enable\n"
601 "# ifdef GL_AMD_texture_texture4\n"
602 "# extension GL_AMD_texture_texture4 : enable\n"
607 "#ifdef USESHADOWMAPCUBE\n"
608 "# extension GL_EXT_gpu_shader4 : enable\n"
611 "//#ifdef USESHADOWSAMPLER\n"
612 "//# extension GL_ARB_shadow : enable\n"
615 "//#ifdef __GLSL_CG_DATA_TYPES\n"
616 "//# define myhalf half\n"
617 "//# define myhalf2 half2\n"
618 "//# define myhalf3 half3\n"
619 "//# define myhalf4 half4\n"
621 "# define myhalf float\n"
622 "# define myhalf2 vec2\n"
623 "# define myhalf3 vec3\n"
624 "# define myhalf4 vec4\n"
627 "#ifdef VERTEX_SHADER\n"
628 "uniform mat4 ModelViewProjectionMatrix;\n"
631 "#ifdef MODE_DEPTH_OR_SHADOW\n"
632 "#ifdef VERTEX_SHADER\n"
635 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
638 "#else // !MODE_DEPTH_ORSHADOW\n"
643 "#ifdef MODE_SHOWDEPTH\n"
644 "#ifdef VERTEX_SHADER\n"
647 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
648 " gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
652 "#ifdef FRAGMENT_SHADER\n"
655 " gl_FragColor = gl_Color;\n"
658 "#else // !MODE_SHOWDEPTH\n"
663 "#ifdef MODE_POSTPROCESS\n"
664 "varying vec2 TexCoord1;\n"
665 "varying vec2 TexCoord2;\n"
667 "#ifdef VERTEX_SHADER\n"
670 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
671 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
673 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
678 "#ifdef FRAGMENT_SHADER\n"
679 "uniform sampler2D Texture_First;\n"
681 "uniform sampler2D Texture_Second;\n"
683 "#ifdef USEGAMMARAMPS\n"
684 "uniform sampler2D Texture_GammaRamps;\n"
686 "#ifdef USESATURATION\n"
687 "uniform float Saturation;\n"
689 "#ifdef USEVIEWTINT\n"
690 "uniform vec4 ViewTintColor;\n"
692 "//uncomment these if you want to use them:\n"
693 "uniform vec4 UserVec1;\n"
694 "uniform vec4 UserVec2;\n"
695 "// uniform vec4 UserVec3;\n"
696 "// uniform vec4 UserVec4;\n"
697 "// uniform float ClientTime;\n"
698 "uniform vec2 PixelSize;\n"
701 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
703 " gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
705 "#ifdef USEVIEWTINT\n"
706 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
709 "#ifdef USEPOSTPROCESSING\n"
710 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
711 "// 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"
712 " float sobel = 1.0;\n"
713 " // vec2 ts = textureSize(Texture_First, 0);\n"
714 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
715 " vec2 px = PixelSize;\n"
716 " vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
717 " vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0)).rgb;\n"
718 " vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
719 " vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
720 " vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0)).rgb;\n"
721 " vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
722 " vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
723 " vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y)).rgb;\n"
724 " vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
725 " vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
726 " vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y)).rgb;\n"
727 " vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
728 " float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
729 " float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
730 " float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
731 " float px4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
732 " float px5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
733 " float px6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
734 " float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
735 " float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
736 " float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
737 " float py4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
738 " float py5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
739 " float py6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
740 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
741 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
742 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
743 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
744 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
745 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
746 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
747 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
750 "#ifdef USESATURATION\n"
751 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
752 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
753 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
754 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
757 "#ifdef USEGAMMARAMPS\n"
758 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
759 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
760 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
764 "#else // !MODE_POSTPROCESS\n"
769 "#ifdef MODE_GENERIC\n"
770 "#ifdef USEDIFFUSE\n"
771 "varying vec2 TexCoord1;\n"
773 "#ifdef USESPECULAR\n"
774 "varying vec2 TexCoord2;\n"
776 "#ifdef VERTEX_SHADER\n"
779 " gl_FrontColor = gl_Color;\n"
780 "#ifdef USEDIFFUSE\n"
781 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
783 "#ifdef USESPECULAR\n"
784 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
786 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
790 "#ifdef FRAGMENT_SHADER\n"
791 "#ifdef USEDIFFUSE\n"
792 "uniform sampler2D Texture_First;\n"
794 "#ifdef USESPECULAR\n"
795 "uniform sampler2D Texture_Second;\n"
800 " gl_FragColor = gl_Color;\n"
801 "#ifdef USEDIFFUSE\n"
802 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
805 "#ifdef USESPECULAR\n"
806 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
807 "# ifdef USECOLORMAPPING\n"
808 " gl_FragColor *= tex2;\n"
811 " gl_FragColor += tex2;\n"
813 "# ifdef USEVERTEXTEXTUREBLEND\n"
814 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
819 "#else // !MODE_GENERIC\n"
824 "#ifdef MODE_BLOOMBLUR\n"
825 "varying TexCoord;\n"
826 "#ifdef VERTEX_SHADER\n"
829 " gl_FrontColor = gl_Color;\n"
830 " TexCoord = gl_MultiTexCoord0.xy;\n"
831 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
835 "#ifdef FRAGMENT_SHADER\n"
836 "uniform sampler2D Texture_First;\n"
837 "uniform vec4 BloomBlur_Parameters;\n"
842 " vec2 tc = TexCoord;\n"
843 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
844 " tc += BloomBlur_Parameters.xy;\n"
845 " for (i = 1;i < SAMPLES;i++)\n"
847 " color += texture2D(Texture_First, tc).rgb;\n"
848 " tc += BloomBlur_Parameters.xy;\n"
850 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
853 "#else // !MODE_BLOOMBLUR\n"
854 "#ifdef MODE_REFRACTION\n"
855 "varying vec2 TexCoord;\n"
856 "varying vec4 ModelViewProjectionPosition;\n"
857 "uniform mat4 TexMatrix;\n"
858 "#ifdef VERTEX_SHADER\n"
862 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
863 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
864 " ModelViewProjectionPosition = gl_Position;\n"
868 "#ifdef FRAGMENT_SHADER\n"
869 "uniform sampler2D Texture_Normal;\n"
870 "uniform sampler2D Texture_Refraction;\n"
871 "uniform sampler2D Texture_Reflection;\n"
873 "uniform vec4 DistortScaleRefractReflect;\n"
874 "uniform vec4 ScreenScaleRefractReflect;\n"
875 "uniform vec4 ScreenCenterRefractReflect;\n"
876 "uniform vec4 RefractColor;\n"
877 "uniform vec4 ReflectColor;\n"
878 "uniform float ReflectFactor;\n"
879 "uniform float ReflectOffset;\n"
883 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
884 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
885 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
886 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
887 " // FIXME temporary hack to detect the case that the reflection\n"
888 " // gets blackened at edges due to leaving the area that contains actual\n"
890 " // Remove this 'ack once we have a better way to stop this thing from\n"
892 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
893 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
894 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
895 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
896 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
897 " gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
900 "#else // !MODE_REFRACTION\n"
905 "#ifdef MODE_WATER\n"
906 "varying vec2 TexCoord;\n"
907 "varying vec3 EyeVector;\n"
908 "varying vec4 ModelViewProjectionPosition;\n"
909 "#ifdef VERTEX_SHADER\n"
910 "uniform vec3 EyePosition;\n"
911 "uniform mat4 TexMatrix;\n"
915 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
916 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
917 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
918 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
919 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
920 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
921 " ModelViewProjectionPosition = gl_Position;\n"
925 "#ifdef FRAGMENT_SHADER\n"
926 "uniform sampler2D Texture_Normal;\n"
927 "uniform sampler2D Texture_Refraction;\n"
928 "uniform sampler2D Texture_Reflection;\n"
930 "uniform vec4 DistortScaleRefractReflect;\n"
931 "uniform vec4 ScreenScaleRefractReflect;\n"
932 "uniform vec4 ScreenCenterRefractReflect;\n"
933 "uniform vec4 RefractColor;\n"
934 "uniform vec4 ReflectColor;\n"
935 "uniform float ReflectFactor;\n"
936 "uniform float ReflectOffset;\n"
940 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
941 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
942 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
943 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
944 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
945 " // FIXME temporary hack to detect the case that the reflection\n"
946 " // gets blackened at edges due to leaving the area that contains actual\n"
948 " // Remove this 'ack once we have a better way to stop this thing from\n"
950 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
951 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
952 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
953 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
954 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
955 " f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
956 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
957 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
958 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
959 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
960 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
961 " gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
964 "#else // !MODE_WATER\n"
969 "// common definitions between vertex shader and fragment shader:\n"
971 "varying vec2 TexCoord;\n"
972 "#ifdef USEVERTEXTEXTUREBLEND\n"
973 "varying vec2 TexCoord2;\n"
975 "#ifdef USELIGHTMAP\n"
976 "varying vec2 TexCoordLightmap;\n"
979 "#ifdef MODE_LIGHTSOURCE\n"
980 "varying vec3 CubeVector;\n"
983 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
984 "varying vec3 LightVector;\n"
987 "#ifdef USEEYEVECTOR\n"
988 "varying vec3 EyeVector;\n"
991 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
994 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
995 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
996 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
997 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
1000 "#ifdef USEREFLECTION\n"
1001 "varying vec4 ModelViewProjectionPosition;\n"
1003 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1004 "uniform vec3 LightPosition;\n"
1005 "varying vec4 ModelViewPosition;\n"
1008 "#ifdef MODE_LIGHTSOURCE\n"
1009 "uniform vec3 LightPosition;\n"
1011 "uniform vec3 EyePosition;\n"
1012 "#ifdef MODE_LIGHTDIRECTION\n"
1013 "uniform vec3 LightDir;\n"
1015 "uniform vec4 FogPlane;\n"
1017 "#ifdef USESHADOWMAPORTHO\n"
1018 "varying vec3 ShadowMapTC;\n"
1025 "// 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"
1027 "// fragment shader specific:\n"
1028 "#ifdef FRAGMENT_SHADER\n"
1030 "uniform sampler2D Texture_Normal;\n"
1031 "uniform sampler2D Texture_Color;\n"
1032 "uniform sampler2D Texture_Gloss;\n"
1034 "uniform sampler2D Texture_Glow;\n"
1036 "#ifdef USEVERTEXTEXTUREBLEND\n"
1037 "uniform sampler2D Texture_SecondaryNormal;\n"
1038 "uniform sampler2D Texture_SecondaryColor;\n"
1039 "uniform sampler2D Texture_SecondaryGloss;\n"
1041 "uniform sampler2D Texture_SecondaryGlow;\n"
1044 "#ifdef USECOLORMAPPING\n"
1045 "uniform sampler2D Texture_Pants;\n"
1046 "uniform sampler2D Texture_Shirt;\n"
1049 "#ifdef USEFOGHEIGHTTEXTURE\n"
1050 "uniform sampler2D Texture_FogHeightTexture;\n"
1052 "uniform sampler2D Texture_FogMask;\n"
1054 "#ifdef USELIGHTMAP\n"
1055 "uniform sampler2D Texture_Lightmap;\n"
1057 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1058 "uniform sampler2D Texture_Deluxemap;\n"
1060 "#ifdef USEREFLECTION\n"
1061 "uniform sampler2D Texture_Reflection;\n"
1064 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1065 "uniform sampler2D Texture_ScreenDepth;\n"
1066 "uniform sampler2D Texture_ScreenNormalMap;\n"
1068 "#ifdef USEDEFERREDLIGHTMAP\n"
1069 "uniform sampler2D Texture_ScreenDiffuse;\n"
1070 "uniform sampler2D Texture_ScreenSpecular;\n"
1073 "uniform myhalf3 Color_Pants;\n"
1074 "uniform myhalf3 Color_Shirt;\n"
1075 "uniform myhalf3 FogColor;\n"
1078 "uniform float FogRangeRecip;\n"
1079 "uniform float FogPlaneViewDist;\n"
1080 "uniform float FogHeightFade;\n"
1081 "vec3 FogVertex(vec3 surfacecolor)\n"
1083 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1084 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1086 "#ifdef USEFOGHEIGHTTEXTURE\n"
1087 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1088 " fogfrac = fogheightpixel.a;\n"
1089 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1091 "# ifdef USEFOGOUTSIDE\n"
1092 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1094 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1096 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1101 "#ifdef USEOFFSETMAPPING\n"
1102 "uniform float OffsetMapping_Scale;\n"
1103 "vec2 OffsetMapping(vec2 TexCoord)\n"
1105 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1106 " // 14 sample relief mapping: linear search and then binary search\n"
1107 " // this basically steps forward a small amount repeatedly until it finds\n"
1108 " // itself inside solid, then jitters forward and back using decreasing\n"
1109 " // amounts to find the impact\n"
1110 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1111 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1112 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1113 " vec3 RT = vec3(TexCoord, 1);\n"
1114 " OffsetVector *= 0.1;\n"
1115 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1116 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1117 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1118 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1119 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1120 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1121 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1122 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1123 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1124 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1125 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1126 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1127 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1128 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1131 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1132 " // this basically moves forward the full distance, and then backs up based\n"
1133 " // on height of samples\n"
1134 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1135 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1136 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1137 " TexCoord += OffsetVector;\n"
1138 " OffsetVector *= 0.333;\n"
1139 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1140 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1141 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1142 " return TexCoord;\n"
1145 "#endif // USEOFFSETMAPPING\n"
1147 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1148 "uniform sampler2D Texture_Attenuation;\n"
1149 "uniform samplerCube Texture_Cube;\n"
1152 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1154 "#ifdef USESHADOWMAPRECT\n"
1155 "# ifdef USESHADOWSAMPLER\n"
1156 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1158 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1162 "#ifdef USESHADOWMAP2D\n"
1163 "# ifdef USESHADOWSAMPLER\n"
1164 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1166 "uniform sampler2D Texture_ShadowMap2D;\n"
1170 "#ifdef USESHADOWMAPVSDCT\n"
1171 "uniform samplerCube Texture_CubeProjection;\n"
1174 "#ifdef USESHADOWMAPCUBE\n"
1175 "# ifdef USESHADOWSAMPLER\n"
1176 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1178 "uniform samplerCube Texture_ShadowMapCube;\n"
1182 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1183 "uniform vec2 ShadowMap_TextureScale;\n"
1184 "uniform vec4 ShadowMap_Parameters;\n"
1187 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1188 "# ifdef USESHADOWMAPORTHO\n"
1189 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1191 "# ifdef USESHADOWMAPVSDCT\n"
1192 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1194 " vec3 adir = abs(dir);\n"
1195 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1196 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1197 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1200 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1202 " vec3 adir = abs(dir);\n"
1203 " float ma = adir.z;\n"
1204 " vec4 proj = vec4(dir, 2.5);\n"
1205 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1206 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1207 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1208 " 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"
1212 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1214 "#ifdef USESHADOWMAPCUBE\n"
1215 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1217 " vec3 adir = abs(dir);\n"
1218 " return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1222 "# ifdef USESHADOWMAPRECT\n"
1223 "float ShadowMapCompare(vec3 dir)\n"
1225 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1227 "# ifdef USESHADOWSAMPLER\n"
1229 "# ifdef USESHADOWMAPPCF\n"
1230 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1231 " 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"
1233 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1238 "# ifdef USESHADOWMAPPCF\n"
1239 "# if USESHADOWMAPPCF > 1\n"
1240 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1241 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1242 " 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"
1243 " 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"
1244 " 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"
1245 " 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"
1246 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1247 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1249 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1250 " vec2 offset = fract(shadowmaptc.xy);\n"
1251 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1252 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1253 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1254 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1255 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1258 " f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1262 "# ifdef USESHADOWMAPORTHO\n"
1263 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1270 "# ifdef USESHADOWMAP2D\n"
1271 "float ShadowMapCompare(vec3 dir)\n"
1273 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1276 "# ifdef USESHADOWSAMPLER\n"
1277 "# ifdef USESHADOWMAPPCF\n"
1278 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1279 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1280 " 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"
1282 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1285 "# ifdef USESHADOWMAPPCF\n"
1286 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1287 "# ifdef GL_ARB_texture_gather\n"
1288 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1290 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1292 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1293 "# if USESHADOWMAPPCF > 1\n"
1294 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1295 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1296 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1297 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1298 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1299 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1300 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1301 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1302 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1303 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1304 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1305 " locols.yz += group2.ab;\n"
1306 " hicols.yz += group8.rg;\n"
1307 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1308 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1309 " mix(locols, hicols, offset.y);\n"
1310 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1311 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1312 " f = dot(cols, vec4(1.0/25.0));\n"
1314 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1315 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1316 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1317 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1318 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1319 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1320 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1323 "# ifdef GL_EXT_gpu_shader4\n"
1324 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1326 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1328 "# if USESHADOWMAPPCF > 1\n"
1329 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1330 " center *= ShadowMap_TextureScale;\n"
1331 " 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"
1332 " 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"
1333 " 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"
1334 " 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"
1335 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1336 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1338 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1339 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1340 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1341 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1342 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1343 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1347 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1350 "# ifdef USESHADOWMAPORTHO\n"
1351 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1358 "# ifdef USESHADOWMAPCUBE\n"
1359 "float ShadowMapCompare(vec3 dir)\n"
1361 " // apply depth texture cubemap as light filter\n"
1362 " vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1364 "# ifdef USESHADOWSAMPLER\n"
1365 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1367 " f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1372 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1373 "#endif // FRAGMENT_SHADER\n"
1378 "#ifdef MODE_DEFERREDGEOMETRY\n"
1379 "#ifdef VERTEX_SHADER\n"
1380 "uniform mat4 TexMatrix;\n"
1381 "#ifdef USEVERTEXTEXTUREBLEND\n"
1382 "uniform mat4 BackgroundTexMatrix;\n"
1384 "uniform mat4 ModelViewMatrix;\n"
1387 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1388 "#ifdef USEVERTEXTEXTUREBLEND\n"
1389 " gl_FrontColor = gl_Color;\n"
1390 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1393 " // transform unnormalized eye direction into tangent space\n"
1394 "#ifdef USEOFFSETMAPPING\n"
1395 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1396 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1397 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1398 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1401 " VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1402 " VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1403 " VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1404 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1406 "#endif // VERTEX_SHADER\n"
1408 "#ifdef FRAGMENT_SHADER\n"
1411 "#ifdef USEOFFSETMAPPING\n"
1412 " // apply offsetmapping\n"
1413 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1414 "#define TexCoord TexCoordOffset\n"
1417 "#ifdef USEALPHAKILL\n"
1418 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1422 "#ifdef USEVERTEXTEXTUREBLEND\n"
1423 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1424 " float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1425 " //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1426 " //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1429 "#ifdef USEVERTEXTEXTUREBLEND\n"
1430 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1431 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1433 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1434 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1437 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1439 "#endif // FRAGMENT_SHADER\n"
1440 "#else // !MODE_DEFERREDGEOMETRY\n"
1445 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1446 "#ifdef VERTEX_SHADER\n"
1447 "uniform mat4 ModelViewMatrix;\n"
1450 " ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1451 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1453 "#endif // VERTEX_SHADER\n"
1455 "#ifdef FRAGMENT_SHADER\n"
1456 "uniform mat4 ViewToLight;\n"
1457 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1458 "uniform vec2 ScreenToDepth;\n"
1459 "uniform myhalf3 DeferredColor_Ambient;\n"
1460 "uniform myhalf3 DeferredColor_Diffuse;\n"
1461 "#ifdef USESPECULAR\n"
1462 "uniform myhalf3 DeferredColor_Specular;\n"
1463 "uniform myhalf SpecularPower;\n"
1465 "uniform myhalf2 PixelToScreenTexCoord;\n"
1468 " // calculate viewspace pixel position\n"
1469 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1471 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1472 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1473 " // decode viewspace pixel normal\n"
1474 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1475 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1476 " // surfacenormal = pixel normal in viewspace\n"
1477 " // LightVector = pixel to light in viewspace\n"
1478 " // CubeVector = position in lightspace\n"
1479 " // eyevector = pixel to view in viewspace\n"
1480 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1481 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1482 "#ifdef USEDIFFUSE\n"
1483 " // calculate diffuse shading\n"
1484 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1485 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1487 "#ifdef USESPECULAR\n"
1488 " // calculate directional shading\n"
1489 " vec3 eyevector = position * -1.0;\n"
1490 "# ifdef USEEXACTSPECULARMATH\n"
1491 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1493 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1494 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1498 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1499 " fade *= ShadowMapCompare(CubeVector);\n"
1502 "#ifdef USEDIFFUSE\n"
1503 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1505 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1507 "#ifdef USESPECULAR\n"
1508 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1510 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1513 "# ifdef USECUBEFILTER\n"
1514 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1515 " gl_FragData[0].rgb *= cubecolor;\n"
1516 " gl_FragData[1].rgb *= cubecolor;\n"
1519 "#endif // FRAGMENT_SHADER\n"
1520 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1525 "#ifdef VERTEX_SHADER\n"
1526 "uniform mat4 TexMatrix;\n"
1527 "#ifdef USEVERTEXTEXTUREBLEND\n"
1528 "uniform mat4 BackgroundTexMatrix;\n"
1530 "#ifdef MODE_LIGHTSOURCE\n"
1531 "uniform mat4 ModelToLight;\n"
1533 "#ifdef USESHADOWMAPORTHO\n"
1534 "uniform mat4 ShadowMapMatrix;\n"
1538 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1539 " gl_FrontColor = gl_Color;\n"
1541 " // copy the surface texcoord\n"
1542 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1543 "#ifdef USEVERTEXTEXTUREBLEND\n"
1544 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1546 "#ifdef USELIGHTMAP\n"
1547 " TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1550 "#ifdef MODE_LIGHTSOURCE\n"
1551 " // transform vertex position into light attenuation/cubemap space\n"
1552 " // (-1 to +1 across the light box)\n"
1553 " CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1555 "# ifdef USEDIFFUSE\n"
1556 " // transform unnormalized light direction into tangent space\n"
1557 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1558 " // normalize it per pixel)\n"
1559 " vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1560 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1561 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1562 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1566 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1567 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1568 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1569 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1572 " // transform unnormalized eye direction into tangent space\n"
1573 "#ifdef USEEYEVECTOR\n"
1574 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1575 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1576 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1577 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1581 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1582 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1585 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1586 " VectorS = gl_MultiTexCoord1.xyz;\n"
1587 " VectorT = gl_MultiTexCoord2.xyz;\n"
1588 " VectorR = gl_MultiTexCoord3.xyz;\n"
1591 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1592 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1594 "#ifdef USESHADOWMAPORTHO\n"
1595 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1598 "#ifdef USEREFLECTION\n"
1599 " ModelViewProjectionPosition = gl_Position;\n"
1602 "#endif // VERTEX_SHADER\n"
1607 "#ifdef FRAGMENT_SHADER\n"
1608 "#ifdef USEDEFERREDLIGHTMAP\n"
1609 "uniform myhalf2 PixelToScreenTexCoord;\n"
1610 "uniform myhalf3 DeferredMod_Diffuse;\n"
1611 "uniform myhalf3 DeferredMod_Specular;\n"
1613 "uniform myhalf3 Color_Ambient;\n"
1614 "uniform myhalf3 Color_Diffuse;\n"
1615 "uniform myhalf3 Color_Specular;\n"
1616 "uniform myhalf SpecularPower;\n"
1618 "uniform myhalf3 Color_Glow;\n"
1620 "uniform myhalf Alpha;\n"
1621 "#ifdef USEREFLECTION\n"
1622 "uniform vec4 DistortScaleRefractReflect;\n"
1623 "uniform vec4 ScreenScaleRefractReflect;\n"
1624 "uniform vec4 ScreenCenterRefractReflect;\n"
1625 "uniform myhalf4 ReflectColor;\n"
1627 "#ifdef USEREFLECTCUBE\n"
1628 "uniform mat4 ModelToReflectCube;\n"
1629 "uniform sampler2D Texture_ReflectMask;\n"
1630 "uniform samplerCube Texture_ReflectCube;\n"
1632 "#ifdef MODE_LIGHTDIRECTION\n"
1633 "uniform myhalf3 LightColor;\n"
1635 "#ifdef MODE_LIGHTSOURCE\n"
1636 "uniform myhalf3 LightColor;\n"
1640 "#ifdef USEOFFSETMAPPING\n"
1641 " // apply offsetmapping\n"
1642 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1643 "#define TexCoord TexCoordOffset\n"
1646 " // combine the diffuse textures (base, pants, shirt)\n"
1647 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1648 "#ifdef USEALPHAKILL\n"
1649 " if (color.a < 0.5)\n"
1652 " color.a *= Alpha;\n"
1653 "#ifdef USECOLORMAPPING\n"
1654 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1656 "#ifdef USEVERTEXTEXTUREBLEND\n"
1657 " myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1658 " //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1659 " //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1660 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1662 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1665 " // get the surface normal\n"
1666 "#ifdef USEVERTEXTEXTUREBLEND\n"
1667 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1669 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1672 " // get the material colors\n"
1673 " myhalf3 diffusetex = color.rgb;\n"
1674 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1675 "# ifdef USEVERTEXTEXTUREBLEND\n"
1676 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1678 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1682 "#ifdef USEREFLECTCUBE\n"
1683 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1684 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1685 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1686 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1692 "#ifdef MODE_LIGHTSOURCE\n"
1693 " // light source\n"
1694 "#ifdef USEDIFFUSE\n"
1695 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1696 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1697 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1698 "#ifdef USESPECULAR\n"
1699 "#ifdef USEEXACTSPECULARMATH\n"
1700 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1702 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1703 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1705 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1708 " color.rgb = diffusetex * Color_Ambient;\n"
1710 " color.rgb *= LightColor;\n"
1711 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1712 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1713 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1715 "# ifdef USECUBEFILTER\n"
1716 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1718 "#endif // MODE_LIGHTSOURCE\n"
1723 "#ifdef MODE_LIGHTDIRECTION\n"
1725 "#ifdef USEDIFFUSE\n"
1726 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1728 "#define lightcolor LightColor\n"
1729 "#endif // MODE_LIGHTDIRECTION\n"
1730 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1732 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1733 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1734 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1735 " // convert modelspace light vector to tangentspace\n"
1736 " myhalf3 lightnormal;\n"
1737 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1738 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1739 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1740 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1741 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1742 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1743 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1744 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1745 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1746 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1747 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1748 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1749 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1750 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1751 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1753 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1754 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1755 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1761 "#ifdef MODE_LIGHTMAP\n"
1762 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1763 "#endif // MODE_LIGHTMAP\n"
1764 "#ifdef MODE_VERTEXCOLOR\n"
1765 " color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1766 "#endif // MODE_VERTEXCOLOR\n"
1767 "#ifdef MODE_FLATCOLOR\n"
1768 " color.rgb = diffusetex * Color_Ambient;\n"
1769 "#endif // MODE_FLATCOLOR\n"
1775 "# ifdef USEDIFFUSE\n"
1776 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1777 "# ifdef USESPECULAR\n"
1778 "# ifdef USEEXACTSPECULARMATH\n"
1779 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1781 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1782 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1784 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1786 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1789 " color.rgb = diffusetex * Color_Ambient;\n"
1793 "#ifdef USESHADOWMAPORTHO\n"
1794 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1797 "#ifdef USEDEFERREDLIGHTMAP\n"
1798 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1799 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1800 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1804 "#ifdef USEVERTEXTEXTUREBLEND\n"
1805 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1807 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1812 " color.rgb = FogVertex(color.rgb);\n"
1815 " // 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"
1816 "#ifdef USEREFLECTION\n"
1817 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1818 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1819 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1820 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1821 " // FIXME temporary hack to detect the case that the reflection\n"
1822 " // gets blackened at edges due to leaving the area that contains actual\n"
1824 " // Remove this 'ack once we have a better way to stop this thing from\n"
1826 " float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1827 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1828 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1829 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1830 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1831 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1834 " gl_FragColor = vec4(color);\n"
1836 "#endif // FRAGMENT_SHADER\n"
1838 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1839 "#endif // !MODE_DEFERREDGEOMETRY\n"
1840 "#endif // !MODE_WATER\n"
1841 "#endif // !MODE_REFRACTION\n"
1842 "#endif // !MODE_BLOOMBLUR\n"
1843 "#endif // !MODE_GENERIC\n"
1844 "#endif // !MODE_POSTPROCESS\n"
1845 "#endif // !MODE_SHOWDEPTH\n"
1846 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1850 =========================================================================================================================================================
1854 =========================================================================================================================================================
1858 =========================================================================================================================================================
1862 =========================================================================================================================================================
1866 =========================================================================================================================================================
1870 =========================================================================================================================================================
1874 =========================================================================================================================================================
1877 const char *builtincgshaderstring =
1878 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1879 "// written by Forest 'LordHavoc' Hale\n"
1880 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1882 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1883 "#if defined(USEREFLECTION)\n"
1884 "#undef USESHADOWMAPORTHO\n"
1887 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1890 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1891 "#define USELIGHTMAP\n"
1893 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1894 "#define USEEYEVECTOR\n"
1897 "#ifdef FRAGMENT_SHADER\n"
1898 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1901 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1902 "#ifdef VERTEX_SHADER\n"
1905 "float4 gl_Vertex : POSITION,\n"
1906 "uniform float4x4 ModelViewProjectionMatrix,\n"
1907 "out float4 gl_Position : POSITION\n"
1910 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1913 "#else // !MODE_DEPTH_ORSHADOW\n"
1918 "#ifdef MODE_SHOWDEPTH\n"
1919 "#ifdef VERTEX_SHADER\n"
1922 "float4 gl_Vertex : POSITION,\n"
1923 "uniform float4x4 ModelViewProjectionMatrix,\n"
1924 "out float4 gl_Position : POSITION,\n"
1925 "out float4 gl_FrontColor : COLOR0\n"
1928 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1929 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1933 "#ifdef FRAGMENT_SHADER\n"
1936 "float4 gl_FrontColor : COLOR0,\n"
1937 "out float4 gl_FragColor : COLOR\n"
1940 " gl_FragColor = gl_FrontColor;\n"
1943 "#else // !MODE_SHOWDEPTH\n"
1948 "#ifdef MODE_POSTPROCESS\n"
1950 "#ifdef VERTEX_SHADER\n"
1953 "float4 gl_Vertex : POSITION,\n"
1954 "uniform float4x4 ModelViewProjectionMatrix,\n"
1955 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1956 "float4 gl_MultiTexCoord1 : TEXCOORD4,\n"
1957 "out float4 gl_Position : POSITION,\n"
1958 "out float2 TexCoord1 : TEXCOORD0,\n"
1959 "out float2 TexCoord2 : TEXCOORD1\n"
1962 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1963 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
1965 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
1970 "#ifdef FRAGMENT_SHADER\n"
1973 "float2 TexCoord1 : TEXCOORD0,\n"
1974 "float2 TexCoord2 : TEXCOORD1,\n"
1975 "uniform sampler2D Texture_First,\n"
1977 "uniform sampler2D Texture_Second,\n"
1979 "#ifdef USEGAMMARAMPS\n"
1980 "uniform sampler2D Texture_GammaRamps,\n"
1982 "#ifdef USESATURATION\n"
1983 "uniform float Saturation,\n"
1985 "#ifdef USEVIEWTINT\n"
1986 "uniform float4 ViewTintColor,\n"
1988 "uniform float4 UserVec1,\n"
1989 "uniform float4 UserVec2,\n"
1990 "uniform float4 UserVec3,\n"
1991 "uniform float4 UserVec4,\n"
1992 "uniform float ClientTime,\n"
1993 "uniform float2 PixelSize,\n"
1994 "out float4 gl_FragColor : COLOR\n"
1997 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1999 " gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
2001 "#ifdef USEVIEWTINT\n"
2002 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
2005 "#ifdef USEPOSTPROCESSING\n"
2006 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
2007 "// 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"
2008 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
2009 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
2010 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
2011 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
2012 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
2013 " gl_FragColor /= (1 + 5 * UserVec1.y);\n"
2016 "#ifdef USESATURATION\n"
2017 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2018 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2019 " //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2020 " gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2023 "#ifdef USEGAMMARAMPS\n"
2024 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2025 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2026 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2030 "#else // !MODE_POSTPROCESS\n"
2035 "#ifdef MODE_GENERIC\n"
2036 "#ifdef VERTEX_SHADER\n"
2039 "float4 gl_Vertex : POSITION,\n"
2040 "uniform float4x4 ModelViewProjectionMatrix,\n"
2041 "float4 gl_Color : COLOR0,\n"
2042 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2043 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2044 "out float4 gl_Position : POSITION,\n"
2045 "out float4 gl_FrontColor : COLOR,\n"
2046 "out float2 TexCoord1 : TEXCOORD0,\n"
2047 "out float2 TexCoord2 : TEXCOORD1\n"
2050 " gl_FrontColor = gl_Color;\n"
2051 "#ifdef USEDIFFUSE\n"
2052 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2054 "#ifdef USESPECULAR\n"
2055 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2057 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2061 "#ifdef FRAGMENT_SHADER\n"
2065 "float4 gl_FrontColor : COLOR,\n"
2066 "float2 TexCoord1 : TEXCOORD0,\n"
2067 "float2 TexCoord2 : TEXCOORD1,\n"
2068 "#ifdef USEDIFFUSE\n"
2069 "uniform sampler2D Texture_First,\n"
2071 "#ifdef USESPECULAR\n"
2072 "uniform sampler2D Texture_Second,\n"
2074 "out float4 gl_FragColor : COLOR\n"
2077 " gl_FragColor = gl_FrontColor;\n"
2078 "#ifdef USEDIFFUSE\n"
2079 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2082 "#ifdef USESPECULAR\n"
2083 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2084 "# ifdef USECOLORMAPPING\n"
2085 " gl_FragColor *= tex2;\n"
2088 " gl_FragColor += tex2;\n"
2090 "# ifdef USEVERTEXTEXTUREBLEND\n"
2091 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2096 "#else // !MODE_GENERIC\n"
2101 "#ifdef MODE_BLOOMBLUR\n"
2102 "#ifdef VERTEX_SHADER\n"
2105 "float4 gl_Vertex : POSITION,\n"
2106 "uniform float4x4 ModelViewProjectionMatrix,\n"
2107 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2108 "out float4 gl_Position : POSITION,\n"
2109 "out float2 TexCoord : TEXCOORD0\n"
2112 " TexCoord = gl_MultiTexCoord0.xy;\n"
2113 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2117 "#ifdef FRAGMENT_SHADER\n"
2121 "float2 TexCoord : TEXCOORD0,\n"
2122 "uniform sampler2D Texture_First,\n"
2123 "uniform float4 BloomBlur_Parameters,\n"
2124 "out float4 gl_FragColor : COLOR\n"
2128 " float2 tc = TexCoord;\n"
2129 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2130 " tc += BloomBlur_Parameters.xy;\n"
2131 " for (i = 1;i < SAMPLES;i++)\n"
2133 " color += tex2D(Texture_First, tc).rgb;\n"
2134 " tc += BloomBlur_Parameters.xy;\n"
2136 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2139 "#else // !MODE_BLOOMBLUR\n"
2140 "#ifdef MODE_REFRACTION\n"
2141 "#ifdef VERTEX_SHADER\n"
2144 "float4 gl_Vertex : POSITION,\n"
2145 "uniform float4x4 ModelViewProjectionMatrix,\n"
2146 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2147 "uniform float4x4 TexMatrix,\n"
2148 "uniform float3 EyePosition,\n"
2149 "out float4 gl_Position : POSITION,\n"
2150 "out float2 TexCoord : TEXCOORD0,\n"
2151 "out float3 EyeVector : TEXCOORD1,\n"
2152 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2155 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2156 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2157 " ModelViewProjectionPosition = gl_Position;\n"
2161 "#ifdef FRAGMENT_SHADER\n"
2164 "float2 TexCoord : TEXCOORD0,\n"
2165 "float3 EyeVector : TEXCOORD1,\n"
2166 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2167 "uniform sampler2D Texture_Normal,\n"
2168 "uniform sampler2D Texture_Refraction,\n"
2169 "uniform sampler2D Texture_Reflection,\n"
2170 "uniform float4 DistortScaleRefractReflect,\n"
2171 "uniform float4 ScreenScaleRefractReflect,\n"
2172 "uniform float4 ScreenCenterRefractReflect,\n"
2173 "uniform float4 RefractColor,\n"
2174 "out float4 gl_FragColor : COLOR\n"
2177 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2178 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2179 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2180 " float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2181 " // FIXME temporary hack to detect the case that the reflection\n"
2182 " // gets blackened at edges due to leaving the area that contains actual\n"
2184 " // Remove this 'ack once we have a better way to stop this thing from\n"
2186 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2187 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2188 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2189 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2190 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2191 " gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2194 "#else // !MODE_REFRACTION\n"
2199 "#ifdef MODE_WATER\n"
2200 "#ifdef VERTEX_SHADER\n"
2204 "float4 gl_Vertex : POSITION,\n"
2205 "uniform float4x4 ModelViewProjectionMatrix,\n"
2206 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2207 "uniform float4x4 TexMatrix,\n"
2208 "uniform float3 EyePosition,\n"
2209 "out float4 gl_Position : POSITION,\n"
2210 "out float2 TexCoord : TEXCOORD0,\n"
2211 "out float3 EyeVector : TEXCOORD1,\n"
2212 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2215 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2216 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2217 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2218 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2219 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2220 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2221 " ModelViewProjectionPosition = gl_Position;\n"
2225 "#ifdef FRAGMENT_SHADER\n"
2228 "float2 TexCoord : TEXCOORD0,\n"
2229 "float3 EyeVector : TEXCOORD1,\n"
2230 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2231 "uniform sampler2D Texture_Normal,\n"
2232 "uniform sampler2D Texture_Refraction,\n"
2233 "uniform sampler2D Texture_Reflection,\n"
2234 "uniform float4 DistortScaleRefractReflect,\n"
2235 "uniform float4 ScreenScaleRefractReflect,\n"
2236 "uniform float4 ScreenCenterRefractReflect,\n"
2237 "uniform float4 RefractColor,\n"
2238 "uniform float4 ReflectColor,\n"
2239 "uniform float ReflectFactor,\n"
2240 "uniform float ReflectOffset,\n"
2241 "out float4 gl_FragColor : COLOR\n"
2244 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2245 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2246 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2247 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2248 " // FIXME temporary hack to detect the case that the reflection\n"
2249 " // gets blackened at edges due to leaving the area that contains actual\n"
2251 " // Remove this 'ack once we have a better way to stop this thing from\n"
2253 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2254 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2255 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2256 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2257 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2258 " f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2259 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2260 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2261 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2262 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2263 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2264 " gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2267 "#else // !MODE_WATER\n"
2272 "// 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"
2274 "// fragment shader specific:\n"
2275 "#ifdef FRAGMENT_SHADER\n"
2278 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask, sampler2D Texture_FogHeightTexture)\n"
2281 "#ifdef USEFOGHEIGHTTEXTURE\n"
2282 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2283 " fogfrac = fogheightpixel.a;\n"
2284 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2286 "# ifdef USEFOGOUTSIDE\n"
2287 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2289 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2291 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2296 "#ifdef USEOFFSETMAPPING\n"
2297 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2299 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2300 " // 14 sample relief mapping: linear search and then binary search\n"
2301 " // this basically steps forward a small amount repeatedly until it finds\n"
2302 " // itself inside solid, then jitters forward and back using decreasing\n"
2303 " // amounts to find the impact\n"
2304 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2305 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2306 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2307 " float3 RT = float3(TexCoord, 1);\n"
2308 " OffsetVector *= 0.1;\n"
2309 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2310 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2311 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2312 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2313 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2314 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2315 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2316 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2317 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2318 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2319 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2320 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2321 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2322 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2325 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2326 " // this basically moves forward the full distance, and then backs up based\n"
2327 " // on height of samples\n"
2328 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2329 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2330 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2331 " TexCoord += OffsetVector;\n"
2332 " OffsetVector *= 0.333;\n"
2333 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2334 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2335 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2336 " return TexCoord;\n"
2339 "#endif // USEOFFSETMAPPING\n"
2341 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2342 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2343 "# ifdef USESHADOWMAPORTHO\n"
2344 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2346 "# ifdef USESHADOWMAPVSDCT\n"
2347 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2349 " float3 adir = abs(dir);\n"
2350 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2351 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2352 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2355 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2357 " float3 adir = abs(dir);\n"
2358 " float ma = adir.z;\n"
2359 " float4 proj = float4(dir, 2.5);\n"
2360 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2361 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2362 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2363 " 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"
2367 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2369 "#ifdef USESHADOWMAPCUBE\n"
2370 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2372 " float3 adir = abs(dir);\n"
2373 " return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2377 "# ifdef USESHADOWMAPRECT\n"
2378 "#ifdef USESHADOWMAPVSDCT\n"
2379 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2381 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2384 "#ifdef USESHADOWMAPVSDCT\n"
2385 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2387 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2390 "# ifdef USESHADOWSAMPLER\n"
2392 "# ifdef USESHADOWMAPPCF\n"
2393 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2394 " 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"
2396 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2401 "# ifdef USESHADOWMAPPCF\n"
2402 "# if USESHADOWMAPPCF > 1\n"
2403 "# define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2404 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2405 " 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"
2406 " 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"
2407 " 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"
2408 " 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"
2409 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2410 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2412 "# define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2413 " float2 offset = frac(shadowmaptc.xy);\n"
2414 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2415 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2416 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2417 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2418 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2421 " f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2425 "# ifdef USESHADOWMAPORTHO\n"
2426 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2433 "# ifdef USESHADOWMAP2D\n"
2434 "#ifdef USESHADOWMAPVSDCT\n"
2435 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2437 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2440 "#ifdef USESHADOWMAPVSDCT\n"
2441 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2443 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2447 "# ifdef USESHADOWSAMPLER\n"
2448 "# ifdef USESHADOWMAPPCF\n"
2449 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
2450 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2451 " 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"
2453 " f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2456 "# ifdef USESHADOWMAPPCF\n"
2457 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2458 "# ifdef GL_ARB_texture_gather\n"
2459 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2461 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2463 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2464 " center *= ShadowMap_TextureScale;\n"
2465 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2466 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2467 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2468 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2469 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2470 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2471 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2473 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale) \n"
2474 "# if USESHADOWMAPPCF > 1\n"
2475 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2476 " center *= ShadowMap_TextureScale;\n"
2477 " 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"
2478 " 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"
2479 " 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"
2480 " 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"
2481 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2482 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2484 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2485 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2486 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2487 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2488 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2489 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2493 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2496 "# ifdef USESHADOWMAPORTHO\n"
2497 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2504 "# ifdef USESHADOWMAPCUBE\n"
2505 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2507 " // apply depth texture cubemap as light filter\n"
2508 " float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2510 "# ifdef USESHADOWSAMPLER\n"
2511 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2513 " f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2518 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2519 "#endif // FRAGMENT_SHADER\n"
2524 "#ifdef MODE_DEFERREDGEOMETRY\n"
2525 "#ifdef VERTEX_SHADER\n"
2528 "float4 gl_Vertex : POSITION,\n"
2529 "uniform float4x4 ModelViewProjectionMatrix,\n"
2530 "#ifdef USEVERTEXTEXTUREBLEND\n"
2531 "float4 gl_Color : COLOR0,\n"
2533 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2534 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2535 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2536 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2537 "uniform float4x4 TexMatrix,\n"
2538 "#ifdef USEVERTEXTEXTUREBLEND\n"
2539 "uniform float4x4 BackgroundTexMatrix,\n"
2541 "uniform float4x4 ModelViewMatrix,\n"
2542 "#ifdef USEOFFSETMAPPING\n"
2543 "uniform float3 EyePosition,\n"
2545 "out float4 gl_Position : POSITION,\n"
2546 "out float4 gl_FrontColor : COLOR,\n"
2547 "out float4 TexCoordBoth : TEXCOORD0,\n"
2548 "#ifdef USEOFFSETMAPPING\n"
2549 "out float3 EyeVector : TEXCOORD2,\n"
2551 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2552 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2553 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2556 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2557 "#ifdef USEVERTEXTEXTUREBLEND\n"
2558 " gl_FrontColor = gl_Color;\n"
2559 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2562 " // transform unnormalized eye direction into tangent space\n"
2563 "#ifdef USEOFFSETMAPPING\n"
2564 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2565 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2566 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2567 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2570 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2571 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2572 " VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2573 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2575 "#endif // VERTEX_SHADER\n"
2577 "#ifdef FRAGMENT_SHADER\n"
2580 "float4 TexCoordBoth : TEXCOORD0,\n"
2581 "float3 EyeVector : TEXCOORD2,\n"
2582 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2583 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2584 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2585 "uniform sampler2D Texture_Normal,\n"
2586 "#ifdef USEALPHAKILL\n"
2587 "uniform sampler2D Texture_Color,\n"
2589 "uniform sampler2D Texture_Gloss,\n"
2590 "#ifdef USEVERTEXTEXTUREBLEND\n"
2591 "uniform sampler2D Texture_SecondaryNormal,\n"
2592 "uniform sampler2D Texture_SecondaryGloss,\n"
2594 "#ifdef USEOFFSETMAPPING\n"
2595 "uniform float OffsetMapping_Scale,\n"
2597 "uniform half SpecularPower,\n"
2598 "out float4 gl_FragColor : COLOR\n"
2601 " float2 TexCoord = TexCoordBoth.xy;\n"
2602 "#ifdef USEOFFSETMAPPING\n"
2603 " // apply offsetmapping\n"
2604 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2605 "#define TexCoord TexCoordOffset\n"
2608 "#ifdef USEALPHAKILL\n"
2609 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2613 "#ifdef USEVERTEXTEXTUREBLEND\n"
2614 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2615 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2616 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2617 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2620 "#ifdef USEVERTEXTEXTUREBLEND\n"
2621 " float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2622 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2624 " float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2625 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2628 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2630 "#endif // FRAGMENT_SHADER\n"
2631 "#else // !MODE_DEFERREDGEOMETRY\n"
2636 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2637 "#ifdef VERTEX_SHADER\n"
2640 "float4 gl_Vertex : POSITION,\n"
2641 "uniform float4x4 ModelViewProjectionMatrix,\n"
2642 "uniform float4x4 ModelViewMatrix,\n"
2643 "out float4 gl_Position : POSITION,\n"
2644 "out float4 ModelViewPosition : TEXCOORD0\n"
2647 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2648 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2650 "#endif // VERTEX_SHADER\n"
2652 "#ifdef FRAGMENT_SHADER\n"
2655 "float2 Pixel : WPOS,\n"
2656 "float4 ModelViewPosition : TEXCOORD0,\n"
2657 "uniform float4x4 ViewToLight,\n"
2658 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2659 "uniform float3 LightPosition,\n"
2660 "uniform half2 PixelToScreenTexCoord,\n"
2661 "uniform half3 DeferredColor_Ambient,\n"
2662 "uniform half3 DeferredColor_Diffuse,\n"
2663 "#ifdef USESPECULAR\n"
2664 "uniform half3 DeferredColor_Specular,\n"
2665 "uniform half SpecularPower,\n"
2667 "uniform sampler2D Texture_Attenuation,\n"
2668 "uniform sampler2D Texture_ScreenDepth,\n"
2669 "uniform sampler2D Texture_ScreenNormalMap,\n"
2671 "#ifdef USECUBEFILTER\n"
2672 "uniform samplerCUBE Texture_Cube,\n"
2675 "#ifdef USESHADOWMAPRECT\n"
2676 "# ifdef USESHADOWSAMPLER\n"
2677 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2679 "uniform samplerRECT Texture_ShadowMapRect,\n"
2683 "#ifdef USESHADOWMAP2D\n"
2684 "# ifdef USESHADOWSAMPLER\n"
2685 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2687 "uniform sampler2D Texture_ShadowMap2D,\n"
2691 "#ifdef USESHADOWMAPVSDCT\n"
2692 "uniform samplerCUBE Texture_CubeProjection,\n"
2695 "#ifdef USESHADOWMAPCUBE\n"
2696 "# ifdef USESHADOWSAMPLER\n"
2697 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2699 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2703 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2704 "uniform float2 ShadowMap_TextureScale,\n"
2705 "uniform float4 ShadowMap_Parameters,\n"
2708 "out float4 gl_FragData0 : COLOR0,\n"
2709 "out float4 gl_FragData1 : COLOR1\n"
2712 " // calculate viewspace pixel position\n"
2713 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2714 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2715 " float3 position;\n"
2716 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2717 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2718 " // decode viewspace pixel normal\n"
2719 " half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2720 " half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2721 " // surfacenormal = pixel normal in viewspace\n"
2722 " // LightVector = pixel to light in viewspace\n"
2723 " // CubeVector = position in lightspace\n"
2724 " // eyevector = pixel to view in viewspace\n"
2725 " float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2726 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2727 "#ifdef USEDIFFUSE\n"
2728 " // calculate diffuse shading\n"
2729 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2730 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2732 "#ifdef USESPECULAR\n"
2733 " // calculate directional shading\n"
2734 " float3 eyevector = position * -1.0;\n"
2735 "# ifdef USEEXACTSPECULARMATH\n"
2736 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2738 " half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2739 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2743 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2744 " fade *= ShadowMapCompare(CubeVector,\n"
2745 "# if defined(USESHADOWMAP2D)\n"
2746 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2748 "# if defined(USESHADOWMAPRECT)\n"
2749 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2751 "# if defined(USESHADOWMAPCUBE)\n"
2752 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2755 "#ifdef USESHADOWMAPVSDCT\n"
2756 ", Texture_CubeProjection\n"
2761 "#ifdef USEDIFFUSE\n"
2762 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2764 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2766 "#ifdef USESPECULAR\n"
2767 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2769 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2772 "# ifdef USECUBEFILTER\n"
2773 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2774 " gl_FragData0.rgb *= cubecolor;\n"
2775 " gl_FragData1.rgb *= cubecolor;\n"
2778 "#endif // FRAGMENT_SHADER\n"
2779 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2784 "#ifdef VERTEX_SHADER\n"
2787 "float4 gl_Vertex : POSITION,\n"
2788 "uniform float4x4 ModelViewProjectionMatrix,\n"
2789 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2790 "float4 gl_Color : COLOR0,\n"
2792 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2793 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2794 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2795 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2796 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2798 "uniform float3 EyePosition,\n"
2799 "uniform float4x4 TexMatrix,\n"
2800 "#ifdef USEVERTEXTEXTUREBLEND\n"
2801 "uniform float4x4 BackgroundTexMatrix,\n"
2803 "#ifdef MODE_LIGHTSOURCE\n"
2804 "uniform float4x4 ModelToLight,\n"
2806 "#ifdef MODE_LIGHTSOURCE\n"
2807 "uniform float3 LightPosition,\n"
2809 "#ifdef MODE_LIGHTDIRECTION\n"
2810 "uniform float3 LightDir,\n"
2812 "uniform float4 FogPlane,\n"
2813 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2814 "uniform float3 LightPosition,\n"
2816 "#ifdef USESHADOWMAPORTHO\n"
2817 "uniform float4x4 ShadowMapMatrix,\n"
2820 "out float4 gl_FrontColor : COLOR,\n"
2821 "out float4 TexCoordBoth : TEXCOORD0,\n"
2822 "#ifdef USELIGHTMAP\n"
2823 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2825 "#ifdef USEEYEVECTOR\n"
2826 "out float3 EyeVector : TEXCOORD2,\n"
2828 "#ifdef USEREFLECTION\n"
2829 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2832 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2834 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2835 "out float3 LightVector : TEXCOORD1,\n"
2837 "#ifdef MODE_LIGHTSOURCE\n"
2838 "out float3 CubeVector : TEXCOORD3,\n"
2840 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2841 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2842 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2843 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2845 "#ifdef USESHADOWMAPORTHO\n"
2846 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2848 "out float4 gl_Position : POSITION\n"
2851 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2852 " gl_FrontColor = gl_Color;\n"
2854 " // copy the surface texcoord\n"
2855 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2856 "#ifdef USEVERTEXTEXTUREBLEND\n"
2857 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2859 "#ifdef USELIGHTMAP\n"
2860 " TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2863 "#ifdef MODE_LIGHTSOURCE\n"
2864 " // transform vertex position into light attenuation/cubemap space\n"
2865 " // (-1 to +1 across the light box)\n"
2866 " CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2868 "# ifdef USEDIFFUSE\n"
2869 " // transform unnormalized light direction into tangent space\n"
2870 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2871 " // normalize it per pixel)\n"
2872 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2873 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2874 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2875 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2879 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2880 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2881 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2882 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2885 " // transform unnormalized eye direction into tangent space\n"
2886 "#ifdef USEEYEVECTOR\n"
2887 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2888 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2889 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2890 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2894 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2895 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2898 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2899 " VectorS = gl_MultiTexCoord1.xyz;\n"
2900 " VectorT = gl_MultiTexCoord2.xyz;\n"
2901 " VectorR = gl_MultiTexCoord3.xyz;\n"
2904 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2905 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2907 "#ifdef USESHADOWMAPORTHO\n"
2908 " ShadowMapTC = float3(mul(ShadowMapMatrix, gl_Position));\n"
2911 "#ifdef USEREFLECTION\n"
2912 " ModelViewProjectionPosition = gl_Position;\n"
2915 "#endif // VERTEX_SHADER\n"
2920 "#ifdef FRAGMENT_SHADER\n"
2923 "#ifdef USEDEFERREDLIGHTMAP\n"
2924 "float2 Pixel : WPOS,\n"
2926 "float4 gl_FrontColor : COLOR,\n"
2927 "float4 TexCoordBoth : TEXCOORD0,\n"
2928 "#ifdef USELIGHTMAP\n"
2929 "float2 TexCoordLightmap : TEXCOORD1,\n"
2931 "#ifdef USEEYEVECTOR\n"
2932 "float3 EyeVector : TEXCOORD2,\n"
2934 "#ifdef USEREFLECTION\n"
2935 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2938 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2940 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2941 "float3 LightVector : TEXCOORD1,\n"
2943 "#ifdef MODE_LIGHTSOURCE\n"
2944 "float3 CubeVector : TEXCOORD3,\n"
2946 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2947 "float4 ModelViewPosition : TEXCOORD0,\n"
2949 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2950 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2951 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2952 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2954 "#ifdef USESHADOWMAPORTHO\n"
2955 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2958 "uniform sampler2D Texture_Normal,\n"
2959 "uniform sampler2D Texture_Color,\n"
2960 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2961 "uniform sampler2D Texture_Gloss,\n"
2964 "uniform sampler2D Texture_Glow,\n"
2966 "#ifdef USEVERTEXTEXTUREBLEND\n"
2967 "uniform sampler2D Texture_SecondaryNormal,\n"
2968 "uniform sampler2D Texture_SecondaryColor,\n"
2969 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2970 "uniform sampler2D Texture_SecondaryGloss,\n"
2973 "uniform sampler2D Texture_SecondaryGlow,\n"
2976 "#ifdef USECOLORMAPPING\n"
2977 "uniform sampler2D Texture_Pants,\n"
2978 "uniform sampler2D Texture_Shirt,\n"
2981 "uniform sampler2D Texture_FogHeightTexture,\n"
2982 "uniform sampler2D Texture_FogMask,\n"
2984 "#ifdef USELIGHTMAP\n"
2985 "uniform sampler2D Texture_Lightmap,\n"
2987 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2988 "uniform sampler2D Texture_Deluxemap,\n"
2990 "#ifdef USEREFLECTION\n"
2991 "uniform sampler2D Texture_Reflection,\n"
2994 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2995 "uniform sampler2D Texture_ScreenDepth,\n"
2996 "uniform sampler2D Texture_ScreenNormalMap,\n"
2998 "#ifdef USEDEFERREDLIGHTMAP\n"
2999 "uniform sampler2D Texture_ScreenDiffuse,\n"
3000 "uniform sampler2D Texture_ScreenSpecular,\n"
3003 "#ifdef USECOLORMAPPING\n"
3004 "uniform half3 Color_Pants,\n"
3005 "uniform half3 Color_Shirt,\n"
3008 "uniform float3 FogColor,\n"
3009 "uniform float FogRangeRecip,\n"
3010 "uniform float FogPlaneViewDist,\n"
3011 "uniform float FogHeightFade,\n"
3014 "#ifdef USEOFFSETMAPPING\n"
3015 "uniform float OffsetMapping_Scale,\n"
3018 "#ifdef USEDEFERREDLIGHTMAP\n"
3019 "uniform half2 PixelToScreenTexCoord,\n"
3020 "uniform half3 DeferredMod_Diffuse,\n"
3021 "uniform half3 DeferredMod_Specular,\n"
3023 "uniform half3 Color_Ambient,\n"
3024 "uniform half3 Color_Diffuse,\n"
3025 "uniform half3 Color_Specular,\n"
3026 "uniform half SpecularPower,\n"
3028 "uniform half3 Color_Glow,\n"
3030 "uniform half Alpha,\n"
3031 "#ifdef USEREFLECTION\n"
3032 "uniform float4 DistortScaleRefractReflect,\n"
3033 "uniform float4 ScreenScaleRefractReflect,\n"
3034 "uniform float4 ScreenCenterRefractReflect,\n"
3035 "uniform half4 ReflectColor,\n"
3037 "#ifdef USEREFLECTCUBE\n"
3038 "uniform float4x4 ModelToReflectCube,\n"
3039 "uniform sampler2D Texture_ReflectMask,\n"
3040 "uniform samplerCUBE Texture_ReflectCube,\n"
3042 "#ifdef MODE_LIGHTDIRECTION\n"
3043 "uniform half3 LightColor,\n"
3045 "#ifdef MODE_LIGHTSOURCE\n"
3046 "uniform half3 LightColor,\n"
3049 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3050 "uniform sampler2D Texture_Attenuation,\n"
3051 "uniform samplerCUBE Texture_Cube,\n"
3054 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3056 "#ifdef USESHADOWMAPRECT\n"
3057 "# ifdef USESHADOWSAMPLER\n"
3058 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
3060 "uniform samplerRECT Texture_ShadowMapRect,\n"
3064 "#ifdef USESHADOWMAP2D\n"
3065 "# ifdef USESHADOWSAMPLER\n"
3066 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
3068 "uniform sampler2D Texture_ShadowMap2D,\n"
3072 "#ifdef USESHADOWMAPVSDCT\n"
3073 "uniform samplerCUBE Texture_CubeProjection,\n"
3076 "#ifdef USESHADOWMAPCUBE\n"
3077 "# ifdef USESHADOWSAMPLER\n"
3078 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
3080 "uniform samplerCUBE Texture_ShadowMapCube,\n"
3084 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3085 "uniform float2 ShadowMap_TextureScale,\n"
3086 "uniform float4 ShadowMap_Parameters,\n"
3088 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3090 "out float4 gl_FragColor : COLOR\n"
3093 " float2 TexCoord = TexCoordBoth.xy;\n"
3094 "#ifdef USEVERTEXTEXTUREBLEND\n"
3095 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3097 "#ifdef USEOFFSETMAPPING\n"
3098 " // apply offsetmapping\n"
3099 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3100 "#define TexCoord TexCoordOffset\n"
3103 " // combine the diffuse textures (base, pants, shirt)\n"
3104 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3105 "#ifdef USEALPHAKILL\n"
3106 " if (color.a < 0.5)\n"
3109 " color.a *= Alpha;\n"
3110 "#ifdef USECOLORMAPPING\n"
3111 " color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
3113 "#ifdef USEVERTEXTEXTUREBLEND\n"
3114 " float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3115 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3116 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3117 " color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
3119 " //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
3122 " // get the surface normal\n"
3123 "#ifdef USEVERTEXTEXTUREBLEND\n"
3124 " half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3126 " half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
3129 " // get the material colors\n"
3130 " half3 diffusetex = color.rgb;\n"
3131 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3132 "# ifdef USEVERTEXTEXTUREBLEND\n"
3133 " half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
3135 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3139 "#ifdef USEREFLECTCUBE\n"
3140 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3141 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3142 " float3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
3143 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
3149 "#ifdef MODE_LIGHTSOURCE\n"
3150 " // light source\n"
3151 "#ifdef USEDIFFUSE\n"
3152 " half3 lightnormal = half3(normalize(LightVector));\n"
3153 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3154 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3155 "#ifdef USESPECULAR\n"
3156 "#ifdef USEEXACTSPECULARMATH\n"
3157 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3159 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3160 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3162 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3165 " color.rgb = diffusetex * Color_Ambient;\n"
3167 " color.rgb *= LightColor;\n"
3168 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3169 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3170 " color.rgb *= ShadowMapCompare(CubeVector,\n"
3171 "# if defined(USESHADOWMAP2D)\n"
3172 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3174 "# if defined(USESHADOWMAPRECT)\n"
3175 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3177 "# if defined(USESHADOWMAPCUBE)\n"
3178 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3181 "#ifdef USESHADOWMAPVSDCT\n"
3182 ", Texture_CubeProjection\n"
3187 "# ifdef USECUBEFILTER\n"
3188 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3190 "#endif // MODE_LIGHTSOURCE\n"
3195 "#ifdef MODE_LIGHTDIRECTION\n"
3197 "#ifdef USEDIFFUSE\n"
3198 " half3 lightnormal = half3(normalize(LightVector));\n"
3200 "#define lightcolor LightColor\n"
3201 "#endif // MODE_LIGHTDIRECTION\n"
3202 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3204 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3205 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3206 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3207 " // convert modelspace light vector to tangentspace\n"
3208 " half3 lightnormal;\n"
3209 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3210 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3211 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3212 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3213 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3214 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3215 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3216 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3217 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3218 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3219 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3220 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3221 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3222 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3223 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3225 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3226 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3227 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3233 "#ifdef MODE_LIGHTMAP\n"
3234 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3235 "#endif // MODE_LIGHTMAP\n"
3236 "#ifdef MODE_VERTEXCOLOR\n"
3237 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3238 "#endif // MODE_VERTEXCOLOR\n"
3239 "#ifdef MODE_FLATCOLOR\n"
3240 " color.rgb = diffusetex * Color_Ambient;\n"
3241 "#endif // MODE_FLATCOLOR\n"
3247 "# ifdef USEDIFFUSE\n"
3248 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3249 "# ifdef USESPECULAR\n"
3250 "# ifdef USEEXACTSPECULARMATH\n"
3251 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3253 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3254 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3256 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3258 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3261 " color.rgb = diffusetex * Color_Ambient;\n"
3265 "#ifdef USESHADOWMAPORTHO\n"
3266 " color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3267 "# if defined(USESHADOWMAP2D)\n"
3268 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3270 "# if defined(USESHADOWMAPRECT)\n"
3271 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3276 "#ifdef USEDEFERREDLIGHTMAP\n"
3277 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3278 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3279 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3283 "#ifdef USEVERTEXTEXTUREBLEND\n"
3284 " color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3286 " color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3291 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3294 " // 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"
3295 "#ifdef USEREFLECTION\n"
3296 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3297 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3298 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3299 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3300 " // FIXME temporary hack to detect the case that the reflection\n"
3301 " // gets blackened at edges due to leaving the area that contains actual\n"
3303 " // Remove this 'ack once we have a better way to stop this thing from\n"
3305 " float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3306 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3307 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3308 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3309 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3310 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3313 " gl_FragColor = float4(color);\n"
3315 "#endif // FRAGMENT_SHADER\n"
3317 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3318 "#endif // !MODE_DEFERREDGEOMETRY\n"
3319 "#endif // !MODE_WATER\n"
3320 "#endif // !MODE_REFRACTION\n"
3321 "#endif // !MODE_BLOOMBLUR\n"
3322 "#endif // !MODE_GENERIC\n"
3323 "#endif // !MODE_POSTPROCESS\n"
3324 "#endif // !MODE_SHOWDEPTH\n"
3325 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3328 char *glslshaderstring = NULL;
3329 char *cgshaderstring = NULL;
3330 char *hlslshaderstring = NULL;
3332 //=======================================================================================================================================================
3334 typedef struct shaderpermutationinfo_s
3336 const char *pretext;
3339 shaderpermutationinfo_t;
3341 typedef struct shadermodeinfo_s
3343 const char *vertexfilename;
3344 const char *geometryfilename;
3345 const char *fragmentfilename;
3346 const char *pretext;
3351 typedef enum shaderpermutation_e
3353 SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3354 SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3355 SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3356 SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3357 SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3358 SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3359 SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3360 SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3361 SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3362 SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3363 SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3364 SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3365 SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3366 SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3367 SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3368 SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3369 SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3370 SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3371 SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3372 SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3373 SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3374 SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3375 SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3376 SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3377 SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3378 SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3379 SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3380 SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3381 SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3382 SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3383 SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3385 shaderpermutation_t;
3387 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3388 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3390 {"#define USEDIFFUSE\n", " diffuse"},
3391 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3392 {"#define USEVIEWTINT\n", " viewtint"},
3393 {"#define USECOLORMAPPING\n", " colormapping"},
3394 {"#define USESATURATION\n", " saturation"},
3395 {"#define USEFOGINSIDE\n", " foginside"},
3396 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3397 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3398 {"#define USEGAMMARAMPS\n", " gammaramps"},
3399 {"#define USECUBEFILTER\n", " cubefilter"},
3400 {"#define USEGLOW\n", " glow"},
3401 {"#define USEBLOOM\n", " bloom"},
3402 {"#define USESPECULAR\n", " specular"},
3403 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3404 {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3405 {"#define USEREFLECTION\n", " reflection"},
3406 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3407 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3408 {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3409 {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3410 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3411 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3412 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3413 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3414 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3415 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3416 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3417 {"#define USEALPHAKILL\n", " alphakill"},
3418 {"#define USEREFLECTCUBE\n", " reflectcube"},
3421 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3422 typedef enum shadermode_e
3424 SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3425 SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3426 SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3427 SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3428 SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3429 SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3430 SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3431 SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3432 SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3433 SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3434 SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3435 SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3436 SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3437 SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3438 SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3443 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3444 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3446 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3447 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3448 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3449 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3450 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3451 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3452 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3453 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3454 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3455 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3456 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3457 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3458 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3459 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3460 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3464 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3466 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3467 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3468 {"cg/default.cg", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3469 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3470 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3471 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3472 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3473 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3474 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3475 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3476 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3477 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3478 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3479 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3480 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3485 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
3487 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
3488 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3489 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3490 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3491 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3492 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3493 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3494 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3495 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3496 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3497 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
3498 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
3499 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3500 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3501 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3505 struct r_glsl_permutation_s;
3506 typedef struct r_glsl_permutation_s
3508 /// hash lookup data
3509 struct r_glsl_permutation_s *hashnext;
3511 unsigned int permutation;
3513 /// indicates if we have tried compiling this permutation already
3515 /// 0 if compilation failed
3517 /// locations of detected uniforms in program object, or -1 if not found
3518 int loc_Texture_First;
3519 int loc_Texture_Second;
3520 int loc_Texture_GammaRamps;
3521 int loc_Texture_Normal;
3522 int loc_Texture_Color;
3523 int loc_Texture_Gloss;
3524 int loc_Texture_Glow;
3525 int loc_Texture_SecondaryNormal;
3526 int loc_Texture_SecondaryColor;
3527 int loc_Texture_SecondaryGloss;
3528 int loc_Texture_SecondaryGlow;
3529 int loc_Texture_Pants;
3530 int loc_Texture_Shirt;
3531 int loc_Texture_FogHeightTexture;
3532 int loc_Texture_FogMask;
3533 int loc_Texture_Lightmap;
3534 int loc_Texture_Deluxemap;
3535 int loc_Texture_Attenuation;
3536 int loc_Texture_Cube;
3537 int loc_Texture_Refraction;
3538 int loc_Texture_Reflection;
3539 int loc_Texture_ShadowMapRect;
3540 int loc_Texture_ShadowMapCube;
3541 int loc_Texture_ShadowMap2D;
3542 int loc_Texture_CubeProjection;
3543 int loc_Texture_ScreenDepth;
3544 int loc_Texture_ScreenNormalMap;
3545 int loc_Texture_ScreenDiffuse;
3546 int loc_Texture_ScreenSpecular;
3547 int loc_Texture_ReflectMask;
3548 int loc_Texture_ReflectCube;
3550 int loc_BloomBlur_Parameters;
3552 int loc_Color_Ambient;
3553 int loc_Color_Diffuse;
3554 int loc_Color_Specular;
3556 int loc_Color_Pants;
3557 int loc_Color_Shirt;
3558 int loc_DeferredColor_Ambient;
3559 int loc_DeferredColor_Diffuse;
3560 int loc_DeferredColor_Specular;
3561 int loc_DeferredMod_Diffuse;
3562 int loc_DeferredMod_Specular;
3563 int loc_DistortScaleRefractReflect;
3564 int loc_EyePosition;
3566 int loc_FogHeightFade;
3568 int loc_FogPlaneViewDist;
3569 int loc_FogRangeRecip;
3572 int loc_LightPosition;
3573 int loc_OffsetMapping_Scale;
3575 int loc_ReflectColor;
3576 int loc_ReflectFactor;
3577 int loc_ReflectOffset;
3578 int loc_RefractColor;
3580 int loc_ScreenCenterRefractReflect;
3581 int loc_ScreenScaleRefractReflect;
3582 int loc_ScreenToDepth;
3583 int loc_ShadowMap_Parameters;
3584 int loc_ShadowMap_TextureScale;
3585 int loc_SpecularPower;
3590 int loc_ViewTintColor;
3591 int loc_ViewToLight;
3592 int loc_ModelToLight;
3594 int loc_BackgroundTexMatrix;
3595 int loc_ModelViewProjectionMatrix;
3596 int loc_ModelViewMatrix;
3597 int loc_PixelToScreenTexCoord;
3598 int loc_ModelToReflectCube;
3599 int loc_ShadowMapMatrix;
3600 int loc_BloomColorSubtract;
3602 r_glsl_permutation_t;
3604 #define SHADERPERMUTATION_HASHSIZE 256
3606 /// information about each possible shader permutation
3607 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3608 /// currently selected permutation
3609 r_glsl_permutation_t *r_glsl_permutation;
3610 /// storage for permutations linked in the hash table
3611 memexpandablearray_t r_glsl_permutationarray;
3613 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3615 //unsigned int hashdepth = 0;
3616 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3617 r_glsl_permutation_t *p;
3618 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3620 if (p->mode == mode && p->permutation == permutation)
3622 //if (hashdepth > 10)
3623 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3628 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3630 p->permutation = permutation;
3631 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3632 r_glsl_permutationhash[mode][hashindex] = p;
3633 //if (hashdepth > 10)
3634 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3638 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3641 if (!filename || !filename[0])
3643 if (!strcmp(filename, "glsl/default.glsl"))
3645 if (!glslshaderstring)
3647 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3648 if (glslshaderstring)
3649 Con_DPrintf("Loading shaders from file %s...\n", filename);
3651 glslshaderstring = (char *)builtinshaderstring;
3653 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3654 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3655 return shaderstring;
3657 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3660 if (printfromdisknotice)
3661 Con_DPrintf("from disk %s... ", filename);
3662 return shaderstring;
3664 return shaderstring;
3667 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3670 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3671 int vertstrings_count = 0;
3672 int geomstrings_count = 0;
3673 int fragstrings_count = 0;
3674 char *vertexstring, *geometrystring, *fragmentstring;
3675 const char *vertstrings_list[32+3];
3676 const char *geomstrings_list[32+3];
3677 const char *fragstrings_list[32+3];
3678 char permutationname[256];
3685 permutationname[0] = 0;
3686 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3687 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3688 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3690 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3692 // the first pretext is which type of shader to compile as
3693 // (later these will all be bound together as a program object)
3694 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3695 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3696 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3698 // the second pretext is the mode (for example a light source)
3699 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3700 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3701 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3702 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3704 // now add all the permutation pretexts
3705 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3707 if (permutation & (1<<i))
3709 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3710 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3711 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3712 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3716 // keep line numbers correct
3717 vertstrings_list[vertstrings_count++] = "\n";
3718 geomstrings_list[geomstrings_count++] = "\n";
3719 fragstrings_list[fragstrings_count++] = "\n";
3723 // now append the shader text itself
3724 vertstrings_list[vertstrings_count++] = vertexstring;
3725 geomstrings_list[geomstrings_count++] = geometrystring;
3726 fragstrings_list[fragstrings_count++] = fragmentstring;
3728 // if any sources were NULL, clear the respective list
3730 vertstrings_count = 0;
3731 if (!geometrystring)
3732 geomstrings_count = 0;
3733 if (!fragmentstring)
3734 fragstrings_count = 0;
3736 // compile the shader program
3737 if (vertstrings_count + geomstrings_count + fragstrings_count)
3738 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3742 qglUseProgramObjectARB(p->program);CHECKGLERROR
3743 // look up all the uniform variable names we care about, so we don't
3744 // have to look them up every time we set them
3746 p->loc_Texture_First = qglGetUniformLocationARB(p->program, "Texture_First");
3747 p->loc_Texture_Second = qglGetUniformLocationARB(p->program, "Texture_Second");
3748 p->loc_Texture_GammaRamps = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3749 p->loc_Texture_Normal = qglGetUniformLocationARB(p->program, "Texture_Normal");
3750 p->loc_Texture_Color = qglGetUniformLocationARB(p->program, "Texture_Color");
3751 p->loc_Texture_Gloss = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3752 p->loc_Texture_Glow = qglGetUniformLocationARB(p->program, "Texture_Glow");
3753 p->loc_Texture_SecondaryNormal = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3754 p->loc_Texture_SecondaryColor = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3755 p->loc_Texture_SecondaryGloss = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3756 p->loc_Texture_SecondaryGlow = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3757 p->loc_Texture_Pants = qglGetUniformLocationARB(p->program, "Texture_Pants");
3758 p->loc_Texture_Shirt = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3759 p->loc_Texture_FogHeightTexture = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3760 p->loc_Texture_FogMask = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3761 p->loc_Texture_Lightmap = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3762 p->loc_Texture_Deluxemap = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3763 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3764 p->loc_Texture_Cube = qglGetUniformLocationARB(p->program, "Texture_Cube");
3765 p->loc_Texture_Refraction = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3766 p->loc_Texture_Reflection = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3767 p->loc_Texture_ShadowMapRect = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3768 p->loc_Texture_ShadowMapCube = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3769 p->loc_Texture_ShadowMap2D = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3770 p->loc_Texture_CubeProjection = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3771 p->loc_Texture_ScreenDepth = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3772 p->loc_Texture_ScreenNormalMap = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3773 p->loc_Texture_ScreenDiffuse = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3774 p->loc_Texture_ScreenSpecular = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3775 p->loc_Texture_ReflectMask = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3776 p->loc_Texture_ReflectCube = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3777 p->loc_Alpha = qglGetUniformLocationARB(p->program, "Alpha");
3778 p->loc_BloomBlur_Parameters = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3779 p->loc_ClientTime = qglGetUniformLocationARB(p->program, "ClientTime");
3780 p->loc_Color_Ambient = qglGetUniformLocationARB(p->program, "Color_Ambient");
3781 p->loc_Color_Diffuse = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3782 p->loc_Color_Specular = qglGetUniformLocationARB(p->program, "Color_Specular");
3783 p->loc_Color_Glow = qglGetUniformLocationARB(p->program, "Color_Glow");
3784 p->loc_Color_Pants = qglGetUniformLocationARB(p->program, "Color_Pants");
3785 p->loc_Color_Shirt = qglGetUniformLocationARB(p->program, "Color_Shirt");
3786 p->loc_DeferredColor_Ambient = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3787 p->loc_DeferredColor_Diffuse = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3788 p->loc_DeferredColor_Specular = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3789 p->loc_DeferredMod_Diffuse = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3790 p->loc_DeferredMod_Specular = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3791 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3792 p->loc_EyePosition = qglGetUniformLocationARB(p->program, "EyePosition");
3793 p->loc_FogColor = qglGetUniformLocationARB(p->program, "FogColor");
3794 p->loc_FogHeightFade = qglGetUniformLocationARB(p->program, "FogHeightFade");
3795 p->loc_FogPlane = qglGetUniformLocationARB(p->program, "FogPlane");
3796 p->loc_FogPlaneViewDist = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3797 p->loc_FogRangeRecip = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3798 p->loc_LightColor = qglGetUniformLocationARB(p->program, "LightColor");
3799 p->loc_LightDir = qglGetUniformLocationARB(p->program, "LightDir");
3800 p->loc_LightPosition = qglGetUniformLocationARB(p->program, "LightPosition");
3801 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3802 p->loc_PixelSize = qglGetUniformLocationARB(p->program, "PixelSize");
3803 p->loc_ReflectColor = qglGetUniformLocationARB(p->program, "ReflectColor");
3804 p->loc_ReflectFactor = qglGetUniformLocationARB(p->program, "ReflectFactor");
3805 p->loc_ReflectOffset = qglGetUniformLocationARB(p->program, "ReflectOffset");
3806 p->loc_RefractColor = qglGetUniformLocationARB(p->program, "RefractColor");
3807 p->loc_Saturation = qglGetUniformLocationARB(p->program, "Saturation");
3808 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3809 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3810 p->loc_ScreenToDepth = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3811 p->loc_ShadowMap_Parameters = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3812 p->loc_ShadowMap_TextureScale = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3813 p->loc_SpecularPower = qglGetUniformLocationARB(p->program, "SpecularPower");
3814 p->loc_UserVec1 = qglGetUniformLocationARB(p->program, "UserVec1");
3815 p->loc_UserVec2 = qglGetUniformLocationARB(p->program, "UserVec2");
3816 p->loc_UserVec3 = qglGetUniformLocationARB(p->program, "UserVec3");
3817 p->loc_UserVec4 = qglGetUniformLocationARB(p->program, "UserVec4");
3818 p->loc_ViewTintColor = qglGetUniformLocationARB(p->program, "ViewTintColor");
3819 p->loc_ViewToLight = qglGetUniformLocationARB(p->program, "ViewToLight");
3820 p->loc_ModelToLight = qglGetUniformLocationARB(p->program, "ModelToLight");
3821 p->loc_TexMatrix = qglGetUniformLocationARB(p->program, "TexMatrix");
3822 p->loc_BackgroundTexMatrix = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3823 p->loc_ModelViewMatrix = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3824 p->loc_ModelViewProjectionMatrix = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3825 p->loc_PixelToScreenTexCoord = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3826 p->loc_ModelToReflectCube = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3827 p->loc_ShadowMapMatrix = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3828 p->loc_BloomColorSubtract = qglGetUniformLocationARB(p->program, "BloomColorSubtract");
3829 // initialize the samplers to refer to the texture units we use
3830 if (p->loc_Texture_First >= 0) qglUniform1iARB(p->loc_Texture_First , GL20TU_FIRST);
3831 if (p->loc_Texture_Second >= 0) qglUniform1iARB(p->loc_Texture_Second , GL20TU_SECOND);
3832 if (p->loc_Texture_GammaRamps >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps , GL20TU_GAMMARAMPS);
3833 if (p->loc_Texture_Normal >= 0) qglUniform1iARB(p->loc_Texture_Normal , GL20TU_NORMAL);
3834 if (p->loc_Texture_Color >= 0) qglUniform1iARB(p->loc_Texture_Color , GL20TU_COLOR);
3835 if (p->loc_Texture_Gloss >= 0) qglUniform1iARB(p->loc_Texture_Gloss , GL20TU_GLOSS);
3836 if (p->loc_Texture_Glow >= 0) qglUniform1iARB(p->loc_Texture_Glow , GL20TU_GLOW);
3837 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3838 if (p->loc_Texture_SecondaryColor >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3839 if (p->loc_Texture_SecondaryGloss >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3840 if (p->loc_Texture_SecondaryGlow >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow , GL20TU_SECONDARY_GLOW);
3841 if (p->loc_Texture_Pants >= 0) qglUniform1iARB(p->loc_Texture_Pants , GL20TU_PANTS);
3842 if (p->loc_Texture_Shirt >= 0) qglUniform1iARB(p->loc_Texture_Shirt , GL20TU_SHIRT);
3843 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3844 if (p->loc_Texture_FogMask >= 0) qglUniform1iARB(p->loc_Texture_FogMask , GL20TU_FOGMASK);
3845 if (p->loc_Texture_Lightmap >= 0) qglUniform1iARB(p->loc_Texture_Lightmap , GL20TU_LIGHTMAP);
3846 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap , GL20TU_DELUXEMAP);
3847 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation , GL20TU_ATTENUATION);
3848 if (p->loc_Texture_Cube >= 0) qglUniform1iARB(p->loc_Texture_Cube , GL20TU_CUBE);
3849 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction , GL20TU_REFRACTION);
3850 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection , GL20TU_REFLECTION);
3851 if (p->loc_Texture_ShadowMapRect >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3852 if (p->loc_Texture_ShadowMapCube >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube , GL20TU_SHADOWMAPCUBE);
3853 if (p->loc_Texture_ShadowMap2D >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3854 if (p->loc_Texture_CubeProjection >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3855 if (p->loc_Texture_ScreenDepth >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth , GL20TU_SCREENDEPTH);
3856 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3857 if (p->loc_Texture_ScreenDiffuse >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse , GL20TU_SCREENDIFFUSE);
3858 if (p->loc_Texture_ScreenSpecular >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3859 if (p->loc_Texture_ReflectMask >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask , GL20TU_REFLECTMASK);
3860 if (p->loc_Texture_ReflectCube >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube , GL20TU_REFLECTCUBE);
3862 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3865 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
3869 Mem_Free(vertexstring);
3871 Mem_Free(geometrystring);
3873 Mem_Free(fragmentstring);
3876 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3878 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3879 if (r_glsl_permutation != perm)
3881 r_glsl_permutation = perm;
3882 if (!r_glsl_permutation->program)
3884 if (!r_glsl_permutation->compiled)
3885 R_GLSL_CompilePermutation(perm, mode, permutation);
3886 if (!r_glsl_permutation->program)
3888 // remove features until we find a valid permutation
3890 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3892 // reduce i more quickly whenever it would not remove any bits
3893 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3894 if (!(permutation & j))
3897 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3898 if (!r_glsl_permutation->compiled)
3899 R_GLSL_CompilePermutation(perm, mode, permutation);
3900 if (r_glsl_permutation->program)
3903 if (i >= SHADERPERMUTATION_COUNT)
3905 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3906 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3907 qglUseProgramObjectARB(0);CHECKGLERROR
3908 return; // no bit left to clear, entire mode is broken
3913 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3915 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3916 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3917 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3921 #include <Cg/cgGL.h>
3922 struct r_cg_permutation_s;
3923 typedef struct r_cg_permutation_s
3925 /// hash lookup data
3926 struct r_cg_permutation_s *hashnext;
3928 unsigned int permutation;
3930 /// indicates if we have tried compiling this permutation already
3932 /// 0 if compilation failed
3935 /// locations of detected parameters in programs, or NULL if not found
3936 CGparameter vp_EyePosition;
3937 CGparameter vp_FogPlane;
3938 CGparameter vp_LightDir;
3939 CGparameter vp_LightPosition;
3940 CGparameter vp_ModelToLight;
3941 CGparameter vp_TexMatrix;
3942 CGparameter vp_BackgroundTexMatrix;
3943 CGparameter vp_ModelViewProjectionMatrix;
3944 CGparameter vp_ModelViewMatrix;
3945 CGparameter vp_ShadowMapMatrix;
3947 CGparameter fp_Texture_First;
3948 CGparameter fp_Texture_Second;
3949 CGparameter fp_Texture_GammaRamps;
3950 CGparameter fp_Texture_Normal;
3951 CGparameter fp_Texture_Color;
3952 CGparameter fp_Texture_Gloss;
3953 CGparameter fp_Texture_Glow;
3954 CGparameter fp_Texture_SecondaryNormal;
3955 CGparameter fp_Texture_SecondaryColor;
3956 CGparameter fp_Texture_SecondaryGloss;
3957 CGparameter fp_Texture_SecondaryGlow;
3958 CGparameter fp_Texture_Pants;
3959 CGparameter fp_Texture_Shirt;
3960 CGparameter fp_Texture_FogHeightTexture;
3961 CGparameter fp_Texture_FogMask;
3962 CGparameter fp_Texture_Lightmap;
3963 CGparameter fp_Texture_Deluxemap;
3964 CGparameter fp_Texture_Attenuation;
3965 CGparameter fp_Texture_Cube;
3966 CGparameter fp_Texture_Refraction;
3967 CGparameter fp_Texture_Reflection;
3968 CGparameter fp_Texture_ShadowMapRect;
3969 CGparameter fp_Texture_ShadowMapCube;
3970 CGparameter fp_Texture_ShadowMap2D;
3971 CGparameter fp_Texture_CubeProjection;
3972 CGparameter fp_Texture_ScreenDepth;
3973 CGparameter fp_Texture_ScreenNormalMap;
3974 CGparameter fp_Texture_ScreenDiffuse;
3975 CGparameter fp_Texture_ScreenSpecular;
3976 CGparameter fp_Texture_ReflectMask;
3977 CGparameter fp_Texture_ReflectCube;
3978 CGparameter fp_Alpha;
3979 CGparameter fp_BloomBlur_Parameters;
3980 CGparameter fp_ClientTime;
3981 CGparameter fp_Color_Ambient;
3982 CGparameter fp_Color_Diffuse;
3983 CGparameter fp_Color_Specular;
3984 CGparameter fp_Color_Glow;
3985 CGparameter fp_Color_Pants;
3986 CGparameter fp_Color_Shirt;
3987 CGparameter fp_DeferredColor_Ambient;
3988 CGparameter fp_DeferredColor_Diffuse;
3989 CGparameter fp_DeferredColor_Specular;
3990 CGparameter fp_DeferredMod_Diffuse;
3991 CGparameter fp_DeferredMod_Specular;
3992 CGparameter fp_DistortScaleRefractReflect;
3993 CGparameter fp_EyePosition;
3994 CGparameter fp_FogColor;
3995 CGparameter fp_FogHeightFade;
3996 CGparameter fp_FogPlane;
3997 CGparameter fp_FogPlaneViewDist;
3998 CGparameter fp_FogRangeRecip;
3999 CGparameter fp_LightColor;
4000 CGparameter fp_LightDir;
4001 CGparameter fp_LightPosition;
4002 CGparameter fp_OffsetMapping_Scale;
4003 CGparameter fp_PixelSize;
4004 CGparameter fp_ReflectColor;
4005 CGparameter fp_ReflectFactor;
4006 CGparameter fp_ReflectOffset;
4007 CGparameter fp_RefractColor;
4008 CGparameter fp_Saturation;
4009 CGparameter fp_ScreenCenterRefractReflect;
4010 CGparameter fp_ScreenScaleRefractReflect;
4011 CGparameter fp_ScreenToDepth;
4012 CGparameter fp_ShadowMap_Parameters;
4013 CGparameter fp_ShadowMap_TextureScale;
4014 CGparameter fp_SpecularPower;
4015 CGparameter fp_UserVec1;
4016 CGparameter fp_UserVec2;
4017 CGparameter fp_UserVec3;
4018 CGparameter fp_UserVec4;
4019 CGparameter fp_ViewTintColor;
4020 CGparameter fp_ViewToLight;
4021 CGparameter fp_PixelToScreenTexCoord;
4022 CGparameter fp_ModelToReflectCube;
4023 CGparameter fp_BloomColorSubtract;
4027 /// information about each possible shader permutation
4028 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4029 /// currently selected permutation
4030 r_cg_permutation_t *r_cg_permutation;
4031 /// storage for permutations linked in the hash table
4032 memexpandablearray_t r_cg_permutationarray;
4034 #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));}}
4036 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
4038 //unsigned int hashdepth = 0;
4039 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4040 r_cg_permutation_t *p;
4041 for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4043 if (p->mode == mode && p->permutation == permutation)
4045 //if (hashdepth > 10)
4046 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4051 p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4053 p->permutation = permutation;
4054 p->hashnext = r_cg_permutationhash[mode][hashindex];
4055 r_cg_permutationhash[mode][hashindex] = p;
4056 //if (hashdepth > 10)
4057 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4061 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4064 if (!filename || !filename[0])
4066 if (!strcmp(filename, "cg/default.cg"))
4068 if (!cgshaderstring)
4070 cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4072 Con_DPrintf("Loading shaders from file %s...\n", filename);
4074 cgshaderstring = (char *)builtincgshaderstring;
4076 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4077 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4078 return shaderstring;
4080 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4083 if (printfromdisknotice)
4084 Con_DPrintf("from disk %s... ", filename);
4085 return shaderstring;
4087 return shaderstring;
4090 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4092 // TODO: load or create .fp and .vp shader files
4095 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4098 shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4099 int vertstrings_count = 0, vertstring_length = 0;
4100 int geomstrings_count = 0, geomstring_length = 0;
4101 int fragstrings_count = 0, fragstring_length = 0;
4103 char *vertexstring, *geometrystring, *fragmentstring;
4104 char *vertstring, *geomstring, *fragstring;
4105 const char *vertstrings_list[32+3];
4106 const char *geomstrings_list[32+3];
4107 const char *fragstrings_list[32+3];
4108 char permutationname[256];
4109 char cachename[256];
4110 CGprofile vertexProfile;
4111 CGprofile fragmentProfile;
4119 permutationname[0] = 0;
4121 vertexstring = R_CG_GetText(modeinfo->vertexfilename, true);
4122 geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4123 fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4125 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4126 strlcat(cachename, "cg/", sizeof(cachename));
4128 // the first pretext is which type of shader to compile as
4129 // (later these will all be bound together as a program object)
4130 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4131 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4132 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4134 // the second pretext is the mode (for example a light source)
4135 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4136 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4137 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4138 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4139 strlcat(cachename, modeinfo->name, sizeof(cachename));
4141 // now add all the permutation pretexts
4142 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4144 if (permutation & (1<<i))
4146 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4147 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4148 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4149 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4150 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4154 // keep line numbers correct
4155 vertstrings_list[vertstrings_count++] = "\n";
4156 geomstrings_list[geomstrings_count++] = "\n";
4157 fragstrings_list[fragstrings_count++] = "\n";
4161 // replace spaces in the cachename with _ characters
4162 for (i = 0;cachename[i];i++)
4163 if (cachename[i] == ' ')
4166 // now append the shader text itself
4167 vertstrings_list[vertstrings_count++] = vertexstring;
4168 geomstrings_list[geomstrings_count++] = geometrystring;
4169 fragstrings_list[fragstrings_count++] = fragmentstring;
4171 // if any sources were NULL, clear the respective list
4173 vertstrings_count = 0;
4174 if (!geometrystring)
4175 geomstrings_count = 0;
4176 if (!fragmentstring)
4177 fragstrings_count = 0;
4179 vertstring_length = 0;
4180 for (i = 0;i < vertstrings_count;i++)
4181 vertstring_length += strlen(vertstrings_list[i]);
4182 vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4183 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4184 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4186 geomstring_length = 0;
4187 for (i = 0;i < geomstrings_count;i++)
4188 geomstring_length += strlen(geomstrings_list[i]);
4189 geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4190 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4191 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4193 fragstring_length = 0;
4194 for (i = 0;i < fragstrings_count;i++)
4195 fragstring_length += strlen(fragstrings_list[i]);
4196 fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4197 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4198 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4202 //vertexProfile = CG_PROFILE_ARBVP1;
4203 //fragmentProfile = CG_PROFILE_ARBFP1;
4204 vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4205 fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4206 //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4207 //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4208 //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4211 // try to load the cached shader, or generate one
4212 R_CG_CacheShader(p, cachename, vertstring, fragstring);
4214 // if caching failed, do a dynamic compile for now
4216 if (vertstring[0] && !p->vprogram)
4217 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4219 if (fragstring[0] && !p->fprogram)
4220 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4223 // look up all the uniform variable names we care about, so we don't
4224 // have to look them up every time we set them
4228 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4229 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4230 p->vp_EyePosition = cgGetNamedParameter(p->vprogram, "EyePosition");
4231 p->vp_FogPlane = cgGetNamedParameter(p->vprogram, "FogPlane");
4232 p->vp_LightDir = cgGetNamedParameter(p->vprogram, "LightDir");
4233 p->vp_LightPosition = cgGetNamedParameter(p->vprogram, "LightPosition");
4234 p->vp_ModelToLight = cgGetNamedParameter(p->vprogram, "ModelToLight");
4235 p->vp_TexMatrix = cgGetNamedParameter(p->vprogram, "TexMatrix");
4236 p->vp_BackgroundTexMatrix = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4237 p->vp_ModelViewProjectionMatrix = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4238 p->vp_ModelViewMatrix = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4239 p->vp_ShadowMapMatrix = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4245 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4246 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4247 p->fp_Texture_First = cgGetNamedParameter(p->fprogram, "Texture_First");
4248 p->fp_Texture_Second = cgGetNamedParameter(p->fprogram, "Texture_Second");
4249 p->fp_Texture_GammaRamps = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4250 p->fp_Texture_Normal = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4251 p->fp_Texture_Color = cgGetNamedParameter(p->fprogram, "Texture_Color");
4252 p->fp_Texture_Gloss = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4253 p->fp_Texture_Glow = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4254 p->fp_Texture_SecondaryNormal = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4255 p->fp_Texture_SecondaryColor = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4256 p->fp_Texture_SecondaryGloss = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4257 p->fp_Texture_SecondaryGlow = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4258 p->fp_Texture_Pants = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4259 p->fp_Texture_Shirt = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4260 p->fp_Texture_FogHeightTexture = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4261 p->fp_Texture_FogMask = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4262 p->fp_Texture_Lightmap = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4263 p->fp_Texture_Deluxemap = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4264 p->fp_Texture_Attenuation = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4265 p->fp_Texture_Cube = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4266 p->fp_Texture_Refraction = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4267 p->fp_Texture_Reflection = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4268 p->fp_Texture_ShadowMapRect = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4269 p->fp_Texture_ShadowMapCube = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4270 p->fp_Texture_ShadowMap2D = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4271 p->fp_Texture_CubeProjection = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4272 p->fp_Texture_ScreenDepth = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4273 p->fp_Texture_ScreenNormalMap = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4274 p->fp_Texture_ScreenDiffuse = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4275 p->fp_Texture_ScreenSpecular = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4276 p->fp_Texture_ReflectMask = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4277 p->fp_Texture_ReflectCube = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4278 p->fp_Alpha = cgGetNamedParameter(p->fprogram, "Alpha");
4279 p->fp_BloomBlur_Parameters = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4280 p->fp_ClientTime = cgGetNamedParameter(p->fprogram, "ClientTime");
4281 p->fp_Color_Ambient = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4282 p->fp_Color_Diffuse = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4283 p->fp_Color_Specular = cgGetNamedParameter(p->fprogram, "Color_Specular");
4284 p->fp_Color_Glow = cgGetNamedParameter(p->fprogram, "Color_Glow");
4285 p->fp_Color_Pants = cgGetNamedParameter(p->fprogram, "Color_Pants");
4286 p->fp_Color_Shirt = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4287 p->fp_DeferredColor_Ambient = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4288 p->fp_DeferredColor_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4289 p->fp_DeferredColor_Specular = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4290 p->fp_DeferredMod_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4291 p->fp_DeferredMod_Specular = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4292 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4293 p->fp_EyePosition = cgGetNamedParameter(p->fprogram, "EyePosition");
4294 p->fp_FogColor = cgGetNamedParameter(p->fprogram, "FogColor");
4295 p->fp_FogHeightFade = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4296 p->fp_FogPlane = cgGetNamedParameter(p->fprogram, "FogPlane");
4297 p->fp_FogPlaneViewDist = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4298 p->fp_FogRangeRecip = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4299 p->fp_LightColor = cgGetNamedParameter(p->fprogram, "LightColor");
4300 p->fp_LightDir = cgGetNamedParameter(p->fprogram, "LightDir");
4301 p->fp_LightPosition = cgGetNamedParameter(p->fprogram, "LightPosition");
4302 p->fp_OffsetMapping_Scale = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4303 p->fp_PixelSize = cgGetNamedParameter(p->fprogram, "PixelSize");
4304 p->fp_ReflectColor = cgGetNamedParameter(p->fprogram, "ReflectColor");
4305 p->fp_ReflectFactor = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4306 p->fp_ReflectOffset = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4307 p->fp_RefractColor = cgGetNamedParameter(p->fprogram, "RefractColor");
4308 p->fp_Saturation = cgGetNamedParameter(p->fprogram, "Saturation");
4309 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4310 p->fp_ScreenScaleRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4311 p->fp_ScreenToDepth = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4312 p->fp_ShadowMap_Parameters = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4313 p->fp_ShadowMap_TextureScale = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4314 p->fp_SpecularPower = cgGetNamedParameter(p->fprogram, "SpecularPower");
4315 p->fp_UserVec1 = cgGetNamedParameter(p->fprogram, "UserVec1");
4316 p->fp_UserVec2 = cgGetNamedParameter(p->fprogram, "UserVec2");
4317 p->fp_UserVec3 = cgGetNamedParameter(p->fprogram, "UserVec3");
4318 p->fp_UserVec4 = cgGetNamedParameter(p->fprogram, "UserVec4");
4319 p->fp_ViewTintColor = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4320 p->fp_ViewToLight = cgGetNamedParameter(p->fprogram, "ViewToLight");
4321 p->fp_PixelToScreenTexCoord = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4322 p->fp_ModelToReflectCube = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4323 p->fp_BloomColorSubtract = cgGetNamedParameter(p->fprogram, "BloomColorSubtract");
4327 if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4328 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4330 Con_Printf("^1CG shader %s failed! some features may not work properly.\n", permutationname);
4334 Mem_Free(vertstring);
4336 Mem_Free(geomstring);
4338 Mem_Free(fragstring);
4340 Mem_Free(vertexstring);
4342 Mem_Free(geometrystring);
4344 Mem_Free(fragmentstring);
4347 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4349 r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4352 if (r_cg_permutation != perm)
4354 r_cg_permutation = perm;
4355 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4357 if (!r_cg_permutation->compiled)
4358 R_CG_CompilePermutation(perm, mode, permutation);
4359 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4361 // remove features until we find a valid permutation
4363 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4365 // reduce i more quickly whenever it would not remove any bits
4366 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4367 if (!(permutation & j))
4370 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4371 if (!r_cg_permutation->compiled)
4372 R_CG_CompilePermutation(perm, mode, permutation);
4373 if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4376 if (i >= SHADERPERMUTATION_COUNT)
4378 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4379 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4380 return; // no bit left to clear, entire mode is broken
4386 if (r_cg_permutation->vprogram)
4388 cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4389 cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4390 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4394 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4395 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4397 if (r_cg_permutation->fprogram)
4399 cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4400 cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4401 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4405 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4406 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4410 if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4411 if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4412 if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4415 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4417 cgGLSetTextureParameter(param, R_GetTexture(tex));
4418 cgGLEnableTextureParameter(param);
4426 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
4427 extern D3DCAPS9 vid_d3d9caps;
4430 struct r_hlsl_permutation_s;
4431 typedef struct r_hlsl_permutation_s
4433 /// hash lookup data
4434 struct r_hlsl_permutation_s *hashnext;
4436 unsigned int permutation;
4438 /// indicates if we have tried compiling this permutation already
4440 /// NULL if compilation failed
4441 IDirect3DVertexShader9 *vertexshader;
4442 IDirect3DPixelShader9 *pixelshader;
4444 r_hlsl_permutation_t;
4446 typedef enum D3DVSREGISTER_e
4448 D3DVSREGISTER_TexMatrix = 0, // float4x4
4449 D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
4450 D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
4451 D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
4452 D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
4453 D3DVSREGISTER_ModelToLight = 20, // float4x4
4454 D3DVSREGISTER_EyePosition = 24,
4455 D3DVSREGISTER_FogPlane = 25,
4456 D3DVSREGISTER_LightDir = 26,
4457 D3DVSREGISTER_LightPosition = 27,
4461 typedef enum D3DPSREGISTER_e
4463 D3DPSREGISTER_Alpha = 0,
4464 D3DPSREGISTER_BloomBlur_Parameters = 1,
4465 D3DPSREGISTER_ClientTime = 2,
4466 D3DPSREGISTER_Color_Ambient = 3,
4467 D3DPSREGISTER_Color_Diffuse = 4,
4468 D3DPSREGISTER_Color_Specular = 5,
4469 D3DPSREGISTER_Color_Glow = 6,
4470 D3DPSREGISTER_Color_Pants = 7,
4471 D3DPSREGISTER_Color_Shirt = 8,
4472 D3DPSREGISTER_DeferredColor_Ambient = 9,
4473 D3DPSREGISTER_DeferredColor_Diffuse = 10,
4474 D3DPSREGISTER_DeferredColor_Specular = 11,
4475 D3DPSREGISTER_DeferredMod_Diffuse = 12,
4476 D3DPSREGISTER_DeferredMod_Specular = 13,
4477 D3DPSREGISTER_DistortScaleRefractReflect = 14,
4478 D3DPSREGISTER_EyePosition = 15, // unused
4479 D3DPSREGISTER_FogColor = 16,
4480 D3DPSREGISTER_FogHeightFade = 17,
4481 D3DPSREGISTER_FogPlane = 18,
4482 D3DPSREGISTER_FogPlaneViewDist = 19,
4483 D3DPSREGISTER_FogRangeRecip = 20,
4484 D3DPSREGISTER_LightColor = 21,
4485 D3DPSREGISTER_LightDir = 22, // unused
4486 D3DPSREGISTER_LightPosition = 23,
4487 D3DPSREGISTER_OffsetMapping_Scale = 24,
4488 D3DPSREGISTER_PixelSize = 25,
4489 D3DPSREGISTER_ReflectColor = 26,
4490 D3DPSREGISTER_ReflectFactor = 27,
4491 D3DPSREGISTER_ReflectOffset = 28,
4492 D3DPSREGISTER_RefractColor = 29,
4493 D3DPSREGISTER_Saturation = 30,
4494 D3DPSREGISTER_ScreenCenterRefractReflect = 31,
4495 D3DPSREGISTER_ScreenScaleRefractReflect = 32,
4496 D3DPSREGISTER_ScreenToDepth = 33,
4497 D3DPSREGISTER_ShadowMap_Parameters = 34,
4498 D3DPSREGISTER_ShadowMap_TextureScale = 35,
4499 D3DPSREGISTER_SpecularPower = 36,
4500 D3DPSREGISTER_UserVec1 = 37,
4501 D3DPSREGISTER_UserVec2 = 38,
4502 D3DPSREGISTER_UserVec3 = 39,
4503 D3DPSREGISTER_UserVec4 = 40,
4504 D3DPSREGISTER_ViewTintColor = 41,
4505 D3DPSREGISTER_PixelToScreenTexCoord = 42,
4506 D3DPSREGISTER_BloomColorSubtract = 43,
4507 D3DPSREGISTER_ViewToLight = 44, // float4x4
4508 D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
4513 /// information about each possible shader permutation
4514 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4515 /// currently selected permutation
4516 r_hlsl_permutation_t *r_hlsl_permutation;
4517 /// storage for permutations linked in the hash table
4518 memexpandablearray_t r_hlsl_permutationarray;
4520 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
4522 //unsigned int hashdepth = 0;
4523 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4524 r_hlsl_permutation_t *p;
4525 for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
4527 if (p->mode == mode && p->permutation == permutation)
4529 //if (hashdepth > 10)
4530 // Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4535 p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
4537 p->permutation = permutation;
4538 p->hashnext = r_hlsl_permutationhash[mode][hashindex];
4539 r_hlsl_permutationhash[mode][hashindex] = p;
4540 //if (hashdepth > 10)
4541 // Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4545 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
4548 if (!filename || !filename[0])
4550 if (!strcmp(filename, "hlsl/default.hlsl"))
4552 if (!hlslshaderstring)
4554 hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4555 if (hlslshaderstring)
4556 Con_DPrintf("Loading shaders from file %s...\n", filename);
4558 hlslshaderstring = (char *)builtincgshaderstring;
4560 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
4561 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
4562 return shaderstring;
4564 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4567 if (printfromdisknotice)
4568 Con_DPrintf("from disk %s... ", filename);
4569 return shaderstring;
4571 return shaderstring;
4575 #include <d3dx9mesh.h>
4576 #pragma comment(lib, "d3dx9.lib")
4578 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4580 DWORD *vsbin = NULL;
4581 DWORD *psbin = NULL;
4582 fs_offset_t vsbinsize;
4583 fs_offset_t psbinsize;
4584 // IDirect3DVertexShader9 *vs = NULL;
4585 // IDirect3DPixelShader9 *ps = NULL;
4586 ID3DXBuffer *vslog = NULL;
4587 ID3DXBuffer *vsbuffer = NULL;
4588 ID3DXConstantTable *vsconstanttable = NULL;
4589 ID3DXBuffer *pslog = NULL;
4590 ID3DXBuffer *psbuffer = NULL;
4591 ID3DXConstantTable *psconstanttable = NULL;
4594 char temp[MAX_INPUTLINE];
4595 const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
4596 if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4597 if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4598 vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
4599 psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
4600 if ((!vsbin && vertstring) || (!psbin && fragstring))
4602 vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4603 psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4604 if (vertstring && vertstring[0])
4606 vsresult = D3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, 0, &vsbuffer, &vslog, &vsconstanttable);
4609 vsbinsize = vsbuffer->GetBufferSize();
4610 vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
4611 memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
4612 vsbuffer->Release();
4616 strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
4617 Con_Printf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
4621 if (fragstring && fragstring[0])
4623 psresult = D3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, 0, &psbuffer, &pslog, &psconstanttable);
4626 psbinsize = psbuffer->GetBufferSize();
4627 psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
4628 memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
4629 psbuffer->Release();
4633 strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
4634 Con_Printf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
4641 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
4642 if (FAILED(vsresult))
4643 Con_Printf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
4647 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
4648 if (FAILED(psresult))
4649 Con_Printf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
4651 // free the shader data
4652 vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4653 psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4656 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
4659 shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
4660 int vertstrings_count = 0, vertstring_length = 0;
4661 int geomstrings_count = 0, geomstring_length = 0;
4662 int fragstrings_count = 0, fragstring_length = 0;
4664 char *vertexstring, *geometrystring, *fragmentstring;
4665 char *vertstring, *geomstring, *fragstring;
4666 const char *vertstrings_list[32+3];
4667 const char *geomstrings_list[32+3];
4668 const char *fragstrings_list[32+3];
4669 char permutationname[256];
4670 char cachename[256];
4675 p->vertexshader = NULL;
4676 p->pixelshader = NULL;
4678 permutationname[0] = 0;
4680 vertexstring = R_HLSL_GetText(modeinfo->vertexfilename, true);
4681 geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
4682 fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
4684 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4685 strlcat(cachename, "hlsl/", sizeof(cachename));
4687 // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
4688 vertstrings_list[vertstrings_count++] = "#define HLSL\n";
4689 geomstrings_list[geomstrings_count++] = "#define HLSL\n";
4690 fragstrings_list[fragstrings_count++] = "#define HLSL\n";
4692 // the first pretext is which type of shader to compile as
4693 // (later these will all be bound together as a program object)
4694 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4695 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4696 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4698 // the second pretext is the mode (for example a light source)
4699 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4700 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4701 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4702 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4703 strlcat(cachename, modeinfo->name, sizeof(cachename));
4705 // now add all the permutation pretexts
4706 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4708 if (permutation & (1<<i))
4710 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4711 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4712 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4713 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4714 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4718 // keep line numbers correct
4719 vertstrings_list[vertstrings_count++] = "\n";
4720 geomstrings_list[geomstrings_count++] = "\n";
4721 fragstrings_list[fragstrings_count++] = "\n";
4725 // replace spaces in the cachename with _ characters
4726 for (i = 0;cachename[i];i++)
4727 if (cachename[i] == ' ')
4730 // now append the shader text itself
4731 vertstrings_list[vertstrings_count++] = vertexstring;
4732 geomstrings_list[geomstrings_count++] = geometrystring;
4733 fragstrings_list[fragstrings_count++] = fragmentstring;
4735 // if any sources were NULL, clear the respective list
4737 vertstrings_count = 0;
4738 if (!geometrystring)
4739 geomstrings_count = 0;
4740 if (!fragmentstring)
4741 fragstrings_count = 0;
4743 vertstring_length = 0;
4744 for (i = 0;i < vertstrings_count;i++)
4745 vertstring_length += strlen(vertstrings_list[i]);
4746 vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
4747 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4748 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4750 geomstring_length = 0;
4751 for (i = 0;i < geomstrings_count;i++)
4752 geomstring_length += strlen(geomstrings_list[i]);
4753 geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
4754 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4755 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4757 fragstring_length = 0;
4758 for (i = 0;i < fragstrings_count;i++)
4759 fragstring_length += strlen(fragstrings_list[i]);
4760 fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
4761 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4762 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4764 // try to load the cached shader, or generate one
4765 R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
4767 if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
4768 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
4770 Con_Printf("^1HLSL shader %s failed! some features may not work properly.\n", permutationname);
4774 Mem_Free(vertstring);
4776 Mem_Free(geomstring);
4778 Mem_Free(fragstring);
4780 Mem_Free(vertexstring);
4782 Mem_Free(geometrystring);
4784 Mem_Free(fragmentstring);
4787 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
4788 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
4789 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4790 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4791 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4792 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4794 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
4795 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
4796 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4797 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4798 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4799 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4801 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
4803 r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
4804 if (r_hlsl_permutation != perm)
4806 r_hlsl_permutation = perm;
4807 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4809 if (!r_hlsl_permutation->compiled)
4810 R_HLSL_CompilePermutation(perm, mode, permutation);
4811 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4813 // remove features until we find a valid permutation
4815 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4817 // reduce i more quickly whenever it would not remove any bits
4818 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4819 if (!(permutation & j))
4822 r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4823 if (!r_hlsl_permutation->compiled)
4824 R_HLSL_CompilePermutation(perm, mode, permutation);
4825 if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
4828 if (i >= SHADERPERMUTATION_COUNT)
4830 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4831 r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4832 return; // no bit left to clear, entire mode is broken
4836 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
4837 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
4839 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
4840 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
4841 hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
4845 void R_GLSL_Restart_f(void)
4847 unsigned int i, limit;
4848 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4849 Mem_Free(glslshaderstring);
4850 glslshaderstring = NULL;
4851 if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4852 Mem_Free(cgshaderstring);
4853 cgshaderstring = NULL;
4854 if (hlslshaderstring && hlslshaderstring != builtincgshaderstring)
4855 Mem_Free(hlslshaderstring);
4856 hlslshaderstring = NULL;
4857 switch(vid.renderpath)
4859 case RENDERPATH_D3D9:
4862 r_hlsl_permutation_t *p;
4863 r_hlsl_permutation = NULL;
4864 // cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4865 // cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4866 // cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4867 // cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4868 limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
4869 for (i = 0;i < limit;i++)
4871 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
4873 if (p->vertexshader)
4874 IDirect3DVertexShader9_Release(p->vertexshader);
4876 IDirect3DPixelShader9_Release(p->pixelshader);
4877 Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
4880 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
4884 case RENDERPATH_D3D10:
4885 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4887 case RENDERPATH_D3D11:
4888 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4890 case RENDERPATH_GL20:
4892 r_glsl_permutation_t *p;
4893 r_glsl_permutation = NULL;
4894 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4895 for (i = 0;i < limit;i++)
4897 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4899 GL_Backend_FreeProgram(p->program);
4900 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4903 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4906 case RENDERPATH_CGGL:
4909 r_cg_permutation_t *p;
4910 r_cg_permutation = NULL;
4911 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4912 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4913 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4914 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4915 limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4916 for (i = 0;i < limit;i++)
4918 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4921 cgDestroyProgram(p->vprogram);
4923 cgDestroyProgram(p->fprogram);
4924 Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4927 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4931 case RENDERPATH_GL13:
4932 case RENDERPATH_GL11:
4937 void R_GLSL_DumpShader_f(void)
4942 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4945 FS_Print(file, "/* The engine may define the following macros:\n");
4946 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4947 for (i = 0;i < SHADERMODE_COUNT;i++)
4948 FS_Print(file, glslshadermodeinfo[i].pretext);
4949 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4950 FS_Print(file, shaderpermutationinfo[i].pretext);
4951 FS_Print(file, "*/\n");
4952 FS_Print(file, builtinshaderstring);
4954 Con_Printf("glsl/default.glsl written\n");
4957 Con_Printf("failed to write to glsl/default.glsl\n");
4960 file = FS_OpenRealFile("cg/default.cg", "w", false);
4963 FS_Print(file, "/* The engine may define the following macros:\n");
4964 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4965 for (i = 0;i < SHADERMODE_COUNT;i++)
4966 FS_Print(file, cgshadermodeinfo[i].pretext);
4967 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4968 FS_Print(file, shaderpermutationinfo[i].pretext);
4969 FS_Print(file, "*/\n");
4970 FS_Print(file, builtincgshaderstring);
4972 Con_Printf("cg/default.cg written\n");
4975 Con_Printf("failed to write to cg/default.cg\n");
4979 file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
4982 FS_Print(file, "/* The engine may define the following macros:\n");
4983 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4984 for (i = 0;i < SHADERMODE_COUNT;i++)
4985 FS_Print(file, hlslshadermodeinfo[i].pretext);
4986 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4987 FS_Print(file, shaderpermutationinfo[i].pretext);
4988 FS_Print(file, "*/\n");
4989 FS_Print(file, builtincgshaderstring);
4991 Con_Printf("hlsl/default.hlsl written\n");
4994 Con_Printf("failed to write to hlsl/default.hlsl\n");
4998 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
5001 texturemode = GL_MODULATE;
5002 switch (vid.renderpath)
5004 case RENDERPATH_D3D9:
5006 R_SetupShader_SetPermutationHLSL(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))));
5007 R_Mesh_TexBind(GL20TU_FIRST , first );
5008 R_Mesh_TexBind(GL20TU_SECOND, second);
5011 case RENDERPATH_D3D10:
5012 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5014 case RENDERPATH_D3D11:
5015 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5017 case RENDERPATH_GL20:
5018 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))));
5019 R_Mesh_TexBind(GL20TU_FIRST , first );
5020 R_Mesh_TexBind(GL20TU_SECOND, second);
5022 case RENDERPATH_CGGL:
5025 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))));
5026 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
5027 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
5030 case RENDERPATH_GL13:
5031 R_Mesh_TexBind(0, first );
5032 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
5033 R_Mesh_TexBind(1, second);
5035 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
5037 case RENDERPATH_GL11:
5038 R_Mesh_TexBind(0, first );
5043 void R_SetupShader_DepthOrShadow(void)
5045 switch (vid.renderpath)
5047 case RENDERPATH_D3D9:
5049 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
5052 case RENDERPATH_D3D10:
5053 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5055 case RENDERPATH_D3D11:
5056 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5058 case RENDERPATH_GL20:
5059 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
5061 case RENDERPATH_CGGL:
5063 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
5066 case RENDERPATH_GL13:
5067 R_Mesh_TexBind(0, 0);
5068 R_Mesh_TexBind(1, 0);
5070 case RENDERPATH_GL11:
5071 R_Mesh_TexBind(0, 0);
5076 void R_SetupShader_ShowDepth(void)
5078 switch (vid.renderpath)
5080 case RENDERPATH_D3D9:
5082 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, 0);
5085 case RENDERPATH_D3D10:
5086 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5088 case RENDERPATH_D3D11:
5089 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5091 case RENDERPATH_GL20:
5092 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
5094 case RENDERPATH_CGGL:
5096 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
5099 case RENDERPATH_GL13:
5101 case RENDERPATH_GL11:
5106 extern qboolean r_shadow_usingdeferredprepass;
5107 extern cvar_t r_shadow_deferred_8bitrange;
5108 extern rtexture_t *r_shadow_attenuationgradienttexture;
5109 extern rtexture_t *r_shadow_attenuation2dtexture;
5110 extern rtexture_t *r_shadow_attenuation3dtexture;
5111 extern qboolean r_shadow_usingshadowmaprect;
5112 extern qboolean r_shadow_usingshadowmapcube;
5113 extern qboolean r_shadow_usingshadowmap2d;
5114 extern qboolean r_shadow_usingshadowmaportho;
5115 extern float r_shadow_shadowmap_texturescale[2];
5116 extern float r_shadow_shadowmap_parameters[4];
5117 extern qboolean r_shadow_shadowmapvsdct;
5118 extern qboolean r_shadow_shadowmapsampler;
5119 extern int r_shadow_shadowmappcf;
5120 extern rtexture_t *r_shadow_shadowmaprectangletexture;
5121 extern rtexture_t *r_shadow_shadowmap2dtexture;
5122 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
5123 extern rtexture_t *r_shadow_shadowmap2dcolortexture;
5124 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
5125 extern matrix4x4_t r_shadow_shadowmapmatrix;
5126 extern int r_shadow_shadowmaplod; // changes for each light based on distance
5127 extern int r_shadow_prepass_width;
5128 extern int r_shadow_prepass_height;
5129 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
5130 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
5131 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
5132 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
5133 extern cvar_t gl_mesh_separatearrays;
5134 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane)
5136 // select a permutation of the lighting shader appropriate to this
5137 // combination of texture, entity, light source, and fogging, only use the
5138 // minimum features necessary to avoid wasting rendering time in the
5139 // fragment shader on features that are not being used
5140 unsigned int permutation = 0;
5141 unsigned int mode = 0;
5143 r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
5144 if (rsurfacepass == RSURFPASS_BACKGROUND)
5146 // distorted background
5147 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
5148 mode = SHADERMODE_WATER;
5149 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
5150 mode = SHADERMODE_REFRACTION;
5153 mode = SHADERMODE_GENERIC;
5154 permutation |= SHADERPERMUTATION_DIFFUSE;
5156 GL_AlphaTest(false);
5157 GL_BlendFunc(GL_ONE, GL_ZERO);
5159 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
5161 if (r_glsl_offsetmapping.integer)
5163 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5164 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5165 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5166 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5167 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5169 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5170 if (r_glsl_offsetmapping_reliefmapping.integer)
5171 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5174 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5175 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5176 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5177 permutation |= SHADERPERMUTATION_ALPHAKILL;
5178 // normalmap (deferred prepass), may use alpha test on diffuse
5179 mode = SHADERMODE_DEFERREDGEOMETRY;
5180 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5181 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5182 GL_AlphaTest(false);
5183 GL_BlendFunc(GL_ONE, GL_ZERO);
5185 else if (rsurfacepass == RSURFPASS_RTLIGHT)
5187 if (r_glsl_offsetmapping.integer)
5189 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5190 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5191 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5192 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5193 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5195 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5196 if (r_glsl_offsetmapping_reliefmapping.integer)
5197 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5200 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5201 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5203 mode = SHADERMODE_LIGHTSOURCE;
5204 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5205 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5206 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
5207 permutation |= SHADERPERMUTATION_CUBEFILTER;
5208 if (diffusescale > 0)
5209 permutation |= SHADERPERMUTATION_DIFFUSE;
5210 if (specularscale > 0)
5212 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5213 if (r_shadow_glossexact.integer)
5214 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5216 if (r_refdef.fogenabled)
5217 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5218 if (rsurface.texture->colormapping)
5219 permutation |= SHADERPERMUTATION_COLORMAPPING;
5220 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5222 if (r_shadow_usingshadowmaprect)
5223 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5224 if (r_shadow_usingshadowmap2d)
5225 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5226 if (r_shadow_usingshadowmapcube)
5227 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5228 else if(r_shadow_shadowmapvsdct)
5229 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5231 if (r_shadow_shadowmapsampler)
5232 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5233 if (r_shadow_shadowmappcf > 1)
5234 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5235 else if (r_shadow_shadowmappcf)
5236 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5238 if (rsurface.texture->reflectmasktexture)
5239 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5240 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5241 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
5243 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5245 if (r_glsl_offsetmapping.integer)
5247 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5248 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5249 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5250 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5251 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5253 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5254 if (r_glsl_offsetmapping_reliefmapping.integer)
5255 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5258 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5259 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5260 // unshaded geometry (fullbright or ambient model lighting)
5261 mode = SHADERMODE_FLATCOLOR;
5262 ambientscale = diffusescale = specularscale = 0;
5263 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5264 permutation |= SHADERPERMUTATION_GLOW;
5265 if (r_refdef.fogenabled)
5266 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5267 if (rsurface.texture->colormapping)
5268 permutation |= SHADERPERMUTATION_COLORMAPPING;
5269 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5271 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5272 if (r_shadow_usingshadowmaprect)
5273 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5274 if (r_shadow_usingshadowmap2d)
5275 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5277 if (r_shadow_shadowmapsampler)
5278 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5279 if (r_shadow_shadowmappcf > 1)
5280 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5281 else if (r_shadow_shadowmappcf)
5282 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5284 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5285 permutation |= SHADERPERMUTATION_REFLECTION;
5286 if (rsurface.texture->reflectmasktexture)
5287 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5288 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5289 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5291 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
5293 if (r_glsl_offsetmapping.integer)
5295 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5296 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5297 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5298 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5299 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5301 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5302 if (r_glsl_offsetmapping_reliefmapping.integer)
5303 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5306 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5307 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5308 // directional model lighting
5309 mode = SHADERMODE_LIGHTDIRECTION;
5310 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5311 permutation |= SHADERPERMUTATION_GLOW;
5312 permutation |= SHADERPERMUTATION_DIFFUSE;
5313 if (specularscale > 0)
5315 permutation |= SHADERPERMUTATION_SPECULAR;
5316 if (r_shadow_glossexact.integer)
5317 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5319 if (r_refdef.fogenabled)
5320 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5321 if (rsurface.texture->colormapping)
5322 permutation |= SHADERPERMUTATION_COLORMAPPING;
5323 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5325 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5326 if (r_shadow_usingshadowmaprect)
5327 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5328 if (r_shadow_usingshadowmap2d)
5329 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5331 if (r_shadow_shadowmapsampler)
5332 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5333 if (r_shadow_shadowmappcf > 1)
5334 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5335 else if (r_shadow_shadowmappcf)
5336 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5338 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5339 permutation |= SHADERPERMUTATION_REFLECTION;
5340 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5341 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5342 if (rsurface.texture->reflectmasktexture)
5343 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5344 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5345 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5347 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5349 if (r_glsl_offsetmapping.integer)
5351 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5352 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5353 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5354 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5355 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5357 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5358 if (r_glsl_offsetmapping_reliefmapping.integer)
5359 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5362 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5363 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5364 // ambient model lighting
5365 mode = SHADERMODE_LIGHTDIRECTION;
5366 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5367 permutation |= SHADERPERMUTATION_GLOW;
5368 if (r_refdef.fogenabled)
5369 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5370 if (rsurface.texture->colormapping)
5371 permutation |= SHADERPERMUTATION_COLORMAPPING;
5372 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5374 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5375 if (r_shadow_usingshadowmaprect)
5376 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5377 if (r_shadow_usingshadowmap2d)
5378 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5380 if (r_shadow_shadowmapsampler)
5381 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5382 if (r_shadow_shadowmappcf > 1)
5383 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5384 else if (r_shadow_shadowmappcf)
5385 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5387 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5388 permutation |= SHADERPERMUTATION_REFLECTION;
5389 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5390 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5391 if (rsurface.texture->reflectmasktexture)
5392 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5393 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5394 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5398 if (r_glsl_offsetmapping.integer)
5400 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5401 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5402 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5403 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5404 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5406 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5407 if (r_glsl_offsetmapping_reliefmapping.integer)
5408 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5411 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5412 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5414 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5415 permutation |= SHADERPERMUTATION_GLOW;
5416 if (r_refdef.fogenabled)
5417 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5418 if (rsurface.texture->colormapping)
5419 permutation |= SHADERPERMUTATION_COLORMAPPING;
5420 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5422 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5423 if (r_shadow_usingshadowmaprect)
5424 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5425 if (r_shadow_usingshadowmap2d)
5426 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5428 if (r_shadow_shadowmapsampler)
5429 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5430 if (r_shadow_shadowmappcf > 1)
5431 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5432 else if (r_shadow_shadowmappcf)
5433 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5435 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5436 permutation |= SHADERPERMUTATION_REFLECTION;
5437 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5438 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5439 if (rsurface.texture->reflectmasktexture)
5440 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5441 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
5443 // deluxemapping (light direction texture)
5444 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
5445 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
5447 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5448 permutation |= SHADERPERMUTATION_DIFFUSE;
5449 if (specularscale > 0)
5451 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5452 if (r_shadow_glossexact.integer)
5453 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5456 else if (r_glsl_deluxemapping.integer >= 2)
5458 // fake deluxemapping (uniform light direction in tangentspace)
5459 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5460 permutation |= SHADERPERMUTATION_DIFFUSE;
5461 if (specularscale > 0)
5463 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5464 if (r_shadow_glossexact.integer)
5465 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5468 else if (rsurface.uselightmaptexture)
5470 // ordinary lightmapping (q1bsp, q3bsp)
5471 mode = SHADERMODE_LIGHTMAP;
5475 // ordinary vertex coloring (q3bsp)
5476 mode = SHADERMODE_VERTEXCOLOR;
5478 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5479 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5481 switch(vid.renderpath)
5483 case RENDERPATH_D3D9:
5485 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5486 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5487 R_SetupShader_SetPermutationHLSL(mode, permutation);
5488 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
5489 if (mode == SHADERMODE_LIGHTSOURCE)
5491 Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
5492 hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5496 if (mode == SHADERMODE_LIGHTDIRECTION)
5498 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5501 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
5502 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
5503 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
5504 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5505 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5507 if (mode == SHADERMODE_LIGHTSOURCE)
5509 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5510 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5511 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);
5512 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);
5513 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5515 // additive passes are only darkened by fog, not tinted
5516 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5517 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5521 if (mode == SHADERMODE_FLATCOLOR)
5523 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
5525 else if (mode == SHADERMODE_LIGHTDIRECTION)
5527 hlslPSSetParameter3f(D3DPSREGISTER_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]);
5528 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);
5529 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5530 hlslPSSetParameter3f(D3DPSREGISTER_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);
5531 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5532 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5533 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5537 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);
5538 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5539 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5540 hlslPSSetParameter3f(D3DPSREGISTER_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);
5541 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5543 // additive passes are only darkened by fog, not tinted
5544 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5545 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5547 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5548 hlslPSSetParameter4f(D3DPSREGISTER_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
5549 hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5550 hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5551 hlslPSSetParameter4fv(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f);
5552 hlslPSSetParameter4fv(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f);
5553 hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5554 hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
5555 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5557 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5558 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5559 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5560 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3]);
5561 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5562 if (rsurface.texture->pantstexture)
5563 hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5565 hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
5566 if (rsurface.texture->shirttexture)
5567 hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5569 hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
5570 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5571 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
5572 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
5573 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
5574 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
5575 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5576 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5578 R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5579 R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5580 R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5581 R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5582 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5583 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5584 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5585 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5586 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5587 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5588 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5589 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5590 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5591 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5592 R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5593 R_Mesh_TexBind(GL20TU_DELUXEMAP , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5594 if (rsurface.rtlight ) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5595 if (rsurfacepass == RSURFPASS_BACKGROUND)
5597 R_Mesh_TexBind(GL20TU_REFRACTION , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5598 R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5599 R_Mesh_TexBind(GL20TU_FIRST , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5603 if (permutation & SHADERPERMUTATION_REFLECTION ) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5605 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5606 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5607 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5608 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5609 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5611 R_Mesh_TexBind((permutation & SHADERPERMUTATION_SHADOWMAPORTHO) ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, (permutation & SHADERPERMUTATION_SHADOWSAMPLER) ? r_shadow_shadowmap2dtexture : r_shadow_shadowmap2dcolortexture);
5612 if (rsurface.rtlight)
5614 if (permutation & SHADERPERMUTATION_CUBEFILTER ) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5615 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5620 case RENDERPATH_D3D10:
5621 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5623 case RENDERPATH_D3D11:
5624 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5626 case RENDERPATH_GL20:
5627 if (gl_mesh_separatearrays.integer)
5629 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5630 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5631 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5632 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5633 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5634 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5635 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5636 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5640 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5641 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5643 R_SetupShader_SetPermutationGLSL(mode, permutation);
5644 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5645 if (mode == SHADERMODE_LIGHTSOURCE)
5647 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5648 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5649 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5650 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);
5651 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);
5652 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);
5654 // additive passes are only darkened by fog, not tinted
5655 if (r_glsl_permutation->loc_FogColor >= 0)
5656 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5657 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5661 if (mode == SHADERMODE_FLATCOLOR)
5663 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
5665 else if (mode == SHADERMODE_LIGHTDIRECTION)
5667 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]);
5668 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]);
5669 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);
5670 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);
5671 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);
5672 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]);
5673 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]);
5677 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]);
5678 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]);
5679 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);
5680 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);
5681 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);
5683 // additive passes are only darkened by fog, not tinted
5684 if (r_glsl_permutation->loc_FogColor >= 0)
5686 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5687 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5689 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5691 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);
5692 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]);
5693 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]);
5694 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
5695 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
5696 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5697 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5698 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5700 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5701 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5702 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5703 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]);
5704 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]);
5706 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5707 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3]);
5708 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5709 if (r_glsl_permutation->loc_Color_Pants >= 0)
5711 if (rsurface.texture->pantstexture)
5712 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5714 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5716 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5718 if (rsurface.texture->shirttexture)
5719 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5721 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5723 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]);
5724 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5725 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5726 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5727 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5728 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]);
5729 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5731 // if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_texture_white );
5732 // if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_texture_white );
5733 // if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS , r_texture_gammaramps );
5734 if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5735 if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5736 if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5737 if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5738 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5739 if (r_glsl_permutation->loc_Texture_SecondaryColor >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5740 if (r_glsl_permutation->loc_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5741 if (r_glsl_permutation->loc_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5742 if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5743 if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5744 if (r_glsl_permutation->loc_Texture_ReflectMask >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5745 if (r_glsl_permutation->loc_Texture_ReflectCube >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5746 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5747 if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5748 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5749 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5750 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5751 if (rsurfacepass == RSURFPASS_BACKGROUND)
5753 R_Mesh_TexBind(GL20TU_REFRACTION , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5754 R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5755 R_Mesh_TexBind(GL20TU_FIRST , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5759 if (permutation & SHADERPERMUTATION_REFLECTION ) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5761 // if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5762 // if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5763 if (r_glsl_permutation->loc_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5764 if (r_glsl_permutation->loc_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5765 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5767 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture );
5768 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture );
5769 if (rsurface.rtlight)
5771 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5772 if (r_shadow_usingshadowmapcube)
5773 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5774 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5779 case RENDERPATH_CGGL:
5781 if (gl_mesh_separatearrays.integer)
5783 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5784 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5785 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5786 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5787 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5788 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5789 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5790 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5794 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5795 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5797 R_SetupShader_SetPermutationCG(mode, permutation);
5798 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5799 if (mode == SHADERMODE_LIGHTSOURCE)
5801 if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5802 if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5806 if (mode == SHADERMODE_LIGHTDIRECTION)
5808 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
5811 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5812 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5813 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5814 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5815 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
5818 if (mode == SHADERMODE_LIGHTSOURCE)
5820 if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5821 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5822 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
5823 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
5824 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
5826 // additive passes are only darkened by fog, not tinted
5827 if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5828 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5832 if (mode == SHADERMODE_FLATCOLOR)
5834 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);CHECKCGERROR
5836 else if (mode == SHADERMODE_LIGHTDIRECTION)
5838 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
5839 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
5840 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
5841 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
5842 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
5843 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
5844 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
5848 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
5849 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
5850 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
5851 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
5852 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
5854 // additive passes are only darkened by fog, not tinted
5855 if (r_cg_permutation->fp_FogColor)
5857 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5858 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5860 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5863 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
5864 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
5865 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
5866 if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f);CHECKCGERROR
5867 if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f);CHECKCGERROR
5868 if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5869 if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5870 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5872 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
5873 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
5874 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5875 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5876 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5877 if (r_cg_permutation->fp_Color_Pants)
5879 if (rsurface.texture->pantstexture)
5880 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5882 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5885 if (r_cg_permutation->fp_Color_Shirt)
5887 if (rsurface.texture->shirttexture)
5888 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5890 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5893 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
5894 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
5895 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
5896 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
5897 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
5898 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
5899 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5901 // if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_texture_white );CHECKCGERROR
5902 // if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_texture_white );CHECKCGERROR
5903 // if (r_cg_permutation->fp_Texture_GammaRamps ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps , r_texture_gammaramps );CHECKCGERROR
5904 if (r_cg_permutation->fp_Texture_Normal ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal , rsurface.texture->nmaptexture );CHECKCGERROR
5905 if (r_cg_permutation->fp_Texture_Color ) CG_BindTexture(r_cg_permutation->fp_Texture_Color , rsurface.texture->basetexture );CHECKCGERROR
5906 if (r_cg_permutation->fp_Texture_Gloss ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss , rsurface.texture->glosstexture );CHECKCGERROR
5907 if (r_cg_permutation->fp_Texture_Glow ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow , rsurface.texture->glowtexture );CHECKCGERROR
5908 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture );CHECKCGERROR
5909 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );CHECKCGERROR
5910 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );CHECKCGERROR
5911 if (r_cg_permutation->fp_Texture_SecondaryGlow ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );CHECKCGERROR
5912 if (r_cg_permutation->fp_Texture_Pants ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants , rsurface.texture->pantstexture );CHECKCGERROR
5913 if (r_cg_permutation->fp_Texture_Shirt ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt , rsurface.texture->shirttexture );CHECKCGERROR
5914 if (r_cg_permutation->fp_Texture_ReflectMask ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask , rsurface.texture->reflectmasktexture );CHECKCGERROR
5915 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
5916 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture );CHECKCGERROR
5917 if (r_cg_permutation->fp_Texture_FogMask ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask , r_texture_fogattenuation );CHECKCGERROR
5918 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);CHECKCGERROR
5919 if (r_cg_permutation->fp_Texture_Deluxemap ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);CHECKCGERROR
5920 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5921 if (rsurfacepass == RSURFPASS_BACKGROUND)
5923 if (r_cg_permutation->fp_Texture_Refraction ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);CHECKCGERROR
5924 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
5925 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);CHECKCGERROR
5929 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
5931 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5932 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5933 if (r_cg_permutation->fp_Texture_ScreenDiffuse ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );CHECKCGERROR
5934 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );CHECKCGERROR
5935 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5937 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5938 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5939 if (rsurface.rtlight)
5941 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5942 if (r_shadow_usingshadowmapcube)
5943 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5944 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5951 case RENDERPATH_GL13:
5952 case RENDERPATH_GL11:
5957 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5959 // select a permutation of the lighting shader appropriate to this
5960 // combination of texture, entity, light source, and fogging, only use the
5961 // minimum features necessary to avoid wasting rendering time in the
5962 // fragment shader on features that are not being used
5963 unsigned int permutation = 0;
5964 unsigned int mode = 0;
5965 const float *lightcolorbase = rtlight->currentcolor;
5966 float ambientscale = rtlight->ambientscale;
5967 float diffusescale = rtlight->diffusescale;
5968 float specularscale = rtlight->specularscale;
5969 // this is the location of the light in view space
5970 vec3_t viewlightorigin;
5971 // this transforms from view space (camera) to light space (cubemap)
5972 matrix4x4_t viewtolight;
5973 matrix4x4_t lighttoview;
5974 float viewtolight16f[16];
5975 float range = 1.0f / r_shadow_deferred_8bitrange.value;
5977 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5978 if (rtlight->currentcubemap != r_texture_whitecube)
5979 permutation |= SHADERPERMUTATION_CUBEFILTER;
5980 if (diffusescale > 0)
5981 permutation |= SHADERPERMUTATION_DIFFUSE;
5982 if (specularscale > 0)
5984 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5985 if (r_shadow_glossexact.integer)
5986 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5988 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5990 if (r_shadow_usingshadowmaprect)
5991 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5992 if (r_shadow_usingshadowmap2d)
5993 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5994 if (r_shadow_usingshadowmapcube)
5995 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5996 else if(r_shadow_shadowmapvsdct)
5997 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5999 if (r_shadow_shadowmapsampler)
6000 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
6001 if (r_shadow_shadowmappcf > 1)
6002 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
6003 else if (r_shadow_shadowmappcf)
6004 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
6006 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
6007 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
6008 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
6009 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
6010 switch(vid.renderpath)
6012 case RENDERPATH_D3D9:
6014 R_SetupShader_SetPermutationHLSL(mode, permutation);
6015 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
6016 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
6017 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
6018 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
6019 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
6020 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
6021 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
6022 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
6023 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
6024 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
6026 R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
6027 R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
6028 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
6029 R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
6030 R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
6031 if (r_shadow_usingshadowmapcube)
6032 R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
6033 R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
6034 R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
6037 case RENDERPATH_D3D10:
6038 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6040 case RENDERPATH_D3D11:
6041 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6043 case RENDERPATH_GL20:
6044 R_SetupShader_SetPermutationGLSL(mode, permutation);
6045 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
6046 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
6047 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);
6048 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);
6049 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);
6050 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]);
6051 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]);
6052 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));
6053 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]);
6054 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
6056 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
6057 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
6058 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
6059 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
6060 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
6061 if (r_shadow_usingshadowmapcube)
6062 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
6063 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
6064 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
6066 case RENDERPATH_CGGL:
6068 R_SetupShader_SetPermutationCG(mode, permutation);
6069 if (r_cg_permutation->fp_LightPosition ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
6070 if (r_cg_permutation->fp_ViewToLight ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
6071 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
6072 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
6073 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
6074 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
6075 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
6076 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
6077 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
6078 if (r_cg_permutation->fp_PixelToScreenTexCoord ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
6080 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
6081 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
6082 if (r_cg_permutation->fp_Texture_ScreenNormalMap ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
6083 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
6084 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
6085 if (r_shadow_usingshadowmapcube)
6086 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
6087 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
6088 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
6091 case RENDERPATH_GL13:
6092 case RENDERPATH_GL11:
6097 #define SKINFRAME_HASH 1024
6101 int loadsequence; // incremented each level change
6102 memexpandablearray_t array;
6103 skinframe_t *hash[SKINFRAME_HASH];
6106 r_skinframe_t r_skinframe;
6108 void R_SkinFrame_PrepareForPurge(void)
6110 r_skinframe.loadsequence++;
6111 // wrap it without hitting zero
6112 if (r_skinframe.loadsequence >= 200)
6113 r_skinframe.loadsequence = 1;
6116 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
6120 // mark the skinframe as used for the purging code
6121 skinframe->loadsequence = r_skinframe.loadsequence;
6124 void R_SkinFrame_Purge(void)
6128 for (i = 0;i < SKINFRAME_HASH;i++)
6130 for (s = r_skinframe.hash[i];s;s = s->next)
6132 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
6134 if (s->merged == s->base)
6136 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
6137 R_PurgeTexture(s->stain );s->stain = NULL;
6138 R_PurgeTexture(s->merged);s->merged = NULL;
6139 R_PurgeTexture(s->base );s->base = NULL;
6140 R_PurgeTexture(s->pants );s->pants = NULL;
6141 R_PurgeTexture(s->shirt );s->shirt = NULL;
6142 R_PurgeTexture(s->nmap );s->nmap = NULL;
6143 R_PurgeTexture(s->gloss );s->gloss = NULL;
6144 R_PurgeTexture(s->glow );s->glow = NULL;
6145 R_PurgeTexture(s->fog );s->fog = NULL;
6146 R_PurgeTexture(s->reflect);s->reflect = NULL;
6147 s->loadsequence = 0;
6153 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
6155 char basename[MAX_QPATH];
6157 Image_StripImageExtension(name, basename, sizeof(basename));
6159 if( last == NULL ) {
6161 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
6162 item = r_skinframe.hash[hashindex];
6167 // linearly search through the hash bucket
6168 for( ; item ; item = item->next ) {
6169 if( !strcmp( item->basename, basename ) ) {
6176 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
6180 char basename[MAX_QPATH];
6182 Image_StripImageExtension(name, basename, sizeof(basename));
6184 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
6185 for (item = r_skinframe.hash[hashindex];item;item = item->next)
6186 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
6190 rtexture_t *dyntexture;
6191 // check whether its a dynamic texture
6192 dyntexture = CL_GetDynTexture( basename );
6193 if (!add && !dyntexture)
6195 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
6196 memset(item, 0, sizeof(*item));
6197 strlcpy(item->basename, basename, sizeof(item->basename));
6198 item->base = dyntexture; // either NULL or dyntexture handle
6199 item->textureflags = textureflags;
6200 item->comparewidth = comparewidth;
6201 item->compareheight = compareheight;
6202 item->comparecrc = comparecrc;
6203 item->next = r_skinframe.hash[hashindex];
6204 r_skinframe.hash[hashindex] = item;
6206 else if( item->base == NULL )
6208 rtexture_t *dyntexture;
6209 // check whether its a dynamic texture
6210 // 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]
6211 dyntexture = CL_GetDynTexture( basename );
6212 item->base = dyntexture; // either NULL or dyntexture handle
6215 R_SkinFrame_MarkUsed(item);
6219 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
6221 unsigned long long avgcolor[5], wsum; \
6229 for(pix = 0; pix < cnt; ++pix) \
6232 for(comp = 0; comp < 3; ++comp) \
6234 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
6237 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
6239 for(comp = 0; comp < 3; ++comp) \
6240 avgcolor[comp] += getpixel * w; \
6243 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
6244 avgcolor[4] += getpixel; \
6246 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
6248 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
6249 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
6250 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
6251 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
6254 extern cvar_t gl_picmip;
6255 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
6258 unsigned char *pixels;
6259 unsigned char *bumppixels;
6260 unsigned char *basepixels = NULL;
6261 int basepixels_width = 0;
6262 int basepixels_height = 0;
6263 skinframe_t *skinframe;
6264 rtexture_t *ddsbase = NULL;
6265 qboolean ddshasalpha = false;
6266 float ddsavgcolor[4];
6267 char basename[MAX_QPATH];
6268 int miplevel = R_PicmipForFlags(textureflags);
6269 int savemiplevel = miplevel;
6272 if (cls.state == ca_dedicated)
6275 // return an existing skinframe if already loaded
6276 // if loading of the first image fails, don't make a new skinframe as it
6277 // would cause all future lookups of this to be missing
6278 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
6279 if (skinframe && skinframe->base)
6282 Image_StripImageExtension(name, basename, sizeof(basename));
6284 // check for DDS texture file first
6285 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
6287 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer != 0, &miplevel);
6288 if (basepixels == NULL)
6292 // FIXME handle miplevel
6294 if (developer_loading.integer)
6295 Con_Printf("loading skin \"%s\"\n", name);
6297 // we've got some pixels to store, so really allocate this new texture now
6299 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
6300 skinframe->stain = NULL;
6301 skinframe->merged = NULL;
6302 skinframe->base = NULL;
6303 skinframe->pants = NULL;
6304 skinframe->shirt = NULL;
6305 skinframe->nmap = NULL;
6306 skinframe->gloss = NULL;
6307 skinframe->glow = NULL;
6308 skinframe->fog = NULL;
6309 skinframe->reflect = NULL;
6310 skinframe->hasalpha = false;
6314 skinframe->base = ddsbase;
6315 skinframe->hasalpha = ddshasalpha;
6316 VectorCopy(ddsavgcolor, skinframe->avgcolor);
6317 if (r_loadfog && skinframe->hasalpha)
6318 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
6319 //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]);
6323 basepixels_width = image_width;
6324 basepixels_height = image_height;
6325 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), miplevel, NULL);
6326 if (textureflags & TEXF_ALPHA)
6328 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
6330 if (basepixels[j] < 255)
6332 skinframe->hasalpha = true;
6336 if (r_loadfog && skinframe->hasalpha)
6338 // has transparent pixels
6339 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6340 for (j = 0;j < image_width * image_height * 4;j += 4)
6345 pixels[j+3] = basepixels[j+3];
6347 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), miplevel, NULL);
6351 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
6352 //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]);
6353 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
6354 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true);
6355 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
6356 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true);
6361 mymiplevel = savemiplevel;
6362 if (r_loadnormalmap)
6363 skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, mymiplevel);
6364 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6366 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6367 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6368 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6369 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6372 // _norm is the name used by tenebrae and has been adopted as standard
6373 if (r_loadnormalmap && skinframe->nmap == NULL)
6375 mymiplevel = savemiplevel;
6376 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6378 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), mymiplevel, NULL);
6382 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6384 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6385 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
6386 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), mymiplevel, NULL);
6388 Mem_Free(bumppixels);
6390 else if (r_shadow_bumpscale_basetexture.value > 0)
6392 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
6393 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
6394 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), mymiplevel, NULL);
6397 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
6398 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true);
6401 // _luma is supported only for tenebrae compatibility
6402 // _glow is the preferred name
6403 mymiplevel = savemiplevel;
6404 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel))))
6406 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), mymiplevel, NULL);
6407 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
6408 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true);
6409 Mem_Free(pixels);pixels = NULL;
6412 mymiplevel = savemiplevel;
6413 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6415 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), mymiplevel, NULL);
6416 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
6417 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true);
6422 mymiplevel = savemiplevel;
6423 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6425 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), mymiplevel, NULL);
6426 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
6427 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true);
6432 mymiplevel = savemiplevel;
6433 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6435 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), mymiplevel, NULL);
6436 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
6437 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true);
6442 mymiplevel = savemiplevel;
6443 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6445 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), mymiplevel, NULL);
6446 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
6447 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true);
6453 Mem_Free(basepixels);
6458 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
6459 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
6462 unsigned char *temp1, *temp2;
6463 skinframe_t *skinframe;
6465 if (cls.state == ca_dedicated)
6468 // if already loaded just return it, otherwise make a new skinframe
6469 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
6470 if (skinframe && skinframe->base)
6473 skinframe->stain = NULL;
6474 skinframe->merged = NULL;
6475 skinframe->base = NULL;
6476 skinframe->pants = NULL;
6477 skinframe->shirt = NULL;
6478 skinframe->nmap = NULL;
6479 skinframe->gloss = NULL;
6480 skinframe->glow = NULL;
6481 skinframe->fog = NULL;
6482 skinframe->reflect = NULL;
6483 skinframe->hasalpha = false;
6485 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6489 if (developer_loading.integer)
6490 Con_Printf("loading 32bit skin \"%s\"\n", name);
6492 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
6494 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6495 temp2 = temp1 + width * height * 4;
6496 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6497 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, -1, NULL);
6500 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, skinframe->textureflags, -1, NULL);
6501 if (textureflags & TEXF_ALPHA)
6503 for (i = 3;i < width * height * 4;i += 4)
6505 if (skindata[i] < 255)
6507 skinframe->hasalpha = true;
6511 if (r_loadfog && skinframe->hasalpha)
6513 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
6514 memcpy(fogpixels, skindata, width * height * 4);
6515 for (i = 0;i < width * height * 4;i += 4)
6516 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
6517 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, skinframe->textureflags, -1, NULL);
6518 Mem_Free(fogpixels);
6522 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
6523 //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]);
6528 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
6532 skinframe_t *skinframe;
6534 if (cls.state == ca_dedicated)
6537 // if already loaded just return it, otherwise make a new skinframe
6538 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6539 if (skinframe && skinframe->base)
6542 skinframe->stain = NULL;
6543 skinframe->merged = NULL;
6544 skinframe->base = NULL;
6545 skinframe->pants = NULL;
6546 skinframe->shirt = NULL;
6547 skinframe->nmap = NULL;
6548 skinframe->gloss = NULL;
6549 skinframe->glow = NULL;
6550 skinframe->fog = NULL;
6551 skinframe->reflect = NULL;
6552 skinframe->hasalpha = false;
6554 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6558 if (developer_loading.integer)
6559 Con_Printf("loading quake skin \"%s\"\n", name);
6561 // 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)
6562 skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height);
6563 memcpy(skinframe->qpixels, skindata, width*height);
6564 skinframe->qwidth = width;
6565 skinframe->qheight = height;
6568 for (i = 0;i < width * height;i++)
6569 featuresmask |= palette_featureflags[skindata[i]];
6571 skinframe->hasalpha = false;
6572 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
6573 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
6574 skinframe->qgeneratemerged = true;
6575 skinframe->qgeneratebase = skinframe->qhascolormapping;
6576 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
6578 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
6579 //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]);
6584 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
6588 unsigned char *skindata;
6590 if (!skinframe->qpixels)
6593 if (!skinframe->qhascolormapping)
6594 colormapped = false;
6598 if (!skinframe->qgeneratebase)
6603 if (!skinframe->qgeneratemerged)
6607 width = skinframe->qwidth;
6608 height = skinframe->qheight;
6609 skindata = skinframe->qpixels;
6611 if (skinframe->qgeneratenmap)
6613 unsigned char *temp1, *temp2;
6614 skinframe->qgeneratenmap = false;
6615 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6616 temp2 = temp1 + width * height * 4;
6617 // use either a custom palette or the quake palette
6618 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
6619 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6620 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, skinframe->textureflags | TEXF_ALPHA, -1, NULL);
6624 if (skinframe->qgenerateglow)
6626 skinframe->qgenerateglow = false;
6627 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
6632 skinframe->qgeneratebase = false;
6633 skinframe->base = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
6634 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6635 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6639 skinframe->qgeneratemerged = false;
6640 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
6643 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6645 Mem_Free(skinframe->qpixels);
6646 skinframe->qpixels = NULL;
6650 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)
6653 skinframe_t *skinframe;
6655 if (cls.state == ca_dedicated)
6658 // if already loaded just return it, otherwise make a new skinframe
6659 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6660 if (skinframe && skinframe->base)
6663 skinframe->stain = NULL;
6664 skinframe->merged = NULL;
6665 skinframe->base = NULL;
6666 skinframe->pants = NULL;
6667 skinframe->shirt = NULL;
6668 skinframe->nmap = NULL;
6669 skinframe->gloss = NULL;
6670 skinframe->glow = NULL;
6671 skinframe->fog = NULL;
6672 skinframe->reflect = NULL;
6673 skinframe->hasalpha = false;
6675 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6679 if (developer_loading.integer)
6680 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6682 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette);
6683 if (textureflags & TEXF_ALPHA)
6685 for (i = 0;i < width * height;i++)
6687 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6689 skinframe->hasalpha = true;
6693 if (r_loadfog && skinframe->hasalpha)
6694 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, alphapalette);
6697 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6698 //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]);
6703 skinframe_t *R_SkinFrame_LoadMissing(void)
6705 skinframe_t *skinframe;
6707 if (cls.state == ca_dedicated)
6710 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6711 skinframe->stain = NULL;
6712 skinframe->merged = NULL;
6713 skinframe->base = NULL;
6714 skinframe->pants = NULL;
6715 skinframe->shirt = NULL;
6716 skinframe->nmap = NULL;
6717 skinframe->gloss = NULL;
6718 skinframe->glow = NULL;
6719 skinframe->fog = NULL;
6720 skinframe->reflect = NULL;
6721 skinframe->hasalpha = false;
6723 skinframe->avgcolor[0] = rand() / RAND_MAX;
6724 skinframe->avgcolor[1] = rand() / RAND_MAX;
6725 skinframe->avgcolor[2] = rand() / RAND_MAX;
6726 skinframe->avgcolor[3] = 1;
6731 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6732 typedef struct suffixinfo_s
6735 qboolean flipx, flipy, flipdiagonal;
6738 static suffixinfo_t suffix[3][6] =
6741 {"px", false, false, false},
6742 {"nx", false, false, false},
6743 {"py", false, false, false},
6744 {"ny", false, false, false},
6745 {"pz", false, false, false},
6746 {"nz", false, false, false}
6749 {"posx", false, false, false},
6750 {"negx", false, false, false},
6751 {"posy", false, false, false},
6752 {"negy", false, false, false},
6753 {"posz", false, false, false},
6754 {"negz", false, false, false}
6757 {"rt", true, false, true},
6758 {"lf", false, true, true},
6759 {"ft", true, true, false},
6760 {"bk", false, false, false},
6761 {"up", true, false, true},
6762 {"dn", true, false, true}
6766 static int componentorder[4] = {0, 1, 2, 3};
6768 rtexture_t *R_LoadCubemap(const char *basename)
6770 int i, j, cubemapsize;
6771 unsigned char *cubemappixels, *image_buffer;
6772 rtexture_t *cubemaptexture;
6774 // must start 0 so the first loadimagepixels has no requested width/height
6776 cubemappixels = NULL;
6777 cubemaptexture = NULL;
6778 // keep trying different suffix groups (posx, px, rt) until one loads
6779 for (j = 0;j < 3 && !cubemappixels;j++)
6781 // load the 6 images in the suffix group
6782 for (i = 0;i < 6;i++)
6784 // generate an image name based on the base and and suffix
6785 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6787 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer != 0, NULL)))
6789 // an image loaded, make sure width and height are equal
6790 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6792 // if this is the first image to load successfully, allocate the cubemap memory
6793 if (!cubemappixels && image_width >= 1)
6795 cubemapsize = image_width;
6796 // note this clears to black, so unavailable sides are black
6797 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6799 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6801 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);
6804 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6806 Mem_Free(image_buffer);
6810 // if a cubemap loaded, upload it
6813 if (developer_loading.integer)
6814 Con_Printf("loading cubemap \"%s\"\n", basename);
6816 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6817 Mem_Free(cubemappixels);
6821 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6822 if (developer_loading.integer)
6824 Con_Printf("(tried tried images ");
6825 for (j = 0;j < 3;j++)
6826 for (i = 0;i < 6;i++)
6827 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6828 Con_Print(" and was unable to find any of them).\n");
6831 return cubemaptexture;
6834 rtexture_t *R_GetCubemap(const char *basename)
6837 for (i = 0;i < r_texture_numcubemaps;i++)
6838 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6839 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6840 if (i >= MAX_CUBEMAPS)
6841 return r_texture_whitecube;
6842 r_texture_numcubemaps++;
6843 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6844 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6845 return r_texture_cubemaps[i].texture;
6848 void R_FreeCubemaps(void)
6851 for (i = 0;i < r_texture_numcubemaps;i++)
6853 if (developer_loading.integer)
6854 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6855 if (r_texture_cubemaps[i].texture)
6856 R_FreeTexture(r_texture_cubemaps[i].texture);
6858 r_texture_numcubemaps = 0;
6861 void R_Main_FreeViewCache(void)
6863 if (r_refdef.viewcache.entityvisible)
6864 Mem_Free(r_refdef.viewcache.entityvisible);
6865 if (r_refdef.viewcache.world_pvsbits)
6866 Mem_Free(r_refdef.viewcache.world_pvsbits);
6867 if (r_refdef.viewcache.world_leafvisible)
6868 Mem_Free(r_refdef.viewcache.world_leafvisible);
6869 if (r_refdef.viewcache.world_surfacevisible)
6870 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6871 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6874 void R_Main_ResizeViewCache(void)
6876 int numentities = r_refdef.scene.numentities;
6877 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6878 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6879 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6880 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6881 if (r_refdef.viewcache.maxentities < numentities)
6883 r_refdef.viewcache.maxentities = numentities;
6884 if (r_refdef.viewcache.entityvisible)
6885 Mem_Free(r_refdef.viewcache.entityvisible);
6886 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6888 if (r_refdef.viewcache.world_numclusters != numclusters)
6890 r_refdef.viewcache.world_numclusters = numclusters;
6891 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6892 if (r_refdef.viewcache.world_pvsbits)
6893 Mem_Free(r_refdef.viewcache.world_pvsbits);
6894 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6896 if (r_refdef.viewcache.world_numleafs != numleafs)
6898 r_refdef.viewcache.world_numleafs = numleafs;
6899 if (r_refdef.viewcache.world_leafvisible)
6900 Mem_Free(r_refdef.viewcache.world_leafvisible);
6901 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6903 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6905 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6906 if (r_refdef.viewcache.world_surfacevisible)
6907 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6908 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6912 extern rtexture_t *loadingscreentexture;
6913 void gl_main_start(void)
6915 loadingscreentexture = NULL;
6916 r_texture_blanknormalmap = NULL;
6917 r_texture_white = NULL;
6918 r_texture_grey128 = NULL;
6919 r_texture_black = NULL;
6920 r_texture_whitecube = NULL;
6921 r_texture_normalizationcube = NULL;
6922 r_texture_fogattenuation = NULL;
6923 r_texture_fogheighttexture = NULL;
6924 r_texture_gammaramps = NULL;
6925 r_texture_numcubemaps = 0;
6927 r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
6928 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6930 switch(vid.renderpath)
6932 case RENDERPATH_GL20:
6933 case RENDERPATH_CGGL:
6934 case RENDERPATH_D3D9:
6935 case RENDERPATH_D3D10:
6936 case RENDERPATH_D3D11:
6937 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6938 Cvar_SetValueQuick(&gl_combine, 1);
6939 Cvar_SetValueQuick(&r_glsl, 1);
6940 r_loadnormalmap = true;
6944 case RENDERPATH_GL13:
6945 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6946 Cvar_SetValueQuick(&gl_combine, 1);
6947 Cvar_SetValueQuick(&r_glsl, 0);
6948 r_loadnormalmap = false;
6949 r_loadgloss = false;
6952 case RENDERPATH_GL11:
6953 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6954 Cvar_SetValueQuick(&gl_combine, 0);
6955 Cvar_SetValueQuick(&r_glsl, 0);
6956 r_loadnormalmap = false;
6957 r_loadgloss = false;
6963 R_FrameData_Reset();
6967 memset(r_queries, 0, sizeof(r_queries));
6969 r_qwskincache = NULL;
6970 r_qwskincache_size = 0;
6972 // set up r_skinframe loading system for textures
6973 memset(&r_skinframe, 0, sizeof(r_skinframe));
6974 r_skinframe.loadsequence = 1;
6975 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6977 r_main_texturepool = R_AllocTexturePool();
6978 R_BuildBlankTextures();
6980 if (vid.support.arb_texture_cube_map)
6983 R_BuildNormalizationCube();
6985 r_texture_fogattenuation = NULL;
6986 r_texture_fogheighttexture = NULL;
6987 r_texture_gammaramps = NULL;
6988 //r_texture_fogintensity = NULL;
6989 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6990 memset(&r_waterstate, 0, sizeof(r_waterstate));
6991 r_glsl_permutation = NULL;
6992 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6993 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6994 glslshaderstring = NULL;
6996 r_cg_permutation = NULL;
6997 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6998 Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
6999 cgshaderstring = NULL;
7002 r_hlsl_permutation = NULL;
7003 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
7004 Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
7005 hlslshaderstring = NULL;
7007 memset(&r_svbsp, 0, sizeof (r_svbsp));
7009 r_refdef.fogmasktable_density = 0;
7012 void gl_main_shutdown(void)
7015 R_FrameData_Reset();
7017 R_Main_FreeViewCache();
7019 switch(vid.renderpath)
7021 case RENDERPATH_GL11:
7022 case RENDERPATH_GL13:
7023 case RENDERPATH_GL20:
7024 case RENDERPATH_CGGL:
7026 qglDeleteQueriesARB(r_maxqueries, r_queries);
7028 case RENDERPATH_D3D9:
7029 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7031 case RENDERPATH_D3D10:
7032 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7034 case RENDERPATH_D3D11:
7035 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7041 memset(r_queries, 0, sizeof(r_queries));
7043 r_qwskincache = NULL;
7044 r_qwskincache_size = 0;
7046 // clear out the r_skinframe state
7047 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
7048 memset(&r_skinframe, 0, sizeof(r_skinframe));
7051 Mem_Free(r_svbsp.nodes);
7052 memset(&r_svbsp, 0, sizeof (r_svbsp));
7053 R_FreeTexturePool(&r_main_texturepool);
7054 loadingscreentexture = NULL;
7055 r_texture_blanknormalmap = NULL;
7056 r_texture_white = NULL;
7057 r_texture_grey128 = NULL;
7058 r_texture_black = NULL;
7059 r_texture_whitecube = NULL;
7060 r_texture_normalizationcube = NULL;
7061 r_texture_fogattenuation = NULL;
7062 r_texture_fogheighttexture = NULL;
7063 r_texture_gammaramps = NULL;
7064 r_texture_numcubemaps = 0;
7065 //r_texture_fogintensity = NULL;
7066 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
7067 memset(&r_waterstate, 0, sizeof(r_waterstate));
7071 extern void CL_ParseEntityLump(char *entitystring);
7072 void gl_main_newmap(void)
7074 // FIXME: move this code to client
7075 char *entities, entname[MAX_QPATH];
7077 Mem_Free(r_qwskincache);
7078 r_qwskincache = NULL;
7079 r_qwskincache_size = 0;
7082 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
7083 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
7085 CL_ParseEntityLump(entities);
7089 if (cl.worldmodel->brush.entities)
7090 CL_ParseEntityLump(cl.worldmodel->brush.entities);
7092 R_Main_FreeViewCache();
7094 R_FrameData_Reset();
7097 void GL_Main_Init(void)
7099 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
7101 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
7102 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
7103 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
7104 if (gamemode == GAME_NEHAHRA)
7106 Cvar_RegisterVariable (&gl_fogenable);
7107 Cvar_RegisterVariable (&gl_fogdensity);
7108 Cvar_RegisterVariable (&gl_fogred);
7109 Cvar_RegisterVariable (&gl_foggreen);
7110 Cvar_RegisterVariable (&gl_fogblue);
7111 Cvar_RegisterVariable (&gl_fogstart);
7112 Cvar_RegisterVariable (&gl_fogend);
7113 Cvar_RegisterVariable (&gl_skyclip);
7115 Cvar_RegisterVariable(&r_motionblur);
7116 Cvar_RegisterVariable(&r_motionblur_maxblur);
7117 Cvar_RegisterVariable(&r_motionblur_bmin);
7118 Cvar_RegisterVariable(&r_motionblur_vmin);
7119 Cvar_RegisterVariable(&r_motionblur_vmax);
7120 Cvar_RegisterVariable(&r_motionblur_vcoeff);
7121 Cvar_RegisterVariable(&r_motionblur_randomize);
7122 Cvar_RegisterVariable(&r_damageblur);
7123 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
7124 Cvar_RegisterVariable(&r_equalize_entities_minambient);
7125 Cvar_RegisterVariable(&r_equalize_entities_by);
7126 Cvar_RegisterVariable(&r_equalize_entities_to);
7127 Cvar_RegisterVariable(&r_depthfirst);
7128 Cvar_RegisterVariable(&r_useinfinitefarclip);
7129 Cvar_RegisterVariable(&r_farclip_base);
7130 Cvar_RegisterVariable(&r_farclip_world);
7131 Cvar_RegisterVariable(&r_nearclip);
7132 Cvar_RegisterVariable(&r_showbboxes);
7133 Cvar_RegisterVariable(&r_showsurfaces);
7134 Cvar_RegisterVariable(&r_showtris);
7135 Cvar_RegisterVariable(&r_shownormals);
7136 Cvar_RegisterVariable(&r_showlighting);
7137 Cvar_RegisterVariable(&r_showshadowvolumes);
7138 Cvar_RegisterVariable(&r_showcollisionbrushes);
7139 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
7140 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
7141 Cvar_RegisterVariable(&r_showdisabledepthtest);
7142 Cvar_RegisterVariable(&r_drawportals);
7143 Cvar_RegisterVariable(&r_drawentities);
7144 Cvar_RegisterVariable(&r_draw2d);
7145 Cvar_RegisterVariable(&r_drawworld);
7146 Cvar_RegisterVariable(&r_cullentities_trace);
7147 Cvar_RegisterVariable(&r_cullentities_trace_samples);
7148 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
7149 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
7150 Cvar_RegisterVariable(&r_cullentities_trace_delay);
7151 Cvar_RegisterVariable(&r_drawviewmodel);
7152 Cvar_RegisterVariable(&r_drawexteriormodel);
7153 Cvar_RegisterVariable(&r_speeds);
7154 Cvar_RegisterVariable(&r_fullbrights);
7155 Cvar_RegisterVariable(&r_wateralpha);
7156 Cvar_RegisterVariable(&r_dynamic);
7157 Cvar_RegisterVariable(&r_fullbright);
7158 Cvar_RegisterVariable(&r_shadows);
7159 Cvar_RegisterVariable(&r_shadows_darken);
7160 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
7161 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
7162 Cvar_RegisterVariable(&r_shadows_throwdistance);
7163 Cvar_RegisterVariable(&r_shadows_throwdirection);
7164 Cvar_RegisterVariable(&r_shadows_focus);
7165 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
7166 Cvar_RegisterVariable(&r_q1bsp_skymasking);
7167 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
7168 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
7169 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
7170 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
7171 Cvar_RegisterVariable(&r_fog_exp2);
7172 Cvar_RegisterVariable(&r_drawfog);
7173 Cvar_RegisterVariable(&r_transparentdepthmasking);
7174 Cvar_RegisterVariable(&r_texture_dds_load);
7175 Cvar_RegisterVariable(&r_texture_dds_save);
7176 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
7177 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
7178 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
7179 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
7180 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
7181 Cvar_RegisterVariable(&r_textureunits);
7182 Cvar_RegisterVariable(&gl_combine);
7183 Cvar_RegisterVariable(&r_glsl);
7184 Cvar_RegisterVariable(&r_glsl_deluxemapping);
7185 Cvar_RegisterVariable(&r_glsl_offsetmapping);
7186 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
7187 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
7188 Cvar_RegisterVariable(&r_glsl_postprocess);
7189 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
7190 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
7191 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
7192 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
7193 Cvar_RegisterVariable(&r_water);
7194 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
7195 Cvar_RegisterVariable(&r_water_clippingplanebias);
7196 Cvar_RegisterVariable(&r_water_refractdistort);
7197 Cvar_RegisterVariable(&r_water_reflectdistort);
7198 Cvar_RegisterVariable(&r_lerpsprites);
7199 Cvar_RegisterVariable(&r_lerpmodels);
7200 Cvar_RegisterVariable(&r_lerplightstyles);
7201 Cvar_RegisterVariable(&r_waterscroll);
7202 Cvar_RegisterVariable(&r_bloom);
7203 Cvar_RegisterVariable(&r_bloom_colorscale);
7204 Cvar_RegisterVariable(&r_bloom_brighten);
7205 Cvar_RegisterVariable(&r_bloom_blur);
7206 Cvar_RegisterVariable(&r_bloom_resolution);
7207 Cvar_RegisterVariable(&r_bloom_colorexponent);
7208 Cvar_RegisterVariable(&r_bloom_colorsubtract);
7209 Cvar_RegisterVariable(&r_hdr);
7210 Cvar_RegisterVariable(&r_hdr_scenebrightness);
7211 Cvar_RegisterVariable(&r_hdr_glowintensity);
7212 Cvar_RegisterVariable(&r_hdr_range);
7213 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
7214 Cvar_RegisterVariable(&developer_texturelogging);
7215 Cvar_RegisterVariable(&gl_lightmaps);
7216 Cvar_RegisterVariable(&r_test);
7217 Cvar_RegisterVariable(&r_glsl_saturation);
7218 Cvar_RegisterVariable(&r_framedatasize);
7219 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
7220 Cvar_SetValue("r_fullbrights", 0);
7221 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
7223 Cvar_RegisterVariable(&r_track_sprites);
7224 Cvar_RegisterVariable(&r_track_sprites_flags);
7225 Cvar_RegisterVariable(&r_track_sprites_scalew);
7226 Cvar_RegisterVariable(&r_track_sprites_scaleh);
7227 Cvar_RegisterVariable(&r_overheadsprites_perspective);
7228 Cvar_RegisterVariable(&r_overheadsprites_pushback);
7231 extern void R_Textures_Init(void);
7232 extern void GL_Draw_Init(void);
7233 extern void GL_Main_Init(void);
7234 extern void R_Shadow_Init(void);
7235 extern void R_Sky_Init(void);
7236 extern void GL_Surf_Init(void);
7237 extern void R_Particles_Init(void);
7238 extern void R_Explosion_Init(void);
7239 extern void gl_backend_init(void);
7240 extern void Sbar_Init(void);
7241 extern void R_LightningBeams_Init(void);
7242 extern void Mod_RenderInit(void);
7243 extern void Font_Init(void);
7245 void Render_Init(void)
7258 R_LightningBeams_Init();
7267 extern char *ENGINE_EXTENSIONS;
7270 gl_renderer = (const char *)qglGetString(GL_RENDERER);
7271 gl_vendor = (const char *)qglGetString(GL_VENDOR);
7272 gl_version = (const char *)qglGetString(GL_VERSION);
7273 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
7277 if (!gl_platformextensions)
7278 gl_platformextensions = "";
7280 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
7281 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
7282 Con_Printf("GL_VERSION: %s\n", gl_version);
7283 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
7284 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
7286 VID_CheckExtensions();
7288 // LordHavoc: report supported extensions
7289 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
7291 // clear to black (loading plaque will be seen over this)
7292 GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
7295 int R_CullBox(const vec3_t mins, const vec3_t maxs)
7299 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7301 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
7304 p = r_refdef.view.frustum + i;
7309 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7313 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7317 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7321 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7325 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7329 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7333 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7337 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7345 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
7349 for (i = 0;i < numplanes;i++)
7356 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7360 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7364 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7368 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7372 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7376 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7380 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7384 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7392 //==================================================================================
7394 // LordHavoc: this stores temporary data used within the same frame
7396 qboolean r_framedata_failed;
7397 static size_t r_framedata_size;
7398 static size_t r_framedata_current;
7399 static void *r_framedata_base;
7401 void R_FrameData_Reset(void)
7403 if (r_framedata_base)
7404 Mem_Free(r_framedata_base);
7405 r_framedata_base = NULL;
7406 r_framedata_size = 0;
7407 r_framedata_current = 0;
7408 r_framedata_failed = false;
7411 void R_FrameData_NewFrame(void)
7414 if (r_framedata_failed)
7415 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
7416 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
7417 wantedsize = bound(65536, wantedsize, 128*1024*1024);
7418 if (r_framedata_size != wantedsize)
7420 r_framedata_size = wantedsize;
7421 if (r_framedata_base)
7422 Mem_Free(r_framedata_base);
7423 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
7425 r_framedata_current = 0;
7426 r_framedata_failed = false;
7429 void *R_FrameData_Alloc(size_t size)
7433 // align to 16 byte boundary
7434 size = (size + 15) & ~15;
7435 data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
7436 r_framedata_current += size;
7439 if (r_framedata_current > r_framedata_size)
7440 r_framedata_failed = true;
7442 // return NULL on everything after a failure
7443 if (r_framedata_failed)
7449 void *R_FrameData_Store(size_t size, void *data)
7451 void *d = R_FrameData_Alloc(size);
7453 memcpy(d, data, size);
7457 //==================================================================================
7459 // LordHavoc: animcache originally written by Echon, rewritten since then
7462 * Animation cache prevents re-generating mesh data for an animated model
7463 * multiple times in one frame for lighting, shadowing, reflections, etc.
7466 void R_AnimCache_Free(void)
7470 void R_AnimCache_ClearCache(void)
7473 entity_render_t *ent;
7475 for (i = 0;i < r_refdef.scene.numentities;i++)
7477 ent = r_refdef.scene.entities[i];
7478 ent->animcache_vertex3f = NULL;
7479 ent->animcache_normal3f = NULL;
7480 ent->animcache_svector3f = NULL;
7481 ent->animcache_tvector3f = NULL;
7482 ent->animcache_vertexposition = NULL;
7483 ent->animcache_vertexmesh = NULL;
7484 ent->animcache_vertexpositionbuffer = NULL;
7485 ent->animcache_vertexmeshbuffer = NULL;
7489 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
7492 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
7493 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
7494 if (!ent->animcache_vertexposition)
7495 ent->animcache_vertexposition = (r_vertexposition_t *)R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
7496 if (ent->animcache_vertexposition)
7498 for (i = 0;i < numvertices;i++)
7499 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexposition[i].vertex3f);
7500 // TODO: upload vertex buffer?
7502 if (ent->animcache_vertexmesh)
7504 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
7505 for (i = 0;i < numvertices;i++)
7506 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexmesh[i].vertex3f);
7507 if (ent->animcache_svector3f)
7508 for (i = 0;i < numvertices;i++)
7509 VectorCopy(ent->animcache_svector3f + 3*i, ent->animcache_vertexmesh[i].svector3f);
7510 if (ent->animcache_tvector3f)
7511 for (i = 0;i < numvertices;i++)
7512 VectorCopy(ent->animcache_tvector3f + 3*i, ent->animcache_vertexmesh[i].tvector3f);
7513 if (ent->animcache_normal3f)
7514 for (i = 0;i < numvertices;i++)
7515 VectorCopy(ent->animcache_normal3f + 3*i, ent->animcache_vertexmesh[i].normal3f);
7516 // TODO: upload vertex buffer?
7520 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
7522 dp_model_t *model = ent->model;
7524 // see if it's already cached this frame
7525 if (ent->animcache_vertex3f)
7527 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
7528 if (wantnormals || wanttangents)
7530 if (ent->animcache_normal3f)
7531 wantnormals = false;
7532 if (ent->animcache_svector3f)
7533 wanttangents = false;
7534 if (wantnormals || wanttangents)
7536 numvertices = model->surfmesh.num_vertices;
7538 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7541 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7542 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7544 if (!r_framedata_failed)
7546 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
7547 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7554 // see if this ent is worth caching
7555 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
7557 // get some memory for this entity and generate mesh data
7558 numvertices = model->surfmesh.num_vertices;
7559 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7561 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7564 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7565 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7567 if (!r_framedata_failed)
7569 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
7570 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7573 return !r_framedata_failed;
7576 void R_AnimCache_CacheVisibleEntities(void)
7579 qboolean wantnormals = true;
7580 qboolean wanttangents = !r_showsurfaces.integer;
7582 switch(vid.renderpath)
7584 case RENDERPATH_GL20:
7585 case RENDERPATH_CGGL:
7586 case RENDERPATH_D3D9:
7587 case RENDERPATH_D3D10:
7588 case RENDERPATH_D3D11:
7590 case RENDERPATH_GL13:
7591 case RENDERPATH_GL11:
7592 wanttangents = false;
7596 if (r_shownormals.integer)
7597 wanttangents = wantnormals = true;
7599 // TODO: thread this
7600 // NOTE: R_PrepareRTLights() also caches entities
7602 for (i = 0;i < r_refdef.scene.numentities;i++)
7603 if (r_refdef.viewcache.entityvisible[i])
7604 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
7607 //==================================================================================
7609 static void R_View_UpdateEntityLighting (void)
7612 entity_render_t *ent;
7613 vec3_t tempdiffusenormal, avg;
7614 vec_t f, fa, fd, fdd;
7615 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
7617 for (i = 0;i < r_refdef.scene.numentities;i++)
7619 ent = r_refdef.scene.entities[i];
7621 // skip unseen models
7622 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
7626 if (ent->model && ent->model->brush.num_leafs)
7628 // TODO: use modellight for r_ambient settings on world?
7629 VectorSet(ent->modellight_ambient, 0, 0, 0);
7630 VectorSet(ent->modellight_diffuse, 0, 0, 0);
7631 VectorSet(ent->modellight_lightdir, 0, 0, 1);
7635 // fetch the lighting from the worldmodel data
7636 VectorClear(ent->modellight_ambient);
7637 VectorClear(ent->modellight_diffuse);
7638 VectorClear(tempdiffusenormal);
7639 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
7642 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7643 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
7644 if(ent->flags & RENDER_EQUALIZE)
7646 // first fix up ambient lighting...
7647 if(r_equalize_entities_minambient.value > 0)
7649 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7652 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
7653 if(fa < r_equalize_entities_minambient.value * fd)
7656 // fa'/fd' = minambient
7657 // fa'+0.25*fd' = fa+0.25*fd
7659 // fa' = fd' * minambient
7660 // fd'*(0.25+minambient) = fa+0.25*fd
7662 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7663 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7665 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7666 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
7667 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7668 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7673 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7675 VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
7676 f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
7679 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
7680 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
7681 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7687 VectorSet(ent->modellight_ambient, 1, 1, 1);
7689 // move the light direction into modelspace coordinates for lighting code
7690 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7691 if(VectorLength2(ent->modellight_lightdir) == 0)
7692 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7693 VectorNormalize(ent->modellight_lightdir);
7697 #define MAX_LINEOFSIGHTTRACES 64
7699 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7702 vec3_t boxmins, boxmaxs;
7705 dp_model_t *model = r_refdef.scene.worldmodel;
7707 if (!model || !model->brush.TraceLineOfSight)
7710 // expand the box a little
7711 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7712 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7713 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7714 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7715 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7716 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7718 // return true if eye is inside enlarged box
7719 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7723 VectorCopy(eye, start);
7724 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7725 if (model->brush.TraceLineOfSight(model, start, end))
7728 // try various random positions
7729 for (i = 0;i < numsamples;i++)
7731 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7732 if (model->brush.TraceLineOfSight(model, start, end))
7740 static void R_View_UpdateEntityVisible (void)
7745 entity_render_t *ent;
7747 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7748 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7749 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
7750 : RENDER_EXTERIORMODEL;
7751 if (!r_drawviewmodel.integer)
7752 renderimask |= RENDER_VIEWMODEL;
7753 if (!r_drawexteriormodel.integer)
7754 renderimask |= RENDER_EXTERIORMODEL;
7755 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7757 // worldmodel can check visibility
7758 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7759 for (i = 0;i < r_refdef.scene.numentities;i++)
7761 ent = r_refdef.scene.entities[i];
7762 if (!(ent->flags & renderimask))
7763 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)))
7764 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))
7765 r_refdef.viewcache.entityvisible[i] = true;
7767 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7768 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7770 for (i = 0;i < r_refdef.scene.numentities;i++)
7772 ent = r_refdef.scene.entities[i];
7773 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7775 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7777 continue; // temp entities do pvs only
7778 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7779 ent->last_trace_visibility = realtime;
7780 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7781 r_refdef.viewcache.entityvisible[i] = 0;
7788 // no worldmodel or it can't check visibility
7789 for (i = 0;i < r_refdef.scene.numentities;i++)
7791 ent = r_refdef.scene.entities[i];
7792 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));
7797 /// only used if skyrendermasked, and normally returns false
7798 int R_DrawBrushModelsSky (void)
7801 entity_render_t *ent;
7804 for (i = 0;i < r_refdef.scene.numentities;i++)
7806 if (!r_refdef.viewcache.entityvisible[i])
7808 ent = r_refdef.scene.entities[i];
7809 if (!ent->model || !ent->model->DrawSky)
7811 ent->model->DrawSky(ent);
7817 static void R_DrawNoModel(entity_render_t *ent);
7818 static void R_DrawModels(void)
7821 entity_render_t *ent;
7823 for (i = 0;i < r_refdef.scene.numentities;i++)
7825 if (!r_refdef.viewcache.entityvisible[i])
7827 ent = r_refdef.scene.entities[i];
7828 r_refdef.stats.entities++;
7829 if (ent->model && ent->model->Draw != NULL)
7830 ent->model->Draw(ent);
7836 static void R_DrawModelsDepth(void)
7839 entity_render_t *ent;
7841 for (i = 0;i < r_refdef.scene.numentities;i++)
7843 if (!r_refdef.viewcache.entityvisible[i])
7845 ent = r_refdef.scene.entities[i];
7846 if (ent->model && ent->model->DrawDepth != NULL)
7847 ent->model->DrawDepth(ent);
7851 static void R_DrawModelsDebug(void)
7854 entity_render_t *ent;
7856 for (i = 0;i < r_refdef.scene.numentities;i++)
7858 if (!r_refdef.viewcache.entityvisible[i])
7860 ent = r_refdef.scene.entities[i];
7861 if (ent->model && ent->model->DrawDebug != NULL)
7862 ent->model->DrawDebug(ent);
7866 static void R_DrawModelsAddWaterPlanes(void)
7869 entity_render_t *ent;
7871 for (i = 0;i < r_refdef.scene.numentities;i++)
7873 if (!r_refdef.viewcache.entityvisible[i])
7875 ent = r_refdef.scene.entities[i];
7876 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7877 ent->model->DrawAddWaterPlanes(ent);
7881 static void R_View_SetFrustum(void)
7884 double slopex, slopey;
7885 vec3_t forward, left, up, origin;
7887 // we can't trust r_refdef.view.forward and friends in reflected scenes
7888 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7891 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7892 r_refdef.view.frustum[0].normal[1] = 0 - 0;
7893 r_refdef.view.frustum[0].normal[2] = -1 - 0;
7894 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7895 r_refdef.view.frustum[1].normal[1] = 0 + 0;
7896 r_refdef.view.frustum[1].normal[2] = -1 + 0;
7897 r_refdef.view.frustum[2].normal[0] = 0 - 0;
7898 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7899 r_refdef.view.frustum[2].normal[2] = -1 - 0;
7900 r_refdef.view.frustum[3].normal[0] = 0 + 0;
7901 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7902 r_refdef.view.frustum[3].normal[2] = -1 + 0;
7906 zNear = r_refdef.nearclip;
7907 nudge = 1.0 - 1.0 / (1<<23);
7908 r_refdef.view.frustum[4].normal[0] = 0 - 0;
7909 r_refdef.view.frustum[4].normal[1] = 0 - 0;
7910 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7911 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7912 r_refdef.view.frustum[5].normal[0] = 0 + 0;
7913 r_refdef.view.frustum[5].normal[1] = 0 + 0;
7914 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7915 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7921 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7922 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7923 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7924 r_refdef.view.frustum[0].dist = m[15] - m[12];
7926 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7927 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7928 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7929 r_refdef.view.frustum[1].dist = m[15] + m[12];
7931 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7932 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7933 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7934 r_refdef.view.frustum[2].dist = m[15] - m[13];
7936 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7937 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7938 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7939 r_refdef.view.frustum[3].dist = m[15] + m[13];
7941 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7942 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7943 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7944 r_refdef.view.frustum[4].dist = m[15] - m[14];
7946 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7947 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7948 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7949 r_refdef.view.frustum[5].dist = m[15] + m[14];
7952 if (r_refdef.view.useperspective)
7954 slopex = 1.0 / r_refdef.view.frustum_x;
7955 slopey = 1.0 / r_refdef.view.frustum_y;
7956 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
7957 VectorMA(forward, slopex, left, r_refdef.view.frustum[1].normal);
7958 VectorMA(forward, -slopey, up , r_refdef.view.frustum[2].normal);
7959 VectorMA(forward, slopey, up , r_refdef.view.frustum[3].normal);
7960 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7962 // Leaving those out was a mistake, those were in the old code, and they
7963 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7964 // I couldn't reproduce it after adding those normalizations. --blub
7965 VectorNormalize(r_refdef.view.frustum[0].normal);
7966 VectorNormalize(r_refdef.view.frustum[1].normal);
7967 VectorNormalize(r_refdef.view.frustum[2].normal);
7968 VectorNormalize(r_refdef.view.frustum[3].normal);
7970 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7971 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]);
7972 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]);
7973 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]);
7974 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]);
7976 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7977 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7978 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7979 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7980 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7984 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7985 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7986 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7987 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7988 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7989 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7990 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7991 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7992 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7993 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7995 r_refdef.view.numfrustumplanes = 5;
7997 if (r_refdef.view.useclipplane)
7999 r_refdef.view.numfrustumplanes = 6;
8000 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
8003 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
8004 PlaneClassify(r_refdef.view.frustum + i);
8006 // LordHavoc: note to all quake engine coders, Quake had a special case
8007 // for 90 degrees which assumed a square view (wrong), so I removed it,
8008 // Quake2 has it disabled as well.
8010 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
8011 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
8012 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
8013 //PlaneClassify(&frustum[0]);
8015 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
8016 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
8017 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
8018 //PlaneClassify(&frustum[1]);
8020 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
8021 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
8022 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
8023 //PlaneClassify(&frustum[2]);
8025 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
8026 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
8027 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
8028 //PlaneClassify(&frustum[3]);
8031 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
8032 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
8033 //PlaneClassify(&frustum[4]);
8036 void R_View_Update(void)
8038 R_Main_ResizeViewCache();
8039 R_View_SetFrustum();
8040 R_View_WorldVisibility(r_refdef.view.useclipplane);
8041 R_View_UpdateEntityVisible();
8042 R_View_UpdateEntityLighting();
8045 void R_SetupView(qboolean allowwaterclippingplane)
8047 const float *customclipplane = NULL;
8049 if (r_refdef.view.useclipplane && allowwaterclippingplane)
8051 // LordHavoc: couldn't figure out how to make this approach the
8052 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
8053 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
8054 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
8055 dist = r_refdef.view.clipplane.dist;
8056 plane[0] = r_refdef.view.clipplane.normal[0];
8057 plane[1] = r_refdef.view.clipplane.normal[1];
8058 plane[2] = r_refdef.view.clipplane.normal[2];
8060 customclipplane = plane;
8063 if (!r_refdef.view.useperspective)
8064 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);
8065 else if (vid.stencil && r_useinfinitefarclip.integer)
8066 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);
8068 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);
8069 R_SetViewport(&r_refdef.view.viewport);
8072 void R_EntityMatrix(const matrix4x4_t *matrix)
8074 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
8076 gl_modelmatrixchanged = false;
8077 gl_modelmatrix = *matrix;
8078 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
8079 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
8080 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
8081 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
8083 switch(vid.renderpath)
8085 case RENDERPATH_D3D9:
8087 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
8088 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
8091 case RENDERPATH_D3D10:
8092 Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
8094 case RENDERPATH_D3D11:
8095 Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
8097 case RENDERPATH_GL20:
8098 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
8099 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
8100 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8102 case RENDERPATH_CGGL:
8105 if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
8106 if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
8107 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8110 case RENDERPATH_GL13:
8111 case RENDERPATH_GL11:
8112 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8118 void R_ResetViewRendering2D(void)
8120 r_viewport_t viewport;
8123 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
8124 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);
8125 R_SetViewport(&viewport);
8126 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
8127 GL_Color(1, 1, 1, 1);
8128 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8129 GL_BlendFunc(GL_ONE, GL_ZERO);
8130 GL_AlphaTest(false);
8131 GL_ScissorTest(false);
8132 GL_DepthMask(false);
8133 GL_DepthRange(0, 1);
8134 GL_DepthTest(false);
8135 GL_DepthFunc(GL_LEQUAL);
8136 R_EntityMatrix(&identitymatrix);
8137 R_Mesh_ResetTextureState();
8138 GL_PolygonOffset(0, 0);
8139 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8140 switch(vid.renderpath)
8142 case RENDERPATH_GL11:
8143 case RENDERPATH_GL13:
8144 case RENDERPATH_GL20:
8145 case RENDERPATH_CGGL:
8146 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8148 case RENDERPATH_D3D9:
8149 case RENDERPATH_D3D10:
8150 case RENDERPATH_D3D11:
8153 GL_CullFace(GL_NONE);
8156 void R_ResetViewRendering3D(void)
8161 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8162 GL_Color(1, 1, 1, 1);
8163 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8164 GL_BlendFunc(GL_ONE, GL_ZERO);
8165 GL_AlphaTest(false);
8166 GL_ScissorTest(true);
8168 GL_DepthRange(0, 1);
8170 GL_DepthFunc(GL_LEQUAL);
8171 R_EntityMatrix(&identitymatrix);
8172 R_Mesh_ResetTextureState();
8173 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8174 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8175 switch(vid.renderpath)
8177 case RENDERPATH_GL11:
8178 case RENDERPATH_GL13:
8179 case RENDERPATH_GL20:
8180 case RENDERPATH_CGGL:
8181 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8183 case RENDERPATH_D3D9:
8184 case RENDERPATH_D3D10:
8185 case RENDERPATH_D3D11:
8188 GL_CullFace(r_refdef.view.cullface_back);
8193 R_RenderView_UpdateViewVectors
8196 static void R_RenderView_UpdateViewVectors(void)
8198 // break apart the view matrix into vectors for various purposes
8199 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
8200 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
8201 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
8202 VectorNegate(r_refdef.view.left, r_refdef.view.right);
8203 // make an inverted copy of the view matrix for tracking sprites
8204 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
8207 void R_RenderScene(void);
8208 void R_RenderWaterPlanes(void);
8210 static void R_Water_StartFrame(void)
8213 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
8214 r_waterstate_waterplane_t *p;
8216 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
8219 switch(vid.renderpath)
8221 case RENDERPATH_GL20:
8222 case RENDERPATH_CGGL:
8223 case RENDERPATH_D3D9:
8224 case RENDERPATH_D3D10:
8225 case RENDERPATH_D3D11:
8227 case RENDERPATH_GL13:
8228 case RENDERPATH_GL11:
8232 // set waterwidth and waterheight to the water resolution that will be
8233 // used (often less than the screen resolution for faster rendering)
8234 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
8235 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
8237 // calculate desired texture sizes
8238 // can't use water if the card does not support the texture size
8239 if (!r_water.integer || r_showsurfaces.integer)
8240 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
8241 else if (vid.support.arb_texture_non_power_of_two)
8243 texturewidth = waterwidth;
8244 textureheight = waterheight;
8245 camerawidth = waterwidth;
8246 cameraheight = waterheight;
8250 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
8251 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
8252 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
8253 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
8256 // allocate textures as needed
8257 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
8259 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8260 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
8262 if (p->texture_refraction)
8263 R_FreeTexture(p->texture_refraction);
8264 p->texture_refraction = NULL;
8265 if (p->texture_reflection)
8266 R_FreeTexture(p->texture_reflection);
8267 p->texture_reflection = NULL;
8268 if (p->texture_camera)
8269 R_FreeTexture(p->texture_camera);
8270 p->texture_camera = NULL;
8272 memset(&r_waterstate, 0, sizeof(r_waterstate));
8273 r_waterstate.texturewidth = texturewidth;
8274 r_waterstate.textureheight = textureheight;
8275 r_waterstate.camerawidth = camerawidth;
8276 r_waterstate.cameraheight = cameraheight;
8279 if (r_waterstate.texturewidth)
8281 r_waterstate.enabled = true;
8283 // when doing a reduced render (HDR) we want to use a smaller area
8284 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
8285 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
8287 // set up variables that will be used in shader setup
8288 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8289 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8290 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8291 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8294 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8295 r_waterstate.numwaterplanes = 0;
8298 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
8300 int triangleindex, planeindex;
8307 r_waterstate_waterplane_t *p;
8308 texture_t *t = R_GetCurrentTexture(surface->texture);
8309 cam_ent = t->camera_entity;
8310 if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
8313 // just use the first triangle with a valid normal for any decisions
8314 VectorClear(normal);
8315 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
8317 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
8318 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
8319 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
8320 TriangleNormal(vert[0], vert[1], vert[2], normal);
8321 if (VectorLength2(normal) >= 0.001)
8325 VectorCopy(normal, plane.normal);
8326 VectorNormalize(plane.normal);
8327 plane.dist = DotProduct(vert[0], plane.normal);
8328 PlaneClassify(&plane);
8329 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
8331 // skip backfaces (except if nocullface is set)
8332 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
8334 VectorNegate(plane.normal, plane.normal);
8336 PlaneClassify(&plane);
8340 // find a matching plane if there is one
8341 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8342 if(p->camera_entity == t->camera_entity)
8343 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
8345 if (planeindex >= r_waterstate.maxwaterplanes)
8346 return; // nothing we can do, out of planes
8348 // if this triangle does not fit any known plane rendered this frame, add one
8349 if (planeindex >= r_waterstate.numwaterplanes)
8351 // store the new plane
8352 r_waterstate.numwaterplanes++;
8354 // clear materialflags and pvs
8355 p->materialflags = 0;
8356 p->pvsvalid = false;
8357 p->camera_entity = t->camera_entity;
8359 // merge this surface's materialflags into the waterplane
8360 p->materialflags |= t->currentmaterialflags;
8361 if(!(p->materialflags & MATERIALFLAG_CAMERA))
8363 // merge this surface's PVS into the waterplane
8364 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
8365 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
8366 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
8368 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
8374 static void R_Water_ProcessPlanes(void)
8376 r_refdef_view_t originalview;
8377 r_refdef_view_t myview;
8379 r_waterstate_waterplane_t *p;
8382 originalview = r_refdef.view;
8384 // make sure enough textures are allocated
8385 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8387 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8389 if (!p->texture_refraction)
8390 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8391 if (!p->texture_refraction)
8394 else if (p->materialflags & MATERIALFLAG_CAMERA)
8396 if (!p->texture_camera)
8397 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
8398 if (!p->texture_camera)
8402 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8404 if (!p->texture_reflection)
8405 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8406 if (!p->texture_reflection)
8412 r_refdef.view = originalview;
8413 r_refdef.view.showdebug = false;
8414 r_refdef.view.width = r_waterstate.waterwidth;
8415 r_refdef.view.height = r_waterstate.waterheight;
8416 r_refdef.view.useclipplane = true;
8417 myview = r_refdef.view;
8418 r_waterstate.renderingscene = true;
8419 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8421 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8423 r_refdef.view = myview;
8424 // render reflected scene and copy into texture
8425 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
8426 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
8427 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
8428 r_refdef.view.clipplane = p->plane;
8429 // reverse the cullface settings for this render
8430 r_refdef.view.cullface_front = GL_FRONT;
8431 r_refdef.view.cullface_back = GL_BACK;
8432 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
8434 r_refdef.view.usecustompvs = true;
8436 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8438 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8441 R_ResetViewRendering3D();
8442 R_ClearScreen(r_refdef.fogenabled);
8446 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);
8449 // render the normal view scene and copy into texture
8450 // (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)
8451 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8453 r_waterstate.renderingrefraction = true;
8454 r_refdef.view = myview;
8456 r_refdef.view.clipplane = p->plane;
8457 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8458 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8460 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
8462 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8463 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
8464 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8465 R_RenderView_UpdateViewVectors();
8466 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
8469 PlaneClassify(&r_refdef.view.clipplane);
8471 R_ResetViewRendering3D();
8472 R_ClearScreen(r_refdef.fogenabled);
8476 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);
8477 r_waterstate.renderingrefraction = false;
8479 else if (p->materialflags & MATERIALFLAG_CAMERA)
8481 r_refdef.view = myview;
8483 r_refdef.view.clipplane = p->plane;
8484 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8485 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8487 r_refdef.view.width = r_waterstate.camerawidth;
8488 r_refdef.view.height = r_waterstate.cameraheight;
8489 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
8490 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
8492 if(p->camera_entity)
8494 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8495 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8498 // reverse the cullface settings for this render
8499 r_refdef.view.cullface_front = GL_FRONT;
8500 r_refdef.view.cullface_back = GL_BACK;
8501 // also reverse the view matrix
8502 Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, 1, -1); // this serves to invert texcoords in the result, as the copied texture is mapped the wrong way round
8503 R_RenderView_UpdateViewVectors();
8504 if(p->camera_entity)
8505 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);
8507 // camera needs no clipplane
8508 r_refdef.view.useclipplane = false;
8510 PlaneClassify(&r_refdef.view.clipplane);
8512 R_ResetViewRendering3D();
8513 R_ClearScreen(r_refdef.fogenabled);
8517 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);
8518 r_waterstate.renderingrefraction = false;
8522 r_waterstate.renderingscene = false;
8523 r_refdef.view = originalview;
8524 R_ResetViewRendering3D();
8525 R_ClearScreen(r_refdef.fogenabled);
8529 r_refdef.view = originalview;
8530 r_waterstate.renderingscene = false;
8531 Cvar_SetValueQuick(&r_water, 0);
8532 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
8536 void R_Bloom_StartFrame(void)
8538 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8540 switch(vid.renderpath)
8542 case RENDERPATH_GL20:
8543 case RENDERPATH_CGGL:
8544 case RENDERPATH_D3D9:
8545 case RENDERPATH_D3D10:
8546 case RENDERPATH_D3D11:
8548 case RENDERPATH_GL13:
8549 case RENDERPATH_GL11:
8553 // set bloomwidth and bloomheight to the bloom resolution that will be
8554 // used (often less than the screen resolution for faster rendering)
8555 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8556 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8557 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8558 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8559 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8561 // calculate desired texture sizes
8562 if (vid.support.arb_texture_non_power_of_two)
8564 screentexturewidth = r_refdef.view.width;
8565 screentextureheight = r_refdef.view.height;
8566 bloomtexturewidth = r_bloomstate.bloomwidth;
8567 bloomtextureheight = r_bloomstate.bloomheight;
8571 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
8572 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
8573 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
8574 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
8577 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))
8579 Cvar_SetValueQuick(&r_hdr, 0);
8580 Cvar_SetValueQuick(&r_bloom, 0);
8581 Cvar_SetValueQuick(&r_motionblur, 0);
8582 Cvar_SetValueQuick(&r_damageblur, 0);
8585 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)))
8586 screentexturewidth = screentextureheight = 0;
8587 if (!r_hdr.integer && !r_bloom.integer)
8588 bloomtexturewidth = bloomtextureheight = 0;
8590 // allocate textures as needed
8591 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8593 if (r_bloomstate.texture_screen)
8594 R_FreeTexture(r_bloomstate.texture_screen);
8595 r_bloomstate.texture_screen = NULL;
8596 r_bloomstate.screentexturewidth = screentexturewidth;
8597 r_bloomstate.screentextureheight = screentextureheight;
8598 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8599 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
8601 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8603 if (r_bloomstate.texture_bloom)
8604 R_FreeTexture(r_bloomstate.texture_bloom);
8605 r_bloomstate.texture_bloom = NULL;
8606 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8607 r_bloomstate.bloomtextureheight = bloomtextureheight;
8608 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8609 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8612 // when doing a reduced render (HDR) we want to use a smaller area
8613 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8614 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8615 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8616 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8617 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8619 // set up a texcoord array for the full resolution screen image
8620 // (we have to keep this around to copy back during final render)
8621 r_bloomstate.screentexcoord2f[0] = 0;
8622 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
8623 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
8624 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
8625 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
8626 r_bloomstate.screentexcoord2f[5] = 0;
8627 r_bloomstate.screentexcoord2f[6] = 0;
8628 r_bloomstate.screentexcoord2f[7] = 0;
8630 // set up a texcoord array for the reduced resolution bloom image
8631 // (which will be additive blended over the screen image)
8632 r_bloomstate.bloomtexcoord2f[0] = 0;
8633 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8634 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8635 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8636 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8637 r_bloomstate.bloomtexcoord2f[5] = 0;
8638 r_bloomstate.bloomtexcoord2f[6] = 0;
8639 r_bloomstate.bloomtexcoord2f[7] = 0;
8641 switch(vid.renderpath)
8643 case RENDERPATH_D3D9:
8644 case RENDERPATH_D3D10:
8645 case RENDERPATH_D3D11:
8648 for (i = 0;i < 4;i++)
8650 r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
8651 r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
8652 r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
8653 r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
8659 if (r_hdr.integer || r_bloom.integer)
8661 r_bloomstate.enabled = true;
8662 r_bloomstate.hdr = r_hdr.integer != 0;
8665 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);
8668 void R_Bloom_CopyBloomTexture(float colorscale)
8670 r_refdef.stats.bloom++;
8672 // scale down screen texture to the bloom texture size
8674 R_SetViewport(&r_bloomstate.viewport);
8675 GL_BlendFunc(GL_ONE, GL_ZERO);
8676 GL_Color(colorscale, colorscale, colorscale, 1);
8677 // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8678 switch(vid.renderpath)
8680 case RENDERPATH_GL11:
8681 case RENDERPATH_GL13:
8682 case RENDERPATH_GL20:
8683 case RENDERPATH_CGGL:
8684 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8686 case RENDERPATH_D3D9:
8687 case RENDERPATH_D3D10:
8688 case RENDERPATH_D3D11:
8689 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8692 // TODO: do boxfilter scale-down in shader?
8693 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8694 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8695 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8697 // we now have a bloom image in the framebuffer
8698 // copy it into the bloom image texture for later processing
8699 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);
8700 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8703 void R_Bloom_CopyHDRTexture(void)
8705 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);
8706 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8709 void R_Bloom_MakeTexture(void)
8712 float xoffset, yoffset, r, brighten;
8714 r_refdef.stats.bloom++;
8716 R_ResetViewRendering2D();
8718 // we have a bloom image in the framebuffer
8720 R_SetViewport(&r_bloomstate.viewport);
8722 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8725 r = bound(0, r_bloom_colorexponent.value / x, 1);
8726 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8728 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8729 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8730 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8731 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8733 // copy the vertically blurred bloom view to a texture
8734 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);
8735 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8738 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8739 brighten = r_bloom_brighten.value;
8741 brighten *= r_hdr_range.value;
8742 brighten = sqrt(brighten);
8744 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8745 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8747 for (dir = 0;dir < 2;dir++)
8749 // blend on at multiple vertical offsets to achieve a vertical blur
8750 // TODO: do offset blends using GLSL
8751 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8752 GL_BlendFunc(GL_ONE, GL_ZERO);
8753 for (x = -range;x <= range;x++)
8755 if (!dir){xoffset = 0;yoffset = x;}
8756 else {xoffset = x;yoffset = 0;}
8757 xoffset /= (float)r_bloomstate.bloomtexturewidth;
8758 yoffset /= (float)r_bloomstate.bloomtextureheight;
8759 // compute a texcoord array with the specified x and y offset
8760 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8761 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8762 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8763 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8764 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8765 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8766 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8767 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8768 // this r value looks like a 'dot' particle, fading sharply to
8769 // black at the edges
8770 // (probably not realistic but looks good enough)
8771 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8772 //r = brighten/(range*2+1);
8773 r = brighten / (range * 2 + 1);
8775 r *= (1 - x*x/(float)(range*range));
8776 GL_Color(r, r, r, 1);
8777 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8778 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8779 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8780 GL_BlendFunc(GL_ONE, GL_ONE);
8783 // copy the vertically blurred bloom view to a texture
8784 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);
8785 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8789 void R_HDR_RenderBloomTexture(void)
8791 int oldwidth, oldheight;
8792 float oldcolorscale;
8794 oldcolorscale = r_refdef.view.colorscale;
8795 oldwidth = r_refdef.view.width;
8796 oldheight = r_refdef.view.height;
8797 r_refdef.view.width = r_bloomstate.bloomwidth;
8798 r_refdef.view.height = r_bloomstate.bloomheight;
8800 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
8801 // TODO: add exposure compensation features
8802 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8804 r_refdef.view.showdebug = false;
8805 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8807 R_ResetViewRendering3D();
8809 R_ClearScreen(r_refdef.fogenabled);
8810 if (r_timereport_active)
8811 R_TimeReport("HDRclear");
8814 if (r_timereport_active)
8815 R_TimeReport("visibility");
8817 // only do secondary renders with HDR if r_hdr is 2 or higher
8818 r_waterstate.numwaterplanes = 0;
8819 if (r_waterstate.enabled && r_hdr.integer >= 2)
8820 R_RenderWaterPlanes();
8822 r_refdef.view.showdebug = true;
8824 r_waterstate.numwaterplanes = 0;
8826 R_ResetViewRendering2D();
8828 R_Bloom_CopyHDRTexture();
8829 R_Bloom_MakeTexture();
8831 // restore the view settings
8832 r_refdef.view.width = oldwidth;
8833 r_refdef.view.height = oldheight;
8834 r_refdef.view.colorscale = oldcolorscale;
8836 R_ResetViewRendering3D();
8838 R_ClearScreen(r_refdef.fogenabled);
8839 if (r_timereport_active)
8840 R_TimeReport("viewclear");
8843 static void R_BlendView(void)
8845 unsigned int permutation;
8846 float uservecs[4][4];
8848 switch (vid.renderpath)
8850 case RENDERPATH_GL20:
8851 case RENDERPATH_CGGL:
8852 case RENDERPATH_D3D9:
8853 case RENDERPATH_D3D10:
8854 case RENDERPATH_D3D11:
8856 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8857 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8858 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8859 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8860 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8862 if (r_bloomstate.texture_screen)
8864 // make sure the buffer is available
8865 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8867 R_ResetViewRendering2D();
8869 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8871 // declare variables
8873 static float avgspeed;
8875 speed = VectorLength(cl.movement_velocity);
8877 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8878 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8880 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8881 speed = bound(0, speed, 1);
8882 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8884 // calculate values into a standard alpha
8885 cl.motionbluralpha = 1 - exp(-
8887 (r_motionblur.value * speed / 80)
8889 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8892 max(0.0001, cl.time - cl.oldtime) // fps independent
8895 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8896 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8898 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8900 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8901 GL_Color(1, 1, 1, cl.motionbluralpha);
8902 switch(vid.renderpath)
8904 case RENDERPATH_GL11:
8905 case RENDERPATH_GL13:
8906 case RENDERPATH_GL20:
8907 case RENDERPATH_CGGL:
8908 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8910 case RENDERPATH_D3D9:
8911 case RENDERPATH_D3D10:
8912 case RENDERPATH_D3D11:
8913 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8916 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8917 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8918 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8922 // copy view into the screen texture
8923 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);
8924 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8926 else if (!r_bloomstate.texture_bloom)
8928 // we may still have to do view tint...
8929 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8931 // apply a color tint to the whole view
8932 R_ResetViewRendering2D();
8933 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8934 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8935 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8936 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8937 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8939 break; // no screen processing, no bloom, skip it
8942 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8944 // render simple bloom effect
8945 // copy the screen and shrink it and darken it for the bloom process
8946 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8947 // make the bloom texture
8948 R_Bloom_MakeTexture();
8951 #if _MSC_VER >= 1400
8952 #define sscanf sscanf_s
8954 memset(uservecs, 0, sizeof(uservecs));
8955 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8956 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8957 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8958 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8960 R_ResetViewRendering2D();
8961 GL_Color(1, 1, 1, 1);
8962 GL_BlendFunc(GL_ONE, GL_ZERO);
8964 switch(vid.renderpath)
8966 case RENDERPATH_GL20:
8967 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8968 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8969 if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8970 if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8971 if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8972 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]);
8973 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8974 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]);
8975 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]);
8976 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]);
8977 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]);
8978 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
8979 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8980 if (r_glsl_permutation->loc_BloomColorSubtract >= 0) qglUniform4fARB(r_glsl_permutation->loc_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
8982 case RENDERPATH_CGGL:
8984 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8985 R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8986 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_bloomstate.texture_screen);CHECKCGERROR
8987 if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_bloomstate.texture_bloom );CHECKCGERROR
8988 if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps );CHECKCGERROR
8989 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
8990 if (r_cg_permutation->fp_PixelSize ) cgGLSetParameter2f( r_cg_permutation->fp_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8991 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
8992 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
8993 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
8994 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
8995 if (r_cg_permutation->fp_Saturation ) cgGLSetParameter1f( r_cg_permutation->fp_Saturation , r_glsl_saturation.value);CHECKCGERROR
8996 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8997 if (r_cg_permutation->fp_BloomColorSubtract ) cgGLSetParameter4f(r_cg_permutation->fp_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9000 case RENDERPATH_D3D9:
9002 // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
9003 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9004 R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
9005 R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
9006 R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
9007 R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
9008 hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9009 hlslPSSetParameter2f(D3DPSREGISTER_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9010 hlslPSSetParameter4f(D3DPSREGISTER_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
9011 hlslPSSetParameter4f(D3DPSREGISTER_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
9012 hlslPSSetParameter4f(D3DPSREGISTER_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
9013 hlslPSSetParameter4f(D3DPSREGISTER_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
9014 hlslPSSetParameter1f(D3DPSREGISTER_Saturation , r_glsl_saturation.value);
9015 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
9016 hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9019 case RENDERPATH_D3D10:
9020 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
9022 case RENDERPATH_D3D11:
9023 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
9028 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9029 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9031 case RENDERPATH_GL13:
9032 case RENDERPATH_GL11:
9033 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9035 // apply a color tint to the whole view
9036 R_ResetViewRendering2D();
9037 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9038 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9039 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9040 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9041 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9047 matrix4x4_t r_waterscrollmatrix;
9049 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
9051 if (r_refdef.fog_density)
9053 r_refdef.fogcolor[0] = r_refdef.fog_red;
9054 r_refdef.fogcolor[1] = r_refdef.fog_green;
9055 r_refdef.fogcolor[2] = r_refdef.fog_blue;
9057 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
9058 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
9059 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
9060 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
9064 VectorCopy(r_refdef.fogcolor, fogvec);
9065 // color.rgb *= ContrastBoost * SceneBrightness;
9066 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
9067 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
9068 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
9069 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
9074 void R_UpdateVariables(void)
9078 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
9080 r_refdef.farclip = r_farclip_base.value;
9081 if (r_refdef.scene.worldmodel)
9082 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
9083 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
9085 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
9086 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
9087 r_refdef.polygonfactor = 0;
9088 r_refdef.polygonoffset = 0;
9089 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9090 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9092 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
9093 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
9094 r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
9095 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
9096 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
9097 if (r_showsurfaces.integer)
9099 r_refdef.scene.rtworld = false;
9100 r_refdef.scene.rtworldshadows = false;
9101 r_refdef.scene.rtdlight = false;
9102 r_refdef.scene.rtdlightshadows = false;
9103 r_refdef.lightmapintensity = 0;
9106 if (gamemode == GAME_NEHAHRA)
9108 if (gl_fogenable.integer)
9110 r_refdef.oldgl_fogenable = true;
9111 r_refdef.fog_density = gl_fogdensity.value;
9112 r_refdef.fog_red = gl_fogred.value;
9113 r_refdef.fog_green = gl_foggreen.value;
9114 r_refdef.fog_blue = gl_fogblue.value;
9115 r_refdef.fog_alpha = 1;
9116 r_refdef.fog_start = 0;
9117 r_refdef.fog_end = gl_skyclip.value;
9118 r_refdef.fog_height = 1<<30;
9119 r_refdef.fog_fadedepth = 128;
9121 else if (r_refdef.oldgl_fogenable)
9123 r_refdef.oldgl_fogenable = false;
9124 r_refdef.fog_density = 0;
9125 r_refdef.fog_red = 0;
9126 r_refdef.fog_green = 0;
9127 r_refdef.fog_blue = 0;
9128 r_refdef.fog_alpha = 0;
9129 r_refdef.fog_start = 0;
9130 r_refdef.fog_end = 0;
9131 r_refdef.fog_height = 1<<30;
9132 r_refdef.fog_fadedepth = 128;
9136 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
9137 r_refdef.fog_start = max(0, r_refdef.fog_start);
9138 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
9140 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
9142 if (r_refdef.fog_density && r_drawfog.integer)
9144 r_refdef.fogenabled = true;
9145 // this is the point where the fog reaches 0.9986 alpha, which we
9146 // consider a good enough cutoff point for the texture
9147 // (0.9986 * 256 == 255.6)
9148 if (r_fog_exp2.integer)
9149 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
9151 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
9152 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
9153 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
9154 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
9155 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
9156 R_BuildFogHeightTexture();
9157 // fog color was already set
9158 // update the fog texture
9159 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)
9160 R_BuildFogTexture();
9161 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
9162 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
9165 r_refdef.fogenabled = false;
9167 switch(vid.renderpath)
9169 case RENDERPATH_GL20:
9170 case RENDERPATH_CGGL:
9171 case RENDERPATH_D3D9:
9172 case RENDERPATH_D3D10:
9173 case RENDERPATH_D3D11:
9174 if(v_glslgamma.integer && !vid_gammatables_trivial)
9176 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
9178 // build GLSL gamma texture
9179 #define RAMPWIDTH 256
9180 unsigned short ramp[RAMPWIDTH * 3];
9181 unsigned char rampbgr[RAMPWIDTH][4];
9184 r_texture_gammaramps_serial = vid_gammatables_serial;
9186 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
9187 for(i = 0; i < RAMPWIDTH; ++i)
9189 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9190 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9191 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
9194 if (r_texture_gammaramps)
9196 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
9200 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, -1, NULL);
9206 // remove GLSL gamma texture
9209 case RENDERPATH_GL13:
9210 case RENDERPATH_GL11:
9215 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
9216 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
9222 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
9223 if( scenetype != r_currentscenetype ) {
9224 // store the old scenetype
9225 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
9226 r_currentscenetype = scenetype;
9227 // move in the new scene
9228 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
9237 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
9239 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
9240 if( scenetype == r_currentscenetype ) {
9241 return &r_refdef.scene;
9243 return &r_scenes_store[ scenetype ];
9252 void R_RenderView(void)
9254 if (r_timereport_active)
9255 R_TimeReport("start");
9256 r_textureframe++; // used only by R_GetCurrentTexture
9257 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
9259 if (!r_drawentities.integer)
9260 r_refdef.scene.numentities = 0;
9262 R_AnimCache_ClearCache();
9263 R_FrameData_NewFrame();
9265 if (r_refdef.view.isoverlay)
9267 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
9268 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
9269 R_TimeReport("depthclear");
9271 r_refdef.view.showdebug = false;
9273 r_waterstate.enabled = false;
9274 r_waterstate.numwaterplanes = 0;
9282 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
9283 return; //Host_Error ("R_RenderView: NULL worldmodel");
9285 r_refdef.view.colorscale = r_hdr_scenebrightness.value;
9287 R_RenderView_UpdateViewVectors();
9289 R_Shadow_UpdateWorldLightSelection();
9291 R_Bloom_StartFrame();
9292 R_Water_StartFrame();
9295 if (r_timereport_active)
9296 R_TimeReport("viewsetup");
9298 R_ResetViewRendering3D();
9300 if (r_refdef.view.clear || r_refdef.fogenabled)
9302 R_ClearScreen(r_refdef.fogenabled);
9303 if (r_timereport_active)
9304 R_TimeReport("viewclear");
9306 r_refdef.view.clear = true;
9308 // this produces a bloom texture to be used in R_BlendView() later
9309 if (r_hdr.integer && r_bloomstate.bloomwidth)
9311 R_HDR_RenderBloomTexture();
9312 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
9313 r_textureframe++; // used only by R_GetCurrentTexture
9316 r_refdef.view.showdebug = true;
9319 if (r_timereport_active)
9320 R_TimeReport("visibility");
9322 r_waterstate.numwaterplanes = 0;
9323 if (r_waterstate.enabled)
9324 R_RenderWaterPlanes();
9327 r_waterstate.numwaterplanes = 0;
9330 if (r_timereport_active)
9331 R_TimeReport("blendview");
9333 GL_Scissor(0, 0, vid.width, vid.height);
9334 GL_ScissorTest(false);
9338 void R_RenderWaterPlanes(void)
9340 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
9342 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
9343 if (r_timereport_active)
9344 R_TimeReport("waterworld");
9347 // don't let sound skip if going slow
9348 if (r_refdef.scene.extraupdate)
9351 R_DrawModelsAddWaterPlanes();
9352 if (r_timereport_active)
9353 R_TimeReport("watermodels");
9355 if (r_waterstate.numwaterplanes)
9357 R_Water_ProcessPlanes();
9358 if (r_timereport_active)
9359 R_TimeReport("waterscenes");
9363 extern void R_DrawLightningBeams (void);
9364 extern void VM_CL_AddPolygonsToMeshQueue (void);
9365 extern void R_DrawPortals (void);
9366 extern cvar_t cl_locs_show;
9367 static void R_DrawLocs(void);
9368 static void R_DrawEntityBBoxes(void);
9369 static void R_DrawModelDecals(void);
9370 extern void R_DrawModelShadows(void);
9371 extern void R_DrawModelShadowMaps(void);
9372 extern cvar_t cl_decals_newsystem;
9373 extern qboolean r_shadow_usingdeferredprepass;
9374 void R_RenderScene(void)
9376 qboolean shadowmapping = false;
9378 if (r_timereport_active)
9379 R_TimeReport("beginscene");
9381 r_refdef.stats.renders++;
9385 // don't let sound skip if going slow
9386 if (r_refdef.scene.extraupdate)
9389 R_MeshQueue_BeginScene();
9393 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);
9395 if (r_timereport_active)
9396 R_TimeReport("skystartframe");
9398 if (cl.csqc_vidvars.drawworld)
9400 // don't let sound skip if going slow
9401 if (r_refdef.scene.extraupdate)
9404 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
9406 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
9407 if (r_timereport_active)
9408 R_TimeReport("worldsky");
9411 if (R_DrawBrushModelsSky() && r_timereport_active)
9412 R_TimeReport("bmodelsky");
9414 if (skyrendermasked && skyrenderlater)
9416 // we have to force off the water clipping plane while rendering sky
9420 if (r_timereport_active)
9421 R_TimeReport("sky");
9425 R_AnimCache_CacheVisibleEntities();
9426 if (r_timereport_active)
9427 R_TimeReport("animation");
9429 R_Shadow_PrepareLights();
9430 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
9431 R_Shadow_PrepareModelShadows();
9432 if (r_timereport_active)
9433 R_TimeReport("preparelights");
9435 if (R_Shadow_ShadowMappingEnabled())
9436 shadowmapping = true;
9438 if (r_shadow_usingdeferredprepass)
9439 R_Shadow_DrawPrepass();
9441 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
9443 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
9444 if (r_timereport_active)
9445 R_TimeReport("worlddepth");
9447 if (r_depthfirst.integer >= 2)
9449 R_DrawModelsDepth();
9450 if (r_timereport_active)
9451 R_TimeReport("modeldepth");
9454 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
9456 R_DrawModelShadowMaps();
9457 R_ResetViewRendering3D();
9458 // don't let sound skip if going slow
9459 if (r_refdef.scene.extraupdate)
9463 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
9465 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
9466 if (r_timereport_active)
9467 R_TimeReport("world");
9470 // don't let sound skip if going slow
9471 if (r_refdef.scene.extraupdate)
9475 if (r_timereport_active)
9476 R_TimeReport("models");
9478 // don't let sound skip if going slow
9479 if (r_refdef.scene.extraupdate)
9482 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9484 R_DrawModelShadows();
9485 R_ResetViewRendering3D();
9486 // don't let sound skip if going slow
9487 if (r_refdef.scene.extraupdate)
9491 if (!r_shadow_usingdeferredprepass)
9493 R_Shadow_DrawLights();
9494 if (r_timereport_active)
9495 R_TimeReport("rtlights");
9498 // don't let sound skip if going slow
9499 if (r_refdef.scene.extraupdate)
9502 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9504 R_DrawModelShadows();
9505 R_ResetViewRendering3D();
9506 // don't let sound skip if going slow
9507 if (r_refdef.scene.extraupdate)
9511 if (cl.csqc_vidvars.drawworld)
9513 if (cl_decals_newsystem.integer)
9515 R_DrawModelDecals();
9516 if (r_timereport_active)
9517 R_TimeReport("modeldecals");
9522 if (r_timereport_active)
9523 R_TimeReport("decals");
9527 if (r_timereport_active)
9528 R_TimeReport("particles");
9531 if (r_timereport_active)
9532 R_TimeReport("explosions");
9534 R_DrawLightningBeams();
9535 if (r_timereport_active)
9536 R_TimeReport("lightning");
9539 VM_CL_AddPolygonsToMeshQueue();
9541 if (r_refdef.view.showdebug)
9543 if (cl_locs_show.integer)
9546 if (r_timereport_active)
9547 R_TimeReport("showlocs");
9550 if (r_drawportals.integer)
9553 if (r_timereport_active)
9554 R_TimeReport("portals");
9557 if (r_showbboxes.value > 0)
9559 R_DrawEntityBBoxes();
9560 if (r_timereport_active)
9561 R_TimeReport("bboxes");
9565 R_MeshQueue_RenderTransparent();
9566 if (r_timereport_active)
9567 R_TimeReport("drawtrans");
9569 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))
9571 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9572 if (r_timereport_active)
9573 R_TimeReport("worlddebug");
9574 R_DrawModelsDebug();
9575 if (r_timereport_active)
9576 R_TimeReport("modeldebug");
9579 if (cl.csqc_vidvars.drawworld)
9581 R_Shadow_DrawCoronas();
9582 if (r_timereport_active)
9583 R_TimeReport("coronas");
9586 // don't let sound skip if going slow
9587 if (r_refdef.scene.extraupdate)
9590 R_ResetViewRendering2D();
9593 static const unsigned short bboxelements[36] =
9603 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9606 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9608 RSurf_ActiveWorldEntity();
9610 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9611 GL_DepthMask(false);
9612 GL_DepthRange(0, 1);
9613 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9614 R_Mesh_ResetTextureState();
9616 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9617 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9618 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9619 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9620 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9621 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9622 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9623 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9624 R_FillColors(color4f, 8, cr, cg, cb, ca);
9625 if (r_refdef.fogenabled)
9627 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9629 f1 = RSurf_FogVertex(v);
9631 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9632 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9633 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9636 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
9637 R_Mesh_ResetTextureState();
9638 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9639 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
9642 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9646 prvm_edict_t *edict;
9647 prvm_prog_t *prog_save = prog;
9649 // this function draws bounding boxes of server entities
9653 GL_CullFace(GL_NONE);
9654 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9658 for (i = 0;i < numsurfaces;i++)
9660 edict = PRVM_EDICT_NUM(surfacelist[i]);
9661 switch ((int)edict->fields.server->solid)
9663 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
9664 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
9665 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
9666 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9667 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
9668 default: Vector4Set(color, 0, 0, 0, 0.50);break;
9670 color[3] *= r_showbboxes.value;
9671 color[3] = bound(0, color[3], 1);
9672 GL_DepthTest(!r_showdisabledepthtest.integer);
9673 GL_CullFace(r_refdef.view.cullface_front);
9674 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9680 static void R_DrawEntityBBoxes(void)
9683 prvm_edict_t *edict;
9685 prvm_prog_t *prog_save = prog;
9687 // this function draws bounding boxes of server entities
9693 for (i = 0;i < prog->num_edicts;i++)
9695 edict = PRVM_EDICT_NUM(i);
9696 if (edict->priv.server->free)
9698 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9699 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9701 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9703 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9704 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9710 static const int nomodelelement3i[24] =
9722 static const unsigned short nomodelelement3s[24] =
9734 static const float nomodelvertex3f[6*3] =
9744 static const float nomodelcolor4f[6*4] =
9746 0.0f, 0.0f, 0.5f, 1.0f,
9747 0.0f, 0.0f, 0.5f, 1.0f,
9748 0.0f, 0.5f, 0.0f, 1.0f,
9749 0.0f, 0.5f, 0.0f, 1.0f,
9750 0.5f, 0.0f, 0.0f, 1.0f,
9751 0.5f, 0.0f, 0.0f, 1.0f
9754 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9760 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);
9762 // this is only called once per entity so numsurfaces is always 1, and
9763 // surfacelist is always {0}, so this code does not handle batches
9765 if (rsurface.ent_flags & RENDER_ADDITIVE)
9767 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9768 GL_DepthMask(false);
9770 else if (rsurface.colormod[3] < 1)
9772 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9773 GL_DepthMask(false);
9777 GL_BlendFunc(GL_ONE, GL_ZERO);
9780 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9781 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9782 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9783 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9784 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9785 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9786 for (i = 0, c = color4f;i < 6;i++, c += 4)
9788 c[0] *= rsurface.colormod[0];
9789 c[1] *= rsurface.colormod[1];
9790 c[2] *= rsurface.colormod[2];
9791 c[3] *= rsurface.colormod[3];
9793 if (r_refdef.fogenabled)
9795 for (i = 0, c = color4f;i < 6;i++, c += 4)
9797 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
9799 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9800 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9801 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9804 R_Mesh_ResetTextureState();
9805 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
9806 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
9809 void R_DrawNoModel(entity_render_t *ent)
9812 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9813 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9814 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9816 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9819 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9821 vec3_t right1, right2, diff, normal;
9823 VectorSubtract (org2, org1, normal);
9825 // calculate 'right' vector for start
9826 VectorSubtract (r_refdef.view.origin, org1, diff);
9827 CrossProduct (normal, diff, right1);
9828 VectorNormalize (right1);
9830 // calculate 'right' vector for end
9831 VectorSubtract (r_refdef.view.origin, org2, diff);
9832 CrossProduct (normal, diff, right2);
9833 VectorNormalize (right2);
9835 vert[ 0] = org1[0] + width * right1[0];
9836 vert[ 1] = org1[1] + width * right1[1];
9837 vert[ 2] = org1[2] + width * right1[2];
9838 vert[ 3] = org1[0] - width * right1[0];
9839 vert[ 4] = org1[1] - width * right1[1];
9840 vert[ 5] = org1[2] - width * right1[2];
9841 vert[ 6] = org2[0] - width * right2[0];
9842 vert[ 7] = org2[1] - width * right2[1];
9843 vert[ 8] = org2[2] - width * right2[2];
9844 vert[ 9] = org2[0] + width * right2[0];
9845 vert[10] = org2[1] + width * right2[1];
9846 vert[11] = org2[2] + width * right2[2];
9849 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)
9851 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9852 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9853 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9854 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9855 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9856 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9857 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9858 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9859 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9860 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9861 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9862 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9865 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9870 VectorSet(v, x, y, z);
9871 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9872 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9874 if (i == mesh->numvertices)
9876 if (mesh->numvertices < mesh->maxvertices)
9878 VectorCopy(v, vertex3f);
9879 mesh->numvertices++;
9881 return mesh->numvertices;
9887 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9891 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9892 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9893 e = mesh->element3i + mesh->numtriangles * 3;
9894 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9896 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9897 if (mesh->numtriangles < mesh->maxtriangles)
9902 mesh->numtriangles++;
9904 element[1] = element[2];
9908 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9912 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9913 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9914 e = mesh->element3i + mesh->numtriangles * 3;
9915 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9917 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9918 if (mesh->numtriangles < mesh->maxtriangles)
9923 mesh->numtriangles++;
9925 element[1] = element[2];
9929 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9930 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9932 int planenum, planenum2;
9935 mplane_t *plane, *plane2;
9937 double temppoints[2][256*3];
9938 // figure out how large a bounding box we need to properly compute this brush
9940 for (w = 0;w < numplanes;w++)
9941 maxdist = max(maxdist, fabs(planes[w].dist));
9942 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9943 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9944 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9948 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9949 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9951 if (planenum2 == planenum)
9953 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);
9956 if (tempnumpoints < 3)
9958 // generate elements forming a triangle fan for this polygon
9959 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9963 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)
9965 texturelayer_t *layer;
9966 layer = t->currentlayers + t->currentnumlayers++;
9968 layer->depthmask = depthmask;
9969 layer->blendfunc1 = blendfunc1;
9970 layer->blendfunc2 = blendfunc2;
9971 layer->texture = texture;
9972 layer->texmatrix = *matrix;
9973 layer->color[0] = r;
9974 layer->color[1] = g;
9975 layer->color[2] = b;
9976 layer->color[3] = a;
9979 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
9981 if(parms[0] == 0 && parms[1] == 0)
9983 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9984 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
9989 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9992 index = parms[2] + r_refdef.scene.time * parms[3];
9993 index -= floor(index);
9994 switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
9997 case Q3WAVEFUNC_NONE:
9998 case Q3WAVEFUNC_NOISE:
9999 case Q3WAVEFUNC_COUNT:
10002 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
10003 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
10004 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
10005 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
10006 case Q3WAVEFUNC_TRIANGLE:
10008 f = index - floor(index);
10011 else if (index < 2)
10013 else if (index < 3)
10019 f = parms[0] + parms[1] * f;
10020 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10021 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
10025 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
10030 matrix4x4_t matrix, temp;
10031 switch(tcmod->tcmod)
10033 case Q3TCMOD_COUNT:
10035 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10036 matrix = r_waterscrollmatrix;
10038 matrix = identitymatrix;
10040 case Q3TCMOD_ENTITYTRANSLATE:
10041 // this is used in Q3 to allow the gamecode to control texcoord
10042 // scrolling on the entity, which is not supported in darkplaces yet.
10043 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
10045 case Q3TCMOD_ROTATE:
10046 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
10047 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
10048 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
10050 case Q3TCMOD_SCALE:
10051 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
10053 case Q3TCMOD_SCROLL:
10054 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
10056 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
10057 w = (int) tcmod->parms[0];
10058 h = (int) tcmod->parms[1];
10059 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
10061 idx = (int) floor(f * w * h);
10062 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
10064 case Q3TCMOD_STRETCH:
10065 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
10066 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
10068 case Q3TCMOD_TRANSFORM:
10069 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
10070 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
10071 VectorSet(tcmat + 6, 0 , 0 , 1);
10072 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
10073 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
10075 case Q3TCMOD_TURBULENT:
10076 // this is handled in the RSurf_PrepareVertices function
10077 matrix = identitymatrix;
10081 Matrix4x4_Concat(texmatrix, &matrix, &temp);
10084 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
10086 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
10087 char name[MAX_QPATH];
10088 skinframe_t *skinframe;
10089 unsigned char pixels[296*194];
10090 strlcpy(cache->name, skinname, sizeof(cache->name));
10091 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
10092 if (developer_loading.integer)
10093 Con_Printf("loading %s\n", name);
10094 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
10095 if (!skinframe || !skinframe->base)
10098 fs_offset_t filesize;
10100 f = FS_LoadFile(name, tempmempool, true, &filesize);
10103 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
10104 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
10108 cache->skinframe = skinframe;
10111 texture_t *R_GetCurrentTexture(texture_t *t)
10114 const entity_render_t *ent = rsurface.entity;
10115 dp_model_t *model = ent->model;
10116 q3shaderinfo_layer_tcmod_t *tcmod;
10118 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
10119 return t->currentframe;
10120 t->update_lastrenderframe = r_textureframe;
10121 t->update_lastrenderentity = (void *)ent;
10123 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
10124 t->camera_entity = ent->entitynumber;
10126 t->camera_entity = 0;
10128 // switch to an alternate material if this is a q1bsp animated material
10130 texture_t *texture = t;
10131 int s = rsurface.ent_skinnum;
10132 if ((unsigned int)s >= (unsigned int)model->numskins)
10134 if (model->skinscenes)
10136 if (model->skinscenes[s].framecount > 1)
10137 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
10139 s = model->skinscenes[s].firstframe;
10142 t = t + s * model->num_surfaces;
10145 // use an alternate animation if the entity's frame is not 0,
10146 // and only if the texture has an alternate animation
10147 if (rsurface.ent_alttextures && t->anim_total[1])
10148 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
10150 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
10152 texture->currentframe = t;
10155 // update currentskinframe to be a qw skin or animation frame
10156 if (rsurface.ent_qwskin >= 0)
10158 i = rsurface.ent_qwskin;
10159 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
10161 r_qwskincache_size = cl.maxclients;
10163 Mem_Free(r_qwskincache);
10164 r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
10166 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
10167 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
10168 t->currentskinframe = r_qwskincache[i].skinframe;
10169 if (t->currentskinframe == NULL)
10170 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10172 else if (t->numskinframes >= 2)
10173 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10174 if (t->backgroundnumskinframes >= 2)
10175 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
10177 t->currentmaterialflags = t->basematerialflags;
10178 t->currentalpha = rsurface.colormod[3];
10179 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
10180 t->currentalpha *= r_wateralpha.value;
10181 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
10182 t->currentalpha *= t->r_water_wateralpha;
10183 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
10184 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
10185 if (!(rsurface.ent_flags & RENDER_LIGHT))
10186 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
10187 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
10189 // pick a model lighting mode
10190 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
10191 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
10193 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
10195 if (rsurface.ent_flags & RENDER_ADDITIVE)
10196 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10197 else if (t->currentalpha < 1)
10198 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10199 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
10200 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
10201 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
10202 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
10203 if (t->backgroundnumskinframes)
10204 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
10205 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
10207 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
10208 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
10211 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
10212 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
10213 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
10215 // there is no tcmod
10216 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10218 t->currenttexmatrix = r_waterscrollmatrix;
10219 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
10221 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
10223 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
10224 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
10227 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10228 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
10229 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10230 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
10232 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
10233 if (t->currentskinframe->qpixels)
10234 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
10235 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
10236 if (!t->basetexture)
10237 t->basetexture = r_texture_notexture;
10238 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
10239 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
10240 t->nmaptexture = t->currentskinframe->nmap;
10241 if (!t->nmaptexture)
10242 t->nmaptexture = r_texture_blanknormalmap;
10243 t->glosstexture = r_texture_black;
10244 t->glowtexture = t->currentskinframe->glow;
10245 t->fogtexture = t->currentskinframe->fog;
10246 t->reflectmasktexture = t->currentskinframe->reflect;
10247 if (t->backgroundnumskinframes)
10249 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
10250 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
10251 t->backgroundglosstexture = r_texture_black;
10252 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
10253 if (!t->backgroundnmaptexture)
10254 t->backgroundnmaptexture = r_texture_blanknormalmap;
10258 t->backgroundbasetexture = r_texture_white;
10259 t->backgroundnmaptexture = r_texture_blanknormalmap;
10260 t->backgroundglosstexture = r_texture_black;
10261 t->backgroundglowtexture = NULL;
10263 t->specularpower = r_shadow_glossexponent.value;
10264 // TODO: store reference values for these in the texture?
10265 t->specularscale = 0;
10266 if (r_shadow_gloss.integer > 0)
10268 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
10270 if (r_shadow_glossintensity.value > 0)
10272 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
10273 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
10274 t->specularscale = r_shadow_glossintensity.value;
10277 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
10279 t->glosstexture = r_texture_white;
10280 t->backgroundglosstexture = r_texture_white;
10281 t->specularscale = r_shadow_gloss2intensity.value;
10282 t->specularpower = r_shadow_gloss2exponent.value;
10285 t->specularscale *= t->specularscalemod;
10286 t->specularpower *= t->specularpowermod;
10288 // lightmaps mode looks bad with dlights using actual texturing, so turn
10289 // off the colormap and glossmap, but leave the normalmap on as it still
10290 // accurately represents the shading involved
10291 if (gl_lightmaps.integer)
10293 t->basetexture = r_texture_grey128;
10294 t->pantstexture = r_texture_black;
10295 t->shirttexture = r_texture_black;
10296 t->nmaptexture = r_texture_blanknormalmap;
10297 t->glosstexture = r_texture_black;
10298 t->glowtexture = NULL;
10299 t->fogtexture = NULL;
10300 t->reflectmasktexture = NULL;
10301 t->backgroundbasetexture = NULL;
10302 t->backgroundnmaptexture = r_texture_blanknormalmap;
10303 t->backgroundglosstexture = r_texture_black;
10304 t->backgroundglowtexture = NULL;
10305 t->specularscale = 0;
10306 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
10309 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
10310 VectorClear(t->dlightcolor);
10311 t->currentnumlayers = 0;
10312 if (t->currentmaterialflags & MATERIALFLAG_WALL)
10314 int blendfunc1, blendfunc2;
10315 qboolean depthmask;
10316 if (t->currentmaterialflags & MATERIALFLAG_ADD)
10318 blendfunc1 = GL_SRC_ALPHA;
10319 blendfunc2 = GL_ONE;
10321 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
10323 blendfunc1 = GL_SRC_ALPHA;
10324 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
10326 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10328 blendfunc1 = t->customblendfunc[0];
10329 blendfunc2 = t->customblendfunc[1];
10333 blendfunc1 = GL_ONE;
10334 blendfunc2 = GL_ZERO;
10336 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
10337 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
10339 // fullbright is not affected by r_refdef.lightmapintensity
10340 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]);
10341 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10342 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]);
10343 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10344 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]);
10348 vec3_t ambientcolor;
10350 // set the color tint used for lights affecting this surface
10351 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
10353 // q3bsp has no lightmap updates, so the lightstylevalue that
10354 // would normally be baked into the lightmap must be
10355 // applied to the color
10356 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
10357 if (model->type == mod_brushq3)
10358 colorscale *= r_refdef.scene.rtlightstylevalue[0];
10359 colorscale *= r_refdef.lightmapintensity;
10360 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
10361 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
10362 // basic lit geometry
10363 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]);
10364 // add pants/shirt if needed
10365 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10366 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]);
10367 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10368 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]);
10369 // now add ambient passes if needed
10370 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
10372 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]);
10373 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10374 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]);
10375 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10376 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]);
10379 if (t->glowtexture != NULL && !gl_lightmaps.integer)
10380 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]);
10381 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
10383 // if this is opaque use alpha blend which will darken the earlier
10386 // if this is an alpha blended material, all the earlier passes
10387 // were darkened by fog already, so we only need to add the fog
10388 // color ontop through the fog mask texture
10390 // if this is an additive blended material, all the earlier passes
10391 // were darkened by fog already, and we should not add fog color
10392 // (because the background was not darkened, there is no fog color
10393 // that was lost behind it).
10394 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]);
10398 return t->currentframe;
10401 rsurfacestate_t rsurface;
10403 void R_Mesh_ResizeArrays(int newvertices)
10405 unsigned char *base;
10407 if (rsurface.array_size >= newvertices)
10409 if (rsurface.array_base)
10410 Mem_Free(rsurface.array_base);
10411 rsurface.array_size = (newvertices + 1023) & ~1023;
10413 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
10414 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
10415 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
10416 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
10417 size += rsurface.array_size * sizeof(float[3]);
10418 size += rsurface.array_size * sizeof(float[3]);
10419 size += rsurface.array_size * sizeof(float[3]);
10420 size += rsurface.array_size * sizeof(float[3]);
10421 size += rsurface.array_size * sizeof(float[3]);
10422 size += rsurface.array_size * sizeof(float[3]);
10423 size += rsurface.array_size * sizeof(float[3]);
10424 size += rsurface.array_size * sizeof(float[3]);
10425 size += rsurface.array_size * sizeof(float[4]);
10426 size += rsurface.array_size * sizeof(float[2]);
10427 size += rsurface.array_size * sizeof(float[2]);
10428 size += rsurface.array_size * sizeof(float[4]);
10429 size += rsurface.array_size * sizeof(int[3]);
10430 size += rsurface.array_size * sizeof(unsigned short[3]);
10431 rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
10432 rsurface.array_modelvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
10433 rsurface.array_batchvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
10434 rsurface.array_modelvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
10435 rsurface.array_batchvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
10436 rsurface.array_modelvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10437 rsurface.array_modelsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10438 rsurface.array_modeltvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10439 rsurface.array_modelnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10440 rsurface.array_batchvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10441 rsurface.array_batchsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10442 rsurface.array_batchtvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10443 rsurface.array_batchnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10444 rsurface.array_batchlightmapcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
10445 rsurface.array_batchtexcoordtexture2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
10446 rsurface.array_batchtexcoordlightmap2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
10447 rsurface.array_passcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
10448 rsurface.array_batchelement3i = (int *)base;base += rsurface.array_size * sizeof(int[3]);
10449 rsurface.array_batchelement3s = (unsigned short *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
10452 void RSurf_ActiveWorldEntity(void)
10454 dp_model_t *model = r_refdef.scene.worldmodel;
10455 //if (rsurface.entity == r_refdef.scene.worldentity)
10457 rsurface.entity = r_refdef.scene.worldentity;
10458 rsurface.skeleton = NULL;
10459 memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
10460 rsurface.ent_skinnum = 0;
10461 rsurface.ent_qwskin = -1;
10462 rsurface.ent_shadertime = 0;
10463 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
10464 if (rsurface.array_size < model->surfmesh.num_vertices)
10465 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10466 rsurface.matrix = identitymatrix;
10467 rsurface.inversematrix = identitymatrix;
10468 rsurface.matrixscale = 1;
10469 rsurface.inversematrixscale = 1;
10470 R_EntityMatrix(&identitymatrix);
10471 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
10472 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
10473 rsurface.fograngerecip = r_refdef.fograngerecip;
10474 rsurface.fogheightfade = r_refdef.fogheightfade;
10475 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
10476 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10477 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10478 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10479 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10480 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10481 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10482 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
10483 rsurface.colormod[3] = 1;
10484 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);
10485 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10486 rsurface.frameblend[0].lerp = 1;
10487 rsurface.ent_alttextures = false;
10488 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10489 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10490 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
10491 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10492 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10493 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10494 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10495 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10496 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10497 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10498 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10499 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
10500 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10501 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10502 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
10503 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10504 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10505 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
10506 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10507 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10508 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
10509 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10510 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10511 rsurface.modelelement3i = model->surfmesh.data_element3i;
10512 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10513 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10514 rsurface.modelelement3s = model->surfmesh.data_element3s;
10515 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10516 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10517 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10518 rsurface.modelnumvertices = model->surfmesh.num_vertices;
10519 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10520 rsurface.modelsurfaces = model->data_surfaces;
10521 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10522 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10523 rsurface.modelvertexposition = model->surfmesh.vertexposition;
10524 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
10525 rsurface.modelgeneratedvertex = false;
10526 rsurface.batchgeneratedvertex = false;
10527 rsurface.batchfirstvertex = 0;
10528 rsurface.batchnumvertices = 0;
10529 rsurface.batchfirsttriangle = 0;
10530 rsurface.batchnumtriangles = 0;
10531 rsurface.batchvertex3f = NULL;
10532 rsurface.batchvertex3f_vertexbuffer = NULL;
10533 rsurface.batchvertex3f_bufferoffset = 0;
10534 rsurface.batchsvector3f = NULL;
10535 rsurface.batchsvector3f_vertexbuffer = NULL;
10536 rsurface.batchsvector3f_bufferoffset = 0;
10537 rsurface.batchtvector3f = NULL;
10538 rsurface.batchtvector3f_vertexbuffer = NULL;
10539 rsurface.batchtvector3f_bufferoffset = 0;
10540 rsurface.batchnormal3f = NULL;
10541 rsurface.batchnormal3f_vertexbuffer = NULL;
10542 rsurface.batchnormal3f_bufferoffset = 0;
10543 rsurface.batchlightmapcolor4f = NULL;
10544 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10545 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10546 rsurface.batchtexcoordtexture2f = NULL;
10547 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10548 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10549 rsurface.batchtexcoordlightmap2f = NULL;
10550 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10551 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10552 rsurface.batchvertexmesh = NULL;
10553 rsurface.batchvertexmeshbuffer = NULL;
10554 rsurface.batchvertexposition = NULL;
10555 rsurface.batchvertexpositionbuffer = NULL;
10556 rsurface.batchelement3i = NULL;
10557 rsurface.batchelement3i_indexbuffer = NULL;
10558 rsurface.batchelement3i_bufferoffset = 0;
10559 rsurface.batchelement3s = NULL;
10560 rsurface.batchelement3s_indexbuffer = NULL;
10561 rsurface.batchelement3s_bufferoffset = 0;
10562 rsurface.passcolor4f = NULL;
10563 rsurface.passcolor4f_vertexbuffer = NULL;
10564 rsurface.passcolor4f_bufferoffset = 0;
10567 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
10569 dp_model_t *model = ent->model;
10570 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
10572 rsurface.entity = (entity_render_t *)ent;
10573 rsurface.skeleton = ent->skeleton;
10574 memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
10575 rsurface.ent_skinnum = ent->skinnum;
10576 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;
10577 rsurface.ent_shadertime = ent->shadertime;
10578 rsurface.ent_flags = ent->flags;
10579 if (rsurface.array_size < model->surfmesh.num_vertices)
10580 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10581 rsurface.matrix = ent->matrix;
10582 rsurface.inversematrix = ent->inversematrix;
10583 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10584 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10585 R_EntityMatrix(&rsurface.matrix);
10586 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10587 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10588 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10589 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10590 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10591 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10592 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10593 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10594 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10595 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10596 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10597 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10598 rsurface.colormod[3] = ent->alpha;
10599 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10600 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10601 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10602 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10603 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10604 if (ent->model->brush.submodel && !prepass)
10606 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10607 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10609 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10611 if (ent->animcache_vertex3f && !r_framedata_failed)
10613 rsurface.modelvertex3f = ent->animcache_vertex3f;
10614 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10615 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10616 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10617 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
10618 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
10619 rsurface.modelvertexposition = ent->animcache_vertexposition;
10620 rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
10622 else if (wanttangents)
10624 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10625 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10626 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10627 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10628 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
10629 rsurface.modelvertexmesh = NULL;
10630 rsurface.modelvertexmeshbuffer = NULL;
10631 rsurface.modelvertexposition = NULL;
10632 rsurface.modelvertexpositionbuffer = NULL;
10634 else if (wantnormals)
10636 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10637 rsurface.modelsvector3f = NULL;
10638 rsurface.modeltvector3f = NULL;
10639 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10640 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
10641 rsurface.modelvertexmesh = NULL;
10642 rsurface.modelvertexmeshbuffer = NULL;
10643 rsurface.modelvertexposition = NULL;
10644 rsurface.modelvertexpositionbuffer = NULL;
10648 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10649 rsurface.modelsvector3f = NULL;
10650 rsurface.modeltvector3f = NULL;
10651 rsurface.modelnormal3f = NULL;
10652 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
10653 rsurface.modelvertexmesh = NULL;
10654 rsurface.modelvertexmeshbuffer = NULL;
10655 rsurface.modelvertexposition = NULL;
10656 rsurface.modelvertexpositionbuffer = NULL;
10658 rsurface.modelvertex3f_vertexbuffer = 0;
10659 rsurface.modelvertex3f_bufferoffset = 0;
10660 rsurface.modelsvector3f_vertexbuffer = 0;
10661 rsurface.modelsvector3f_bufferoffset = 0;
10662 rsurface.modeltvector3f_vertexbuffer = 0;
10663 rsurface.modeltvector3f_bufferoffset = 0;
10664 rsurface.modelnormal3f_vertexbuffer = 0;
10665 rsurface.modelnormal3f_bufferoffset = 0;
10666 rsurface.modelgeneratedvertex = true;
10670 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
10671 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10672 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10673 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10674 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10675 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10676 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10677 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10678 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10679 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
10680 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10681 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10682 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10683 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10684 rsurface.modelvertexposition = model->surfmesh.vertexposition;
10685 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
10686 rsurface.modelgeneratedvertex = false;
10688 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
10689 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10690 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10691 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
10692 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10693 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10694 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
10695 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10696 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10697 rsurface.modelelement3i = model->surfmesh.data_element3i;
10698 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10699 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10700 rsurface.modelelement3s = model->surfmesh.data_element3s;
10701 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10702 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10703 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10704 rsurface.modelnumvertices = model->surfmesh.num_vertices;
10705 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10706 rsurface.modelsurfaces = model->data_surfaces;
10707 rsurface.batchgeneratedvertex = false;
10708 rsurface.batchfirstvertex = 0;
10709 rsurface.batchnumvertices = 0;
10710 rsurface.batchfirsttriangle = 0;
10711 rsurface.batchnumtriangles = 0;
10712 rsurface.batchvertex3f = NULL;
10713 rsurface.batchvertex3f_vertexbuffer = NULL;
10714 rsurface.batchvertex3f_bufferoffset = 0;
10715 rsurface.batchsvector3f = NULL;
10716 rsurface.batchsvector3f_vertexbuffer = NULL;
10717 rsurface.batchsvector3f_bufferoffset = 0;
10718 rsurface.batchtvector3f = NULL;
10719 rsurface.batchtvector3f_vertexbuffer = NULL;
10720 rsurface.batchtvector3f_bufferoffset = 0;
10721 rsurface.batchnormal3f = NULL;
10722 rsurface.batchnormal3f_vertexbuffer = NULL;
10723 rsurface.batchnormal3f_bufferoffset = 0;
10724 rsurface.batchlightmapcolor4f = NULL;
10725 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10726 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10727 rsurface.batchtexcoordtexture2f = NULL;
10728 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10729 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10730 rsurface.batchtexcoordlightmap2f = NULL;
10731 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10732 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10733 rsurface.batchvertexmesh = NULL;
10734 rsurface.batchvertexmeshbuffer = NULL;
10735 rsurface.batchvertexposition = NULL;
10736 rsurface.batchvertexpositionbuffer = NULL;
10737 rsurface.batchelement3i = NULL;
10738 rsurface.batchelement3i_indexbuffer = NULL;
10739 rsurface.batchelement3i_bufferoffset = 0;
10740 rsurface.batchelement3s = NULL;
10741 rsurface.batchelement3s_indexbuffer = NULL;
10742 rsurface.batchelement3s_bufferoffset = 0;
10743 rsurface.passcolor4f = NULL;
10744 rsurface.passcolor4f_vertexbuffer = NULL;
10745 rsurface.passcolor4f_bufferoffset = 0;
10748 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)
10752 rsurface.entity = r_refdef.scene.worldentity;
10753 rsurface.skeleton = NULL;
10754 rsurface.ent_skinnum = 0;
10755 rsurface.ent_qwskin = -1;
10756 rsurface.ent_shadertime = shadertime;
10757 rsurface.ent_flags = entflags;
10758 rsurface.modelnumvertices = numvertices;
10759 rsurface.modelnumtriangles = numtriangles;
10760 if (rsurface.array_size < rsurface.modelnumvertices)
10761 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
10762 rsurface.matrix = *matrix;
10763 rsurface.inversematrix = *inversematrix;
10764 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10765 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10766 R_EntityMatrix(&rsurface.matrix);
10767 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10768 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10769 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10770 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10771 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10772 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10773 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10774 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10775 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10776 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10777 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10778 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10779 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);
10780 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10781 rsurface.frameblend[0].lerp = 1;
10782 rsurface.ent_alttextures = false;
10783 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10784 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10787 rsurface.modelvertex3f = vertex3f;
10788 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
10789 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
10790 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10792 else if (wantnormals)
10794 rsurface.modelvertex3f = vertex3f;
10795 rsurface.modelsvector3f = NULL;
10796 rsurface.modeltvector3f = NULL;
10797 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10801 rsurface.modelvertex3f = vertex3f;
10802 rsurface.modelsvector3f = NULL;
10803 rsurface.modeltvector3f = NULL;
10804 rsurface.modelnormal3f = NULL;
10806 rsurface.modelvertexmesh = NULL;
10807 rsurface.modelvertexmeshbuffer = NULL;
10808 rsurface.modelvertexposition = NULL;
10809 rsurface.modelvertexpositionbuffer = NULL;
10810 rsurface.modelvertex3f_vertexbuffer = 0;
10811 rsurface.modelvertex3f_bufferoffset = 0;
10812 rsurface.modelsvector3f_vertexbuffer = 0;
10813 rsurface.modelsvector3f_bufferoffset = 0;
10814 rsurface.modeltvector3f_vertexbuffer = 0;
10815 rsurface.modeltvector3f_bufferoffset = 0;
10816 rsurface.modelnormal3f_vertexbuffer = 0;
10817 rsurface.modelnormal3f_bufferoffset = 0;
10818 rsurface.modelgeneratedvertex = true;
10819 rsurface.modellightmapcolor4f = color4f;
10820 rsurface.modellightmapcolor4f_vertexbuffer = 0;
10821 rsurface.modellightmapcolor4f_bufferoffset = 0;
10822 rsurface.modeltexcoordtexture2f = texcoord2f;
10823 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
10824 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10825 rsurface.modeltexcoordlightmap2f = NULL;
10826 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
10827 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10828 rsurface.modelelement3i = element3i;
10829 rsurface.modelelement3i_indexbuffer = NULL;
10830 rsurface.modelelement3i_bufferoffset = 0;
10831 rsurface.modelelement3s = element3s;
10832 rsurface.modelelement3s_indexbuffer = NULL;
10833 rsurface.modelelement3s_bufferoffset = 0;
10834 rsurface.modellightmapoffsets = NULL;
10835 rsurface.modelsurfaces = NULL;
10836 rsurface.batchgeneratedvertex = false;
10837 rsurface.batchfirstvertex = 0;
10838 rsurface.batchnumvertices = 0;
10839 rsurface.batchfirsttriangle = 0;
10840 rsurface.batchnumtriangles = 0;
10841 rsurface.batchvertex3f = NULL;
10842 rsurface.batchvertex3f_vertexbuffer = NULL;
10843 rsurface.batchvertex3f_bufferoffset = 0;
10844 rsurface.batchsvector3f = NULL;
10845 rsurface.batchsvector3f_vertexbuffer = NULL;
10846 rsurface.batchsvector3f_bufferoffset = 0;
10847 rsurface.batchtvector3f = NULL;
10848 rsurface.batchtvector3f_vertexbuffer = NULL;
10849 rsurface.batchtvector3f_bufferoffset = 0;
10850 rsurface.batchnormal3f = NULL;
10851 rsurface.batchnormal3f_vertexbuffer = NULL;
10852 rsurface.batchnormal3f_bufferoffset = 0;
10853 rsurface.batchlightmapcolor4f = NULL;
10854 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10855 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10856 rsurface.batchtexcoordtexture2f = NULL;
10857 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10858 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10859 rsurface.batchtexcoordlightmap2f = NULL;
10860 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10861 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10862 rsurface.batchvertexmesh = NULL;
10863 rsurface.batchvertexmeshbuffer = NULL;
10864 rsurface.batchvertexposition = NULL;
10865 rsurface.batchvertexpositionbuffer = NULL;
10866 rsurface.batchelement3i = NULL;
10867 rsurface.batchelement3i_indexbuffer = NULL;
10868 rsurface.batchelement3i_bufferoffset = 0;
10869 rsurface.batchelement3s = NULL;
10870 rsurface.batchelement3s_indexbuffer = NULL;
10871 rsurface.batchelement3s_bufferoffset = 0;
10872 rsurface.passcolor4f = NULL;
10873 rsurface.passcolor4f_vertexbuffer = NULL;
10874 rsurface.passcolor4f_bufferoffset = 0;
10876 if (rsurface.modelnumvertices && rsurface.modelelement3i)
10878 if ((wantnormals || wanttangents) && !normal3f)
10880 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10881 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10883 if (wanttangents && !svector3f)
10885 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);
10886 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10887 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10891 // now convert arrays into vertexmesh structs
10892 for (i = 0;i < numvertices;i++)
10894 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
10895 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
10896 if (rsurface.modelsvector3f)
10897 VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
10898 if (rsurface.modeltvector3f)
10899 VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
10900 if (rsurface.modelnormal3f)
10901 VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
10902 if (rsurface.modellightmapcolor4f)
10903 Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
10904 if (rsurface.modeltexcoordtexture2f)
10905 Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
10906 if (rsurface.modeltexcoordlightmap2f)
10907 Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
10911 float RSurf_FogPoint(const float *v)
10913 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10914 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10915 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10916 float FogHeightFade = r_refdef.fogheightfade;
10918 unsigned int fogmasktableindex;
10919 if (r_refdef.fogplaneviewabove)
10920 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10922 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10923 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10924 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10927 float RSurf_FogVertex(const float *v)
10929 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10930 float FogPlaneViewDist = rsurface.fogplaneviewdist;
10931 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10932 float FogHeightFade = rsurface.fogheightfade;
10934 unsigned int fogmasktableindex;
10935 if (r_refdef.fogplaneviewabove)
10936 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10938 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10939 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10940 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10943 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10946 for (i = 0;i < numelements;i++)
10947 outelement3i[i] = inelement3i[i] + adjust;
10950 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10951 extern cvar_t gl_vbo;
10952 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10960 int surfacefirsttriangle;
10961 int surfacenumtriangles;
10962 int surfacefirstvertex;
10963 int surfaceendvertex;
10964 int surfacenumvertices;
10965 int surfaceadjustvertex;
10969 qboolean dynamicvertex;
10973 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10974 float waveparms[4];
10975 q3shaderinfo_deform_t *deform;
10976 const msurface_t *surface, *firstsurface;
10977 r_vertexposition_t *vertexposition;
10978 r_vertexmesh_t *vertexmesh;
10979 if (!texturenumsurfaces)
10981 // find vertex range of this surface batch
10983 firstsurface = texturesurfacelist[0];
10984 firsttriangle = firstsurface->num_firsttriangle;
10986 firstvertex = endvertex = firstsurface->num_firstvertex;
10987 for (i = 0;i < texturenumsurfaces;i++)
10989 surface = texturesurfacelist[i];
10990 if (surface != firstsurface + i)
10992 surfacefirstvertex = surface->num_firstvertex;
10993 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10994 surfacenumtriangles = surface->num_triangles;
10995 if (firstvertex > surfacefirstvertex)
10996 firstvertex = surfacefirstvertex;
10997 if (endvertex < surfaceendvertex)
10998 endvertex = surfaceendvertex;
10999 numtriangles += surfacenumtriangles;
11004 // we now know the vertex range used, and if there are any gaps in it
11005 rsurface.batchfirstvertex = firstvertex;
11006 rsurface.batchnumvertices = endvertex - firstvertex;
11007 rsurface.batchfirsttriangle = firsttriangle;
11008 rsurface.batchnumtriangles = numtriangles;
11010 // this variable holds flags for which properties have been updated that
11011 // may require regenerating vertexmesh or vertexposition arrays...
11014 // check if any dynamic vertex processing must occur
11015 dynamicvertex = false;
11017 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11018 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
11019 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11021 switch (deform->deform)
11024 case Q3DEFORM_PROJECTIONSHADOW:
11025 case Q3DEFORM_TEXT0:
11026 case Q3DEFORM_TEXT1:
11027 case Q3DEFORM_TEXT2:
11028 case Q3DEFORM_TEXT3:
11029 case Q3DEFORM_TEXT4:
11030 case Q3DEFORM_TEXT5:
11031 case Q3DEFORM_TEXT6:
11032 case Q3DEFORM_TEXT7:
11033 case Q3DEFORM_NONE:
11035 case Q3DEFORM_AUTOSPRITE:
11036 dynamicvertex = true;
11037 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11038 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11040 case Q3DEFORM_AUTOSPRITE2:
11041 dynamicvertex = true;
11042 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11043 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11045 case Q3DEFORM_NORMAL:
11046 dynamicvertex = true;
11047 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11048 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11050 case Q3DEFORM_WAVE:
11051 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11052 break; // if wavefunc is a nop, ignore this transform
11053 dynamicvertex = true;
11054 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11055 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11057 case Q3DEFORM_BULGE:
11058 dynamicvertex = true;
11059 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11060 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11062 case Q3DEFORM_MOVE:
11063 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11064 break; // if wavefunc is a nop, ignore this transform
11065 dynamicvertex = true;
11066 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11067 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
11071 switch(rsurface.texture->tcgen.tcgen)
11074 case Q3TCGEN_TEXTURE:
11076 case Q3TCGEN_LIGHTMAP:
11077 dynamicvertex = true;
11078 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
11079 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
11081 case Q3TCGEN_VECTOR:
11082 dynamicvertex = true;
11083 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11084 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11086 case Q3TCGEN_ENVIRONMENT:
11087 dynamicvertex = true;
11088 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
11089 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11092 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11094 dynamicvertex = true;
11095 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11096 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11099 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11101 dynamicvertex = true;
11102 batchneed |= BATCHNEED_NOGAPS;
11103 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
11106 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11108 dynamicvertex = true;
11109 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11110 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
11113 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
11115 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
11116 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
11117 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
11118 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
11119 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
11120 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
11121 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
11124 // when the model data has no vertex buffer (dynamic mesh), we need to
11126 if (!rsurface.modelvertexmeshbuffer || (!gl_vbo.integer && !vid.forcevbo))
11127 batchneed |= BATCHNEED_NOGAPS;
11129 // if needsupdate, we have to do a dynamic vertex batch for sure
11130 if (needsupdate & batchneed)
11131 dynamicvertex = true;
11133 // see if we need to build vertexmesh from arrays
11134 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11135 dynamicvertex = true;
11137 // see if we need to build vertexposition from arrays
11138 if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
11139 dynamicvertex = true;
11141 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
11142 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
11143 dynamicvertex = true;
11145 // if there is a chance of animated vertex colors, it's a dynamic batch
11146 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11147 dynamicvertex = true;
11149 rsurface.batchvertex3f = rsurface.modelvertex3f;
11150 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
11151 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
11152 rsurface.batchsvector3f = rsurface.modelsvector3f;
11153 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
11154 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
11155 rsurface.batchtvector3f = rsurface.modeltvector3f;
11156 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
11157 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
11158 rsurface.batchnormal3f = rsurface.modelnormal3f;
11159 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
11160 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
11161 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
11162 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
11163 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11164 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
11165 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
11166 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
11167 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
11168 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
11169 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
11170 rsurface.batchvertexposition = rsurface.modelvertexposition;
11171 rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
11172 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
11173 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
11174 rsurface.batchelement3i = rsurface.modelelement3i;
11175 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
11176 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
11177 rsurface.batchelement3s = rsurface.modelelement3s;
11178 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
11179 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
11181 // if any dynamic vertex processing has to occur in software, we copy the
11182 // entire surface list together before processing to rebase the vertices
11183 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
11185 // if any gaps exist and we do not have a static vertex buffer, we have to
11186 // copy the surface list together to avoid wasting upload bandwidth on the
11187 // vertices in the gaps.
11189 // if gaps exist and we have a static vertex buffer, we still have to
11190 // combine the index buffer ranges into one dynamic index buffer.
11192 // in all cases we end up with data that can be drawn in one call.
11194 if (!dynamicvertex)
11196 // static vertex data, just set pointers...
11197 rsurface.batchgeneratedvertex = false;
11198 // if there are gaps, we want to build a combined index buffer,
11199 // otherwise use the original static buffer with an appropriate offset
11204 for (i = 0;i < texturenumsurfaces;i++)
11206 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11207 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11208 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
11209 numtriangles += surfacenumtriangles;
11211 rsurface.batchelement3i = rsurface.array_batchelement3i;
11212 rsurface.batchelement3i_indexbuffer = NULL;
11213 rsurface.batchelement3i_bufferoffset = 0;
11214 rsurface.batchelement3s = NULL;
11215 rsurface.batchelement3s_indexbuffer = NULL;
11216 rsurface.batchelement3s_bufferoffset = 0;
11217 if (endvertex <= 65536)
11219 rsurface.batchelement3s = rsurface.array_batchelement3s;
11220 for (i = 0;i < numtriangles*3;i++)
11221 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
11223 rsurface.batchfirsttriangle = firsttriangle;
11224 rsurface.batchnumtriangles = numtriangles;
11229 // something needs software processing, do it for real...
11230 // we only directly handle interleaved array data in this case...
11231 rsurface.batchgeneratedvertex = true;
11233 // now copy the vertex data into a combined array and make an index array
11234 // (this is what Quake3 does all the time)
11235 //if (gaps || rsurface.batchfirstvertex)
11237 rsurface.batchvertexposition = NULL;
11238 rsurface.batchvertexpositionbuffer = NULL;
11239 rsurface.batchvertexmesh = NULL;
11240 rsurface.batchvertexmeshbuffer = NULL;
11241 rsurface.batchvertex3f = NULL;
11242 rsurface.batchvertex3f_vertexbuffer = NULL;
11243 rsurface.batchvertex3f_bufferoffset = 0;
11244 rsurface.batchsvector3f = NULL;
11245 rsurface.batchsvector3f_vertexbuffer = NULL;
11246 rsurface.batchsvector3f_bufferoffset = 0;
11247 rsurface.batchtvector3f = NULL;
11248 rsurface.batchtvector3f_vertexbuffer = NULL;
11249 rsurface.batchtvector3f_bufferoffset = 0;
11250 rsurface.batchnormal3f = NULL;
11251 rsurface.batchnormal3f_vertexbuffer = NULL;
11252 rsurface.batchnormal3f_bufferoffset = 0;
11253 rsurface.batchlightmapcolor4f = NULL;
11254 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11255 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11256 rsurface.batchtexcoordtexture2f = NULL;
11257 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11258 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11259 rsurface.batchtexcoordlightmap2f = NULL;
11260 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
11261 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11262 rsurface.batchelement3i = rsurface.array_batchelement3i;
11263 rsurface.batchelement3i_indexbuffer = NULL;
11264 rsurface.batchelement3i_bufferoffset = 0;
11265 rsurface.batchelement3s = NULL;
11266 rsurface.batchelement3s_indexbuffer = NULL;
11267 rsurface.batchelement3s_bufferoffset = 0;
11268 // we'll only be setting up certain arrays as needed
11269 if (batchneed & BATCHNEED_VERTEXPOSITION)
11270 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11271 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11272 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11273 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11274 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11275 if (batchneed & BATCHNEED_ARRAY_NORMAL)
11276 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11277 if (batchneed & BATCHNEED_ARRAY_VECTOR)
11279 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11280 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11282 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
11283 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
11284 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
11285 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11286 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
11287 rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
11290 for (i = 0;i < texturenumsurfaces;i++)
11292 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
11293 surfacenumvertices = texturesurfacelist[i]->num_vertices;
11294 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11295 surfaceadjustvertex = numvertices - surfacefirstvertex;
11296 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11297 // copy only the data requested
11298 if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
11299 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
11300 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
11301 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
11302 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
11304 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11305 memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11306 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
11307 memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11308 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
11310 memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11311 memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11313 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
11314 memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
11315 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
11316 memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11317 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
11318 memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11320 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
11321 numvertices += surfacenumvertices;
11322 numtriangles += surfacenumtriangles;
11325 // generate a 16bit index array as well if possible
11326 // (in general, dynamic batches fit)
11327 if (numvertices <= 65536)
11329 rsurface.batchelement3s = rsurface.array_batchelement3s;
11330 for (i = 0;i < numtriangles*3;i++)
11331 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
11334 // since we've copied everything, the batch now starts at 0
11335 rsurface.batchfirstvertex = 0;
11336 rsurface.batchnumvertices = numvertices;
11337 rsurface.batchfirsttriangle = 0;
11338 rsurface.batchnumtriangles = numtriangles;
11341 // q1bsp surfaces rendered in vertex color mode have to have colors
11342 // calculated based on lightstyles
11343 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11345 // generate color arrays for the surfaces in this list
11349 const int *offsets;
11350 const unsigned char *lm;
11352 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
11353 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11354 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11355 for (i = 0;i < texturenumsurfaces;i++)
11357 surface = texturesurfacelist[i];
11358 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
11359 surfacenumvertices = surface->num_vertices;
11360 if (surface->lightmapinfo->samples)
11362 for (j = 0;j < surfacenumvertices;j++)
11364 lm = surface->lightmapinfo->samples + offsets[j];
11365 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
11366 VectorScale(lm, scale, c);
11367 if (surface->lightmapinfo->styles[1] != 255)
11369 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11371 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
11372 VectorMA(c, scale, lm, c);
11373 if (surface->lightmapinfo->styles[2] != 255)
11376 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
11377 VectorMA(c, scale, lm, c);
11378 if (surface->lightmapinfo->styles[3] != 255)
11381 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
11382 VectorMA(c, scale, lm, c);
11389 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);
11395 for (j = 0;j < surfacenumvertices;j++)
11397 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
11404 // if vertices are deformed (sprite flares and things in maps, possibly
11405 // water waves, bulges and other deformations), modify the copied vertices
11407 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11409 switch (deform->deform)
11412 case Q3DEFORM_PROJECTIONSHADOW:
11413 case Q3DEFORM_TEXT0:
11414 case Q3DEFORM_TEXT1:
11415 case Q3DEFORM_TEXT2:
11416 case Q3DEFORM_TEXT3:
11417 case Q3DEFORM_TEXT4:
11418 case Q3DEFORM_TEXT5:
11419 case Q3DEFORM_TEXT6:
11420 case Q3DEFORM_TEXT7:
11421 case Q3DEFORM_NONE:
11423 case Q3DEFORM_AUTOSPRITE:
11424 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11425 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11426 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11427 VectorNormalize(newforward);
11428 VectorNormalize(newright);
11429 VectorNormalize(newup);
11430 // a single autosprite surface can contain multiple sprites...
11431 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
11433 VectorClear(center);
11434 for (i = 0;i < 4;i++)
11435 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11436 VectorScale(center, 0.25f, center);
11437 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
11438 VectorCopy(rsurface.batchsvector3f + 3*j, right);
11439 VectorCopy(rsurface.batchtvector3f + 3*j, up);
11440 for (i = 0;i < 4;i++)
11442 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
11443 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
11446 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11447 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);
11448 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11449 rsurface.batchvertex3f_vertexbuffer = NULL;
11450 rsurface.batchvertex3f_bufferoffset = 0;
11451 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11452 rsurface.batchsvector3f_vertexbuffer = NULL;
11453 rsurface.batchsvector3f_bufferoffset = 0;
11454 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11455 rsurface.batchtvector3f_vertexbuffer = NULL;
11456 rsurface.batchtvector3f_bufferoffset = 0;
11457 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11458 rsurface.batchnormal3f_vertexbuffer = NULL;
11459 rsurface.batchnormal3f_bufferoffset = 0;
11461 case Q3DEFORM_AUTOSPRITE2:
11462 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11463 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11464 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11465 VectorNormalize(newforward);
11466 VectorNormalize(newright);
11467 VectorNormalize(newup);
11469 const float *v1, *v2;
11479 memset(shortest, 0, sizeof(shortest));
11480 // a single autosprite surface can contain multiple sprites...
11481 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
11483 VectorClear(center);
11484 for (i = 0;i < 4;i++)
11485 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11486 VectorScale(center, 0.25f, center);
11487 // find the two shortest edges, then use them to define the
11488 // axis vectors for rotating around the central axis
11489 for (i = 0;i < 6;i++)
11491 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
11492 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
11493 l = VectorDistance2(v1, v2);
11494 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
11495 if (v1[2] != v2[2])
11496 l += (1.0f / 1024.0f);
11497 if (shortest[0].length2 > l || i == 0)
11499 shortest[1] = shortest[0];
11500 shortest[0].length2 = l;
11501 shortest[0].v1 = v1;
11502 shortest[0].v2 = v2;
11504 else if (shortest[1].length2 > l || i == 1)
11506 shortest[1].length2 = l;
11507 shortest[1].v1 = v1;
11508 shortest[1].v2 = v2;
11511 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
11512 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
11513 // this calculates the right vector from the shortest edge
11514 // and the up vector from the edge midpoints
11515 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
11516 VectorNormalize(right);
11517 VectorSubtract(end, start, up);
11518 VectorNormalize(up);
11519 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
11520 VectorSubtract(rsurface.localvieworigin, center, forward);
11521 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
11522 VectorNegate(forward, forward);
11523 VectorReflect(forward, 0, up, forward);
11524 VectorNormalize(forward);
11525 CrossProduct(up, forward, newright);
11526 VectorNormalize(newright);
11527 // rotate the quad around the up axis vector, this is made
11528 // especially easy by the fact we know the quad is flat,
11529 // so we only have to subtract the center position and
11530 // measure distance along the right vector, and then
11531 // multiply that by the newright vector and add back the
11533 // we also need to subtract the old position to undo the
11534 // displacement from the center, which we do with a
11535 // DotProduct, the subtraction/addition of center is also
11536 // optimized into DotProducts here
11537 l = DotProduct(right, center);
11538 for (i = 0;i < 4;i++)
11540 v1 = rsurface.batchvertex3f + 3*(j+i);
11541 f = DotProduct(right, v1) - l;
11542 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
11546 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11547 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);
11548 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11549 rsurface.batchvertex3f_vertexbuffer = NULL;
11550 rsurface.batchvertex3f_bufferoffset = 0;
11551 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11552 rsurface.batchsvector3f_vertexbuffer = NULL;
11553 rsurface.batchsvector3f_bufferoffset = 0;
11554 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11555 rsurface.batchtvector3f_vertexbuffer = NULL;
11556 rsurface.batchtvector3f_bufferoffset = 0;
11557 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11558 rsurface.batchnormal3f_vertexbuffer = NULL;
11559 rsurface.batchnormal3f_bufferoffset = 0;
11561 case Q3DEFORM_NORMAL:
11562 // deform the normals to make reflections wavey
11563 for (j = 0;j < rsurface.batchnumvertices;j++)
11566 float *normal = rsurface.array_batchnormal3f + 3*j;
11567 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
11568 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11569 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]);
11570 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]);
11571 VectorNormalize(normal);
11573 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);
11574 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11575 rsurface.batchsvector3f_vertexbuffer = NULL;
11576 rsurface.batchsvector3f_bufferoffset = 0;
11577 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11578 rsurface.batchtvector3f_vertexbuffer = NULL;
11579 rsurface.batchtvector3f_bufferoffset = 0;
11580 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11581 rsurface.batchnormal3f_vertexbuffer = NULL;
11582 rsurface.batchnormal3f_bufferoffset = 0;
11584 case Q3DEFORM_WAVE:
11585 // deform vertex array to make wavey water and flags and such
11586 waveparms[0] = deform->waveparms[0];
11587 waveparms[1] = deform->waveparms[1];
11588 waveparms[2] = deform->waveparms[2];
11589 waveparms[3] = deform->waveparms[3];
11590 if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
11591 break; // if wavefunc is a nop, don't make a dynamic vertex array
11592 // this is how a divisor of vertex influence on deformation
11593 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
11594 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11595 for (j = 0;j < rsurface.batchnumvertices;j++)
11597 // if the wavefunc depends on time, evaluate it per-vertex
11600 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
11601 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11603 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
11605 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11606 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);
11607 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11608 rsurface.batchvertex3f_vertexbuffer = NULL;
11609 rsurface.batchvertex3f_bufferoffset = 0;
11610 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11611 rsurface.batchsvector3f_vertexbuffer = NULL;
11612 rsurface.batchsvector3f_bufferoffset = 0;
11613 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11614 rsurface.batchtvector3f_vertexbuffer = NULL;
11615 rsurface.batchtvector3f_bufferoffset = 0;
11616 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11617 rsurface.batchnormal3f_vertexbuffer = NULL;
11618 rsurface.batchnormal3f_bufferoffset = 0;
11620 case Q3DEFORM_BULGE:
11621 // deform vertex array to make the surface have moving bulges
11622 for (j = 0;j < rsurface.batchnumvertices;j++)
11624 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
11625 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
11627 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11628 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);
11629 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11630 rsurface.batchvertex3f_vertexbuffer = NULL;
11631 rsurface.batchvertex3f_bufferoffset = 0;
11632 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11633 rsurface.batchsvector3f_vertexbuffer = NULL;
11634 rsurface.batchsvector3f_bufferoffset = 0;
11635 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11636 rsurface.batchtvector3f_vertexbuffer = NULL;
11637 rsurface.batchtvector3f_bufferoffset = 0;
11638 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11639 rsurface.batchnormal3f_vertexbuffer = NULL;
11640 rsurface.batchnormal3f_bufferoffset = 0;
11642 case Q3DEFORM_MOVE:
11643 // deform vertex array
11644 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11645 break; // if wavefunc is a nop, don't make a dynamic vertex array
11646 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
11647 VectorScale(deform->parms, scale, waveparms);
11648 for (j = 0;j < rsurface.batchnumvertices;j++)
11649 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
11650 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11651 rsurface.batchvertex3f_vertexbuffer = NULL;
11652 rsurface.batchvertex3f_bufferoffset = 0;
11657 // generate texcoords based on the chosen texcoord source
11658 switch(rsurface.texture->tcgen.tcgen)
11661 case Q3TCGEN_TEXTURE:
11663 case Q3TCGEN_LIGHTMAP:
11664 if (rsurface.batchtexcoordlightmap2f)
11665 memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
11666 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11667 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11668 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11670 case Q3TCGEN_VECTOR:
11671 for (j = 0;j < rsurface.batchnumvertices;j++)
11673 rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
11674 rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
11676 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11677 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11678 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11680 case Q3TCGEN_ENVIRONMENT:
11681 // make environment reflections using a spheremap
11682 for (j = 0;j < rsurface.batchnumvertices;j++)
11684 // identical to Q3A's method, but executed in worldspace so
11685 // carried models can be shiny too
11687 float viewer[3], d, reflected[3], worldreflected[3];
11689 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
11690 // VectorNormalize(viewer);
11692 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
11694 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
11695 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
11696 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
11697 // note: this is proportinal to viewer, so we can normalize later
11699 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
11700 VectorNormalize(worldreflected);
11702 // note: this sphere map only uses world x and z!
11703 // so positive and negative y will LOOK THE SAME.
11704 rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
11705 rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
11707 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11708 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11709 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11712 // the only tcmod that needs software vertex processing is turbulent, so
11713 // check for it here and apply the changes if needed
11714 // and we only support that as the first one
11715 // (handling a mixture of turbulent and other tcmods would be problematic
11716 // without punting it entirely to a software path)
11717 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11719 amplitude = rsurface.texture->tcmods[0].parms[1];
11720 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
11721 for (j = 0;j < rsurface.batchnumvertices;j++)
11723 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);
11724 rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11726 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11727 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11728 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11731 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11733 // convert the modified arrays to vertex structs
11734 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11735 rsurface.batchvertexmeshbuffer = NULL;
11736 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
11737 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11738 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
11739 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
11740 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11741 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
11742 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
11744 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11746 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
11747 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
11750 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
11751 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11752 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
11753 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
11754 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11755 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
11756 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
11757 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11758 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
11761 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11763 // convert the modified arrays to vertex structs
11764 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11765 rsurface.batchvertexpositionbuffer = NULL;
11766 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
11767 memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
11769 for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
11770 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
11774 void RSurf_DrawBatch(void)
11776 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);
11779 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
11781 // pick the closest matching water plane
11782 int planeindex, vertexindex, bestplaneindex = -1;
11786 r_waterstate_waterplane_t *p;
11788 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
11790 if(p->camera_entity != rsurface.texture->camera_entity)
11793 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, 1, &surface);
11794 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
11796 Matrix4x4_Transform(&rsurface.matrix, v, vert);
11797 d += fabs(PlaneDiff(vert, &p->plane));
11799 if (bestd > d || bestplaneindex < 0)
11802 bestplaneindex = planeindex;
11805 return bestplaneindex;
11808 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
11811 for (i = 0;i < rsurface.batchnumvertices;i++)
11812 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
11813 rsurface.passcolor4f = rsurface.array_passcolor4f;
11814 rsurface.passcolor4f_vertexbuffer = 0;
11815 rsurface.passcolor4f_bufferoffset = 0;
11818 static void RSurf_DrawBatch_GL11_ApplyFog(void)
11825 if (rsurface.passcolor4f)
11827 // generate color arrays
11828 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)
11830 f = RSurf_FogVertex(v);
11839 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
11841 f = RSurf_FogVertex(v);
11848 rsurface.passcolor4f = rsurface.array_passcolor4f;
11849 rsurface.passcolor4f_vertexbuffer = 0;
11850 rsurface.passcolor4f_bufferoffset = 0;
11853 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11860 if (!rsurface.passcolor4f)
11862 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)
11864 f = RSurf_FogVertex(v);
11865 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11866 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11867 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11870 rsurface.passcolor4f = rsurface.array_passcolor4f;
11871 rsurface.passcolor4f_vertexbuffer = 0;
11872 rsurface.passcolor4f_bufferoffset = 0;
11875 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11880 if (!rsurface.passcolor4f)
11882 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11889 rsurface.passcolor4f = rsurface.array_passcolor4f;
11890 rsurface.passcolor4f_vertexbuffer = 0;
11891 rsurface.passcolor4f_bufferoffset = 0;
11894 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11899 if (!rsurface.passcolor4f)
11901 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11903 c2[0] = c[0] + r_refdef.scene.ambient;
11904 c2[1] = c[1] + r_refdef.scene.ambient;
11905 c2[2] = c[2] + r_refdef.scene.ambient;
11908 rsurface.passcolor4f = rsurface.array_passcolor4f;
11909 rsurface.passcolor4f_vertexbuffer = 0;
11910 rsurface.passcolor4f_bufferoffset = 0;
11913 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11916 rsurface.passcolor4f = NULL;
11917 rsurface.passcolor4f_vertexbuffer = 0;
11918 rsurface.passcolor4f_bufferoffset = 0;
11919 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11920 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11921 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11922 GL_Color(r, g, b, a);
11923 R_Mesh_TexBind(0, rsurface.lightmaptexture);
11927 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11929 // TODO: optimize applyfog && applycolor case
11930 // just apply fog if necessary, and tint the fog color array if necessary
11931 rsurface.passcolor4f = NULL;
11932 rsurface.passcolor4f_vertexbuffer = 0;
11933 rsurface.passcolor4f_bufferoffset = 0;
11934 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11935 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11936 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11937 GL_Color(r, g, b, a);
11941 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11944 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11945 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11946 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11947 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11948 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11949 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11950 GL_Color(r, g, b, a);
11954 static void RSurf_DrawBatch_GL11_ClampColor(void)
11959 if (!rsurface.passcolor4f)
11961 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11963 c2[0] = bound(0.0f, c1[0], 1.0f);
11964 c2[1] = bound(0.0f, c1[1], 1.0f);
11965 c2[2] = bound(0.0f, c1[2], 1.0f);
11966 c2[3] = bound(0.0f, c1[3], 1.0f);
11970 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
11978 vec3_t ambientcolor;
11979 vec3_t diffusecolor;
11983 VectorCopy(rsurface.modellight_lightdir, lightdir);
11984 f = 0.5f * r_refdef.lightmapintensity;
11985 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11986 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11987 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11988 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11989 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11990 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11992 if (VectorLength2(diffusecolor) > 0)
11994 // q3-style directional shading
11995 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)
11997 if ((f = DotProduct(n, lightdir)) > 0)
11998 VectorMA(ambientcolor, f, diffusecolor, c);
12000 VectorCopy(ambientcolor, c);
12007 rsurface.passcolor4f = rsurface.array_passcolor4f;
12008 rsurface.passcolor4f_vertexbuffer = 0;
12009 rsurface.passcolor4f_bufferoffset = 0;
12010 *applycolor = false;
12014 *r = ambientcolor[0];
12015 *g = ambientcolor[1];
12016 *b = ambientcolor[2];
12017 rsurface.passcolor4f = NULL;
12018 rsurface.passcolor4f_vertexbuffer = 0;
12019 rsurface.passcolor4f_bufferoffset = 0;
12023 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12025 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
12026 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
12027 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12028 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12029 GL_Color(r, g, b, a);
12033 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
12039 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
12041 f = 1 - RSurf_FogVertex(v);
12049 void RSurf_SetupDepthAndCulling(void)
12051 // submodels are biased to avoid z-fighting with world surfaces that they
12052 // may be exactly overlapping (avoids z-fighting artifacts on certain
12053 // doors and things in Quake maps)
12054 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
12055 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
12056 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
12057 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
12060 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12062 // transparent sky would be ridiculous
12063 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12065 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12066 skyrenderlater = true;
12067 RSurf_SetupDepthAndCulling();
12068 GL_DepthMask(true);
12069 // LordHavoc: HalfLife maps have freaky skypolys so don't use
12070 // skymasking on them, and Quake3 never did sky masking (unlike
12071 // software Quake and software Quake2), so disable the sky masking
12072 // in Quake3 maps as it causes problems with q3map2 sky tricks,
12073 // and skymasking also looks very bad when noclipping outside the
12074 // level, so don't use it then either.
12075 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
12077 R_Mesh_ResetTextureState();
12078 if (skyrendermasked)
12080 R_SetupShader_DepthOrShadow();
12081 // depth-only (masking)
12082 GL_ColorMask(0,0,0,0);
12083 // just to make sure that braindead drivers don't draw
12084 // anything despite that colormask...
12085 GL_BlendFunc(GL_ZERO, GL_ONE);
12086 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12087 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12091 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12093 GL_BlendFunc(GL_ONE, GL_ZERO);
12094 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
12095 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
12096 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12099 if (skyrendermasked)
12100 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12102 R_Mesh_ResetTextureState();
12103 GL_Color(1, 1, 1, 1);
12106 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
12107 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
12108 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12110 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
12114 // render screenspace normalmap to texture
12115 GL_DepthMask(true);
12116 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL);
12121 // bind lightmap texture
12123 // water/refraction/reflection/camera surfaces have to be handled specially
12124 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)) && !r_waterstate.renderingscene)
12126 int start, end, startplaneindex;
12127 for (start = 0;start < texturenumsurfaces;start = end)
12129 startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
12130 for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
12132 // now that we have a batch using the same planeindex, render it
12133 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
12135 // render water or distortion background
12136 GL_DepthMask(true);
12137 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12139 // blend surface on top
12140 GL_DepthMask(false);
12141 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL);
12144 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
12146 // render surface with reflection texture as input
12147 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12148 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12155 // render surface batch normally
12156 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12157 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL);
12161 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12163 // OpenGL 1.3 path - anything not completely ancient
12164 qboolean applycolor;
12167 const texturelayer_t *layer;
12168 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);
12169 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12171 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12174 int layertexrgbscale;
12175 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12177 if (layerindex == 0)
12178 GL_AlphaTest(true);
12181 GL_AlphaTest(false);
12182 GL_DepthFunc(GL_EQUAL);
12185 GL_DepthMask(layer->depthmask && writedepth);
12186 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12187 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
12189 layertexrgbscale = 4;
12190 VectorScale(layer->color, 0.25f, layercolor);
12192 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
12194 layertexrgbscale = 2;
12195 VectorScale(layer->color, 0.5f, layercolor);
12199 layertexrgbscale = 1;
12200 VectorScale(layer->color, 1.0f, layercolor);
12202 layercolor[3] = layer->color[3];
12203 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
12204 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12205 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12206 switch (layer->type)
12208 case TEXTURELAYERTYPE_LITTEXTURE:
12209 // single-pass lightmapped texture with 2x rgbscale
12210 R_Mesh_TexBind(0, r_texture_white);
12211 R_Mesh_TexMatrix(0, NULL);
12212 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12213 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12214 R_Mesh_TexBind(1, layer->texture);
12215 R_Mesh_TexMatrix(1, &layer->texmatrix);
12216 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12217 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12218 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12219 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12220 else if (rsurface.uselightmaptexture)
12221 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12223 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12225 case TEXTURELAYERTYPE_TEXTURE:
12226 // singletexture unlit texture with transparency support
12227 R_Mesh_TexBind(0, layer->texture);
12228 R_Mesh_TexMatrix(0, &layer->texmatrix);
12229 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12230 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12231 R_Mesh_TexBind(1, 0);
12232 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12233 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12235 case TEXTURELAYERTYPE_FOG:
12236 // singletexture fogging
12237 if (layer->texture)
12239 R_Mesh_TexBind(0, layer->texture);
12240 R_Mesh_TexMatrix(0, &layer->texmatrix);
12241 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12242 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12246 R_Mesh_TexBind(0, 0);
12247 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12249 R_Mesh_TexBind(1, 0);
12250 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12251 // generate a color array for the fog pass
12252 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
12253 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
12257 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12260 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12262 GL_DepthFunc(GL_LEQUAL);
12263 GL_AlphaTest(false);
12267 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12269 // OpenGL 1.1 - crusty old voodoo path
12272 const texturelayer_t *layer;
12273 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);
12274 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12276 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12278 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12280 if (layerindex == 0)
12281 GL_AlphaTest(true);
12284 GL_AlphaTest(false);
12285 GL_DepthFunc(GL_EQUAL);
12288 GL_DepthMask(layer->depthmask && writedepth);
12289 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12290 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12291 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12292 switch (layer->type)
12294 case TEXTURELAYERTYPE_LITTEXTURE:
12295 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
12297 // two-pass lit texture with 2x rgbscale
12298 // first the lightmap pass
12299 R_Mesh_TexBind(0, r_texture_white);
12300 R_Mesh_TexMatrix(0, NULL);
12301 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12302 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12303 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12304 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
12305 else if (rsurface.uselightmaptexture)
12306 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
12308 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
12309 // then apply the texture to it
12310 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
12311 R_Mesh_TexBind(0, layer->texture);
12312 R_Mesh_TexMatrix(0, &layer->texmatrix);
12313 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12314 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12315 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);
12319 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
12320 R_Mesh_TexBind(0, layer->texture);
12321 R_Mesh_TexMatrix(0, &layer->texmatrix);
12322 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12323 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12324 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12325 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);
12327 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);
12330 case TEXTURELAYERTYPE_TEXTURE:
12331 // singletexture unlit texture with transparency support
12332 R_Mesh_TexBind(0, layer->texture);
12333 R_Mesh_TexMatrix(0, &layer->texmatrix);
12334 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12335 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12336 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);
12338 case TEXTURELAYERTYPE_FOG:
12339 // singletexture fogging
12340 if (layer->texture)
12342 R_Mesh_TexBind(0, layer->texture);
12343 R_Mesh_TexMatrix(0, &layer->texmatrix);
12344 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12345 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12349 R_Mesh_TexBind(0, 0);
12350 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12352 // generate a color array for the fog pass
12353 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
12354 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
12358 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12361 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12363 GL_DepthFunc(GL_LEQUAL);
12364 GL_AlphaTest(false);
12368 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12372 r_vertexgeneric_t *batchvertex;
12375 GL_AlphaTest(false);
12376 R_Mesh_ResetTextureState();
12377 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12379 if(rsurface.texture && rsurface.texture->currentskinframe)
12381 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
12382 c[3] *= rsurface.texture->currentalpha;
12392 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
12394 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
12395 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
12396 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
12399 // brighten it up (as texture value 127 means "unlit")
12400 c[0] *= 2 * r_refdef.view.colorscale;
12401 c[1] *= 2 * r_refdef.view.colorscale;
12402 c[2] *= 2 * r_refdef.view.colorscale;
12404 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
12405 c[3] *= r_wateralpha.value;
12407 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
12409 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12410 GL_DepthMask(false);
12412 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
12414 GL_BlendFunc(GL_ONE, GL_ONE);
12415 GL_DepthMask(false);
12417 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12419 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
12420 GL_DepthMask(false);
12422 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
12424 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
12425 GL_DepthMask(false);
12429 GL_BlendFunc(GL_ONE, GL_ZERO);
12430 GL_DepthMask(writedepth);
12433 if (r_showsurfaces.integer == 3)
12435 rsurface.passcolor4f = NULL;
12437 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
12439 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12441 rsurface.passcolor4f = NULL;
12442 rsurface.passcolor4f_vertexbuffer = 0;
12443 rsurface.passcolor4f_bufferoffset = 0;
12445 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12447 qboolean applycolor = true;
12450 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12452 r_refdef.lightmapintensity = 1;
12453 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
12454 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12458 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12460 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12461 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12462 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12465 if(!rsurface.passcolor4f)
12466 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
12468 RSurf_DrawBatch_GL11_ApplyAmbient();
12469 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
12470 if(r_refdef.fogenabled)
12471 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
12472 RSurf_DrawBatch_GL11_ClampColor();
12474 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
12475 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12478 else if (!r_refdef.view.showdebug)
12480 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12481 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12482 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12484 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12485 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
12487 R_Mesh_PrepareVertices_Generic_Unlock();
12490 else if (r_showsurfaces.integer == 4)
12492 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12493 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12494 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12496 unsigned char c = vi << 3;
12497 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12498 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
12500 R_Mesh_PrepareVertices_Generic_Unlock();
12503 else if (r_showsurfaces.integer == 2)
12506 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12507 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
12508 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
12510 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
12511 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
12512 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
12513 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
12514 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
12515 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
12516 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
12518 R_Mesh_PrepareVertices_Generic_Unlock();
12519 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
12523 int texturesurfaceindex;
12525 const msurface_t *surface;
12526 unsigned char surfacecolor4ub[4];
12527 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12528 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
12530 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
12532 surface = texturesurfacelist[texturesurfaceindex];
12533 k = (int)(((size_t)surface) / sizeof(msurface_t));
12534 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
12535 for (j = 0;j < surface->num_vertices;j++)
12537 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12538 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
12542 R_Mesh_PrepareVertices_Generic_Unlock();
12547 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12550 RSurf_SetupDepthAndCulling();
12551 if (r_showsurfaces.integer)
12553 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12556 switch (vid.renderpath)
12558 case RENDERPATH_GL20:
12559 case RENDERPATH_CGGL:
12560 case RENDERPATH_D3D9:
12561 case RENDERPATH_D3D10:
12562 case RENDERPATH_D3D11:
12563 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12565 case RENDERPATH_GL13:
12566 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12568 case RENDERPATH_GL11:
12569 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12575 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12578 RSurf_SetupDepthAndCulling();
12579 if (r_showsurfaces.integer)
12581 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12584 switch (vid.renderpath)
12586 case RENDERPATH_GL20:
12587 case RENDERPATH_CGGL:
12588 case RENDERPATH_D3D9:
12589 case RENDERPATH_D3D10:
12590 case RENDERPATH_D3D11:
12591 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12593 case RENDERPATH_GL13:
12594 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12596 case RENDERPATH_GL11:
12597 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12603 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12606 int texturenumsurfaces, endsurface;
12607 texture_t *texture;
12608 const msurface_t *surface;
12609 #define MAXBATCH_TRANSPARENTSURFACES 256
12610 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
12612 // if the model is static it doesn't matter what value we give for
12613 // wantnormals and wanttangents, so this logic uses only rules applicable
12614 // to a model, knowing that they are meaningless otherwise
12615 if (ent == r_refdef.scene.worldentity)
12616 RSurf_ActiveWorldEntity();
12617 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12618 RSurf_ActiveModelEntity(ent, false, false, false);
12621 switch (vid.renderpath)
12623 case RENDERPATH_GL20:
12624 case RENDERPATH_CGGL:
12625 case RENDERPATH_D3D9:
12626 case RENDERPATH_D3D10:
12627 case RENDERPATH_D3D11:
12628 RSurf_ActiveModelEntity(ent, true, true, false);
12630 case RENDERPATH_GL13:
12631 case RENDERPATH_GL11:
12632 RSurf_ActiveModelEntity(ent, true, false, false);
12637 if (r_transparentdepthmasking.integer)
12639 qboolean setup = false;
12640 for (i = 0;i < numsurfaces;i = j)
12643 surface = rsurface.modelsurfaces + surfacelist[i];
12644 texture = surface->texture;
12645 rsurface.texture = R_GetCurrentTexture(texture);
12646 rsurface.lightmaptexture = NULL;
12647 rsurface.deluxemaptexture = NULL;
12648 rsurface.uselightmaptexture = false;
12649 // scan ahead until we find a different texture
12650 endsurface = min(i + 1024, numsurfaces);
12651 texturenumsurfaces = 0;
12652 texturesurfacelist[texturenumsurfaces++] = surface;
12653 for (;j < endsurface;j++)
12655 surface = rsurface.modelsurfaces + surfacelist[j];
12656 if (texture != surface->texture)
12658 texturesurfacelist[texturenumsurfaces++] = surface;
12660 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
12662 // render the range of surfaces as depth
12666 GL_ColorMask(0,0,0,0);
12668 GL_DepthTest(true);
12669 GL_BlendFunc(GL_ONE, GL_ZERO);
12670 GL_DepthMask(true);
12671 GL_AlphaTest(false);
12672 R_Mesh_ResetTextureState();
12673 R_SetupShader_DepthOrShadow();
12675 RSurf_SetupDepthAndCulling();
12676 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12677 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12681 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12684 for (i = 0;i < numsurfaces;i = j)
12687 surface = rsurface.modelsurfaces + surfacelist[i];
12688 texture = surface->texture;
12689 rsurface.texture = R_GetCurrentTexture(texture);
12690 rsurface.lightmaptexture = surface->lightmaptexture;
12691 rsurface.deluxemaptexture = surface->deluxemaptexture;
12692 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
12693 // scan ahead until we find a different texture
12694 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
12695 texturenumsurfaces = 0;
12696 texturesurfacelist[texturenumsurfaces++] = surface;
12697 for (;j < endsurface;j++)
12699 surface = rsurface.modelsurfaces + surfacelist[j];
12700 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
12702 texturesurfacelist[texturenumsurfaces++] = surface;
12704 // render the range of surfaces
12705 if (ent == r_refdef.scene.worldentity)
12706 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12708 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12710 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12711 GL_AlphaTest(false);
12714 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
12716 // transparent surfaces get pushed off into the transparent queue
12717 int surfacelistindex;
12718 const msurface_t *surface;
12719 vec3_t tempcenter, center;
12720 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
12722 surface = texturesurfacelist[surfacelistindex];
12723 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
12724 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
12725 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
12726 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
12727 if (queueentity->transparent_offset) // transparent offset
12729 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
12730 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
12731 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
12733 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
12737 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12739 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12741 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12743 RSurf_SetupDepthAndCulling();
12744 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12745 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12749 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
12751 const entity_render_t *queueentity = r_refdef.scene.worldentity;
12754 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12757 if (!rsurface.texture->currentnumlayers)
12759 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12760 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12762 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12764 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12765 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12766 else if (!rsurface.texture->currentnumlayers)
12768 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12770 // in the deferred case, transparent surfaces were queued during prepass
12771 if (!r_shadow_usingdeferredprepass)
12772 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12776 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12777 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12782 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12785 texture_t *texture;
12786 // break the surface list down into batches by texture and use of lightmapping
12787 for (i = 0;i < numsurfaces;i = j)
12790 // texture is the base texture pointer, rsurface.texture is the
12791 // current frame/skin the texture is directing us to use (for example
12792 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12793 // use skin 1 instead)
12794 texture = surfacelist[i]->texture;
12795 rsurface.texture = R_GetCurrentTexture(texture);
12796 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12797 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12798 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12799 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12801 // if this texture is not the kind we want, skip ahead to the next one
12802 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12806 // simply scan ahead until we find a different texture or lightmap state
12807 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12809 // render the range of surfaces
12810 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12814 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12818 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12821 if (!rsurface.texture->currentnumlayers)
12823 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12824 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12826 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12828 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12829 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12830 else if (!rsurface.texture->currentnumlayers)
12832 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12834 // in the deferred case, transparent surfaces were queued during prepass
12835 if (!r_shadow_usingdeferredprepass)
12836 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12840 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12841 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12846 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12849 texture_t *texture;
12850 // break the surface list down into batches by texture and use of lightmapping
12851 for (i = 0;i < numsurfaces;i = j)
12854 // texture is the base texture pointer, rsurface.texture is the
12855 // current frame/skin the texture is directing us to use (for example
12856 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12857 // use skin 1 instead)
12858 texture = surfacelist[i]->texture;
12859 rsurface.texture = R_GetCurrentTexture(texture);
12860 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12861 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12862 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12863 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12865 // if this texture is not the kind we want, skip ahead to the next one
12866 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12870 // simply scan ahead until we find a different texture or lightmap state
12871 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12873 // render the range of surfaces
12874 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12878 float locboxvertex3f[6*4*3] =
12880 1,0,1, 1,0,0, 1,1,0, 1,1,1,
12881 0,1,1, 0,1,0, 0,0,0, 0,0,1,
12882 1,1,1, 1,1,0, 0,1,0, 0,1,1,
12883 0,0,1, 0,0,0, 1,0,0, 1,0,1,
12884 0,0,1, 1,0,1, 1,1,1, 0,1,1,
12885 1,0,0, 0,0,0, 0,1,0, 1,1,0
12888 unsigned short locboxelements[6*2*3] =
12893 12,13,14, 12,14,15,
12894 16,17,18, 16,18,19,
12898 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12901 cl_locnode_t *loc = (cl_locnode_t *)ent;
12903 float vertex3f[6*4*3];
12905 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12906 GL_DepthMask(false);
12907 GL_DepthRange(0, 1);
12908 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12909 GL_DepthTest(true);
12910 GL_CullFace(GL_NONE);
12911 R_EntityMatrix(&identitymatrix);
12913 R_Mesh_ResetTextureState();
12915 i = surfacelist[0];
12916 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12917 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12918 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12919 surfacelist[0] < 0 ? 0.5f : 0.125f);
12921 if (VectorCompare(loc->mins, loc->maxs))
12923 VectorSet(size, 2, 2, 2);
12924 VectorMA(loc->mins, -0.5f, size, mins);
12928 VectorCopy(loc->mins, mins);
12929 VectorSubtract(loc->maxs, loc->mins, size);
12932 for (i = 0;i < 6*4*3;)
12933 for (j = 0;j < 3;j++, i++)
12934 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12936 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
12937 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12938 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
12941 void R_DrawLocs(void)
12944 cl_locnode_t *loc, *nearestloc;
12946 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12947 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12949 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12950 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12954 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12956 if (decalsystem->decals)
12957 Mem_Free(decalsystem->decals);
12958 memset(decalsystem, 0, sizeof(*decalsystem));
12961 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)
12964 tridecal_t *decals;
12967 // expand or initialize the system
12968 if (decalsystem->maxdecals <= decalsystem->numdecals)
12970 decalsystem_t old = *decalsystem;
12971 qboolean useshortelements;
12972 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12973 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12974 decalsystem->decals = (tridecal_t *)Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
12975 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12976 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12977 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12978 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12979 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12980 if (decalsystem->numdecals)
12981 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12983 Mem_Free(old.decals);
12984 for (i = 0;i < decalsystem->maxdecals*3;i++)
12985 decalsystem->element3i[i] = i;
12986 if (useshortelements)
12987 for (i = 0;i < decalsystem->maxdecals*3;i++)
12988 decalsystem->element3s[i] = i;
12991 // grab a decal and search for another free slot for the next one
12992 decals = decalsystem->decals;
12993 decal = decalsystem->decals + (i = decalsystem->freedecal++);
12994 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12996 decalsystem->freedecal = i;
12997 if (decalsystem->numdecals <= i)
12998 decalsystem->numdecals = i + 1;
13000 // initialize the decal
13002 decal->triangleindex = triangleindex;
13003 decal->surfaceindex = surfaceindex;
13004 decal->decalsequence = decalsequence;
13005 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
13006 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
13007 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
13008 decal->color4ub[0][3] = 255;
13009 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
13010 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
13011 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
13012 decal->color4ub[1][3] = 255;
13013 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
13014 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
13015 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
13016 decal->color4ub[2][3] = 255;
13017 decal->vertex3f[0][0] = v0[0];
13018 decal->vertex3f[0][1] = v0[1];
13019 decal->vertex3f[0][2] = v0[2];
13020 decal->vertex3f[1][0] = v1[0];
13021 decal->vertex3f[1][1] = v1[1];
13022 decal->vertex3f[1][2] = v1[2];
13023 decal->vertex3f[2][0] = v2[0];
13024 decal->vertex3f[2][1] = v2[1];
13025 decal->vertex3f[2][2] = v2[2];
13026 decal->texcoord2f[0][0] = t0[0];
13027 decal->texcoord2f[0][1] = t0[1];
13028 decal->texcoord2f[1][0] = t1[0];
13029 decal->texcoord2f[1][1] = t1[1];
13030 decal->texcoord2f[2][0] = t2[0];
13031 decal->texcoord2f[2][1] = t2[1];
13034 extern cvar_t cl_decals_bias;
13035 extern cvar_t cl_decals_models;
13036 extern cvar_t cl_decals_newsystem_intensitymultiplier;
13037 // baseparms, parms, temps
13038 static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
13043 const float *vertex3f;
13045 float points[2][9][3];
13052 e = rsurface.modelelement3i + 3*triangleindex;
13054 vertex3f = rsurface.modelvertex3f;
13056 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13058 index = 3*e[cornerindex];
13059 VectorCopy(vertex3f + index, v[cornerindex]);
13062 //TriangleNormal(v[0], v[1], v[2], normal);
13063 //if (DotProduct(normal, localnormal) < 0.0f)
13065 // clip by each of the box planes formed from the projection matrix
13066 // if anything survives, we emit the decal
13067 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]);
13070 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]);
13073 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]);
13076 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]);
13079 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]);
13082 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]);
13085 // some part of the triangle survived, so we have to accept it...
13088 // dynamic always uses the original triangle
13090 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13092 index = 3*e[cornerindex];
13093 VectorCopy(vertex3f + index, v[cornerindex]);
13096 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
13098 // convert vertex positions to texcoords
13099 Matrix4x4_Transform(projection, v[cornerindex], temp);
13100 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
13101 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
13102 // calculate distance fade from the projection origin
13103 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
13104 f = bound(0.0f, f, 1.0f);
13105 c[cornerindex][0] = r * f;
13106 c[cornerindex][1] = g * f;
13107 c[cornerindex][2] = b * f;
13108 c[cornerindex][3] = 1.0f;
13109 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
13112 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
13114 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
13115 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);
13117 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)
13119 matrix4x4_t projection;
13120 decalsystem_t *decalsystem;
13123 const msurface_t *surface;
13124 const msurface_t *surfaces;
13125 const int *surfacelist;
13126 const texture_t *texture;
13128 int numsurfacelist;
13129 int surfacelistindex;
13132 float localorigin[3];
13133 float localnormal[3];
13134 float localmins[3];
13135 float localmaxs[3];
13138 float planes[6][4];
13141 int bih_triangles_count;
13142 int bih_triangles[256];
13143 int bih_surfaces[256];
13145 decalsystem = &ent->decalsystem;
13146 model = ent->model;
13147 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
13149 R_DecalSystem_Reset(&ent->decalsystem);
13153 if (!model->brush.data_nodes && !cl_decals_models.integer)
13155 if (decalsystem->model)
13156 R_DecalSystem_Reset(decalsystem);
13160 if (decalsystem->model != model)
13161 R_DecalSystem_Reset(decalsystem);
13162 decalsystem->model = model;
13164 RSurf_ActiveModelEntity(ent, false, false, false);
13166 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
13167 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
13168 VectorNormalize(localnormal);
13169 localsize = worldsize*rsurface.inversematrixscale;
13170 localmins[0] = localorigin[0] - localsize;
13171 localmins[1] = localorigin[1] - localsize;
13172 localmins[2] = localorigin[2] - localsize;
13173 localmaxs[0] = localorigin[0] + localsize;
13174 localmaxs[1] = localorigin[1] + localsize;
13175 localmaxs[2] = localorigin[2] + localsize;
13177 //VectorCopy(localnormal, planes[4]);
13178 //VectorVectors(planes[4], planes[2], planes[0]);
13179 AnglesFromVectors(angles, localnormal, NULL, false);
13180 AngleVectors(angles, planes[0], planes[2], planes[4]);
13181 VectorNegate(planes[0], planes[1]);
13182 VectorNegate(planes[2], planes[3]);
13183 VectorNegate(planes[4], planes[5]);
13184 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
13185 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
13186 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
13187 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
13188 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
13189 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
13194 matrix4x4_t forwardprojection;
13195 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
13196 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
13201 float projectionvector[4][3];
13202 VectorScale(planes[0], ilocalsize, projectionvector[0]);
13203 VectorScale(planes[2], ilocalsize, projectionvector[1]);
13204 VectorScale(planes[4], ilocalsize, projectionvector[2]);
13205 projectionvector[0][0] = planes[0][0] * ilocalsize;
13206 projectionvector[0][1] = planes[1][0] * ilocalsize;
13207 projectionvector[0][2] = planes[2][0] * ilocalsize;
13208 projectionvector[1][0] = planes[0][1] * ilocalsize;
13209 projectionvector[1][1] = planes[1][1] * ilocalsize;
13210 projectionvector[1][2] = planes[2][1] * ilocalsize;
13211 projectionvector[2][0] = planes[0][2] * ilocalsize;
13212 projectionvector[2][1] = planes[1][2] * ilocalsize;
13213 projectionvector[2][2] = planes[2][2] * ilocalsize;
13214 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
13215 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
13216 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
13217 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
13221 dynamic = model->surfmesh.isanimated;
13222 numsurfacelist = model->nummodelsurfaces;
13223 surfacelist = model->sortedmodelsurfaces;
13224 surfaces = model->data_surfaces;
13227 bih_triangles_count = -1;
13230 if(model->render_bih.numleafs)
13231 bih = &model->render_bih;
13232 else if(model->collision_bih.numleafs)
13233 bih = &model->collision_bih;
13236 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
13237 if(bih_triangles_count == 0)
13239 if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
13241 if(bih_triangles_count > 0)
13243 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
13245 surfaceindex = bih_surfaces[triangleindex];
13246 surface = surfaces + surfaceindex;
13247 texture = surface->texture;
13248 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13250 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13252 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
13257 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
13259 surfaceindex = surfacelist[surfacelistindex];
13260 surface = surfaces + surfaceindex;
13261 // check cull box first because it rejects more than any other check
13262 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
13264 // skip transparent surfaces
13265 texture = surface->texture;
13266 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13268 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13270 numtriangles = surface->num_triangles;
13271 for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
13272 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
13277 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
13278 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)
13280 int renderentityindex;
13281 float worldmins[3];
13282 float worldmaxs[3];
13283 entity_render_t *ent;
13285 if (!cl_decals_newsystem.integer)
13288 worldmins[0] = worldorigin[0] - worldsize;
13289 worldmins[1] = worldorigin[1] - worldsize;
13290 worldmins[2] = worldorigin[2] - worldsize;
13291 worldmaxs[0] = worldorigin[0] + worldsize;
13292 worldmaxs[1] = worldorigin[1] + worldsize;
13293 worldmaxs[2] = worldorigin[2] + worldsize;
13295 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13297 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
13299 ent = r_refdef.scene.entities[renderentityindex];
13300 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
13303 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13307 typedef struct r_decalsystem_splatqueue_s
13309 vec3_t worldorigin;
13310 vec3_t worldnormal;
13316 r_decalsystem_splatqueue_t;
13318 int r_decalsystem_numqueued = 0;
13319 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
13321 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)
13323 r_decalsystem_splatqueue_t *queue;
13325 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
13328 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
13329 VectorCopy(worldorigin, queue->worldorigin);
13330 VectorCopy(worldnormal, queue->worldnormal);
13331 Vector4Set(queue->color, r, g, b, a);
13332 Vector4Set(queue->tcrange, s1, t1, s2, t2);
13333 queue->worldsize = worldsize;
13334 queue->decalsequence = cl.decalsequence++;
13337 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
13340 r_decalsystem_splatqueue_t *queue;
13342 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
13343 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);
13344 r_decalsystem_numqueued = 0;
13347 extern cvar_t cl_decals_max;
13348 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
13351 decalsystem_t *decalsystem = &ent->decalsystem;
13358 if (!decalsystem->numdecals)
13361 if (r_showsurfaces.integer)
13364 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13366 R_DecalSystem_Reset(decalsystem);
13370 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
13371 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
13373 if (decalsystem->lastupdatetime)
13374 frametime = (cl.time - decalsystem->lastupdatetime);
13377 decalsystem->lastupdatetime = cl.time;
13378 decal = decalsystem->decals;
13379 numdecals = decalsystem->numdecals;
13381 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13383 if (decal->color4ub[0][3])
13385 decal->lived += frametime;
13386 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
13388 memset(decal, 0, sizeof(*decal));
13389 if (decalsystem->freedecal > i)
13390 decalsystem->freedecal = i;
13394 decal = decalsystem->decals;
13395 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
13398 // collapse the array by shuffling the tail decals into the gaps
13401 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
13402 decalsystem->freedecal++;
13403 if (decalsystem->freedecal == numdecals)
13405 decal[decalsystem->freedecal] = decal[--numdecals];
13408 decalsystem->numdecals = numdecals;
13410 if (numdecals <= 0)
13412 // if there are no decals left, reset decalsystem
13413 R_DecalSystem_Reset(decalsystem);
13417 extern skinframe_t *decalskinframe;
13418 static void R_DrawModelDecals_Entity(entity_render_t *ent)
13421 decalsystem_t *decalsystem = &ent->decalsystem;
13430 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
13433 numdecals = decalsystem->numdecals;
13437 if (r_showsurfaces.integer)
13440 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13442 R_DecalSystem_Reset(decalsystem);
13446 // if the model is static it doesn't matter what value we give for
13447 // wantnormals and wanttangents, so this logic uses only rules applicable
13448 // to a model, knowing that they are meaningless otherwise
13449 if (ent == r_refdef.scene.worldentity)
13450 RSurf_ActiveWorldEntity();
13452 RSurf_ActiveModelEntity(ent, false, false, false);
13454 decalsystem->lastupdatetime = cl.time;
13455 decal = decalsystem->decals;
13457 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
13459 // update vertex positions for animated models
13460 v3f = decalsystem->vertex3f;
13461 c4f = decalsystem->color4f;
13462 t2f = decalsystem->texcoord2f;
13463 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13465 if (!decal->color4ub[0][3])
13468 if (surfacevisible && !surfacevisible[decal->surfaceindex])
13471 // update color values for fading decals
13472 if (decal->lived >= cl_decals_time.value)
13474 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
13475 alpha *= (1.0f/255.0f);
13478 alpha = 1.0f/255.0f;
13480 c4f[ 0] = decal->color4ub[0][0] * alpha;
13481 c4f[ 1] = decal->color4ub[0][1] * alpha;
13482 c4f[ 2] = decal->color4ub[0][2] * alpha;
13484 c4f[ 4] = decal->color4ub[1][0] * alpha;
13485 c4f[ 5] = decal->color4ub[1][1] * alpha;
13486 c4f[ 6] = decal->color4ub[1][2] * alpha;
13488 c4f[ 8] = decal->color4ub[2][0] * alpha;
13489 c4f[ 9] = decal->color4ub[2][1] * alpha;
13490 c4f[10] = decal->color4ub[2][2] * alpha;
13493 t2f[0] = decal->texcoord2f[0][0];
13494 t2f[1] = decal->texcoord2f[0][1];
13495 t2f[2] = decal->texcoord2f[1][0];
13496 t2f[3] = decal->texcoord2f[1][1];
13497 t2f[4] = decal->texcoord2f[2][0];
13498 t2f[5] = decal->texcoord2f[2][1];
13500 // update vertex positions for animated models
13501 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
13503 e = rsurface.modelelement3i + 3*decal->triangleindex;
13504 VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
13505 VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
13506 VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
13510 VectorCopy(decal->vertex3f[0], v3f);
13511 VectorCopy(decal->vertex3f[1], v3f + 3);
13512 VectorCopy(decal->vertex3f[2], v3f + 6);
13515 if (r_refdef.fogenabled)
13517 alpha = RSurf_FogVertex(v3f);
13518 VectorScale(c4f, alpha, c4f);
13519 alpha = RSurf_FogVertex(v3f + 3);
13520 VectorScale(c4f + 4, alpha, c4f + 4);
13521 alpha = RSurf_FogVertex(v3f + 6);
13522 VectorScale(c4f + 8, alpha, c4f + 8);
13533 r_refdef.stats.drawndecals += numtris;
13535 // now render the decals all at once
13536 // (this assumes they all use one particle font texture!)
13537 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);
13538 R_Mesh_ResetTextureState();
13539 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
13540 GL_DepthMask(false);
13541 GL_DepthRange(0, 1);
13542 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
13543 GL_DepthTest(true);
13544 GL_CullFace(GL_NONE);
13545 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
13546 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
13547 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
13551 static void R_DrawModelDecals(void)
13555 // fade faster when there are too many decals
13556 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13557 for (i = 0;i < r_refdef.scene.numentities;i++)
13558 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13560 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
13561 for (i = 0;i < r_refdef.scene.numentities;i++)
13562 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13563 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
13565 R_DecalSystem_ApplySplatEntitiesQueue();
13567 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13568 for (i = 0;i < r_refdef.scene.numentities;i++)
13569 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13571 r_refdef.stats.totaldecals += numdecals;
13573 if (r_showsurfaces.integer)
13576 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
13578 for (i = 0;i < r_refdef.scene.numentities;i++)
13580 if (!r_refdef.viewcache.entityvisible[i])
13582 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13583 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
13587 extern cvar_t mod_collision_bih;
13588 void R_DrawDebugModel(void)
13590 entity_render_t *ent = rsurface.entity;
13591 int i, j, k, l, flagsmask;
13592 const msurface_t *surface;
13593 dp_model_t *model = ent->model;
13596 switch(vid.renderpath)
13598 case RENDERPATH_GL11:
13599 case RENDERPATH_GL13:
13600 case RENDERPATH_GL20:
13601 case RENDERPATH_CGGL:
13603 case RENDERPATH_D3D9:
13604 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13606 case RENDERPATH_D3D10:
13607 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13609 case RENDERPATH_D3D11:
13610 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13614 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
13616 R_Mesh_ResetTextureState();
13617 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13618 GL_DepthRange(0, 1);
13619 GL_DepthTest(!r_showdisabledepthtest.integer);
13620 GL_DepthMask(false);
13621 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13623 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
13627 qboolean cullbox = ent == r_refdef.scene.worldentity;
13628 const q3mbrush_t *brush;
13629 const bih_t *bih = &model->collision_bih;
13630 const bih_leaf_t *bihleaf;
13631 float vertex3f[3][3];
13632 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
13634 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
13636 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
13638 switch (bihleaf->type)
13641 brush = model->brush.data_brushes + bihleaf->itemindex;
13642 if (brush->colbrushf && brush->colbrushf->numtriangles)
13644 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);
13645 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
13646 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
13649 case BIH_COLLISIONTRIANGLE:
13650 triangleindex = bihleaf->itemindex;
13651 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
13652 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
13653 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
13654 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);
13655 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13656 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13658 case BIH_RENDERTRIANGLE:
13659 triangleindex = bihleaf->itemindex;
13660 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
13661 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
13662 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
13663 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);
13664 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13665 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13671 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13673 if (r_showtris.integer || r_shownormals.integer)
13675 if (r_showdisabledepthtest.integer)
13677 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13678 GL_DepthMask(false);
13682 GL_BlendFunc(GL_ONE, GL_ZERO);
13683 GL_DepthMask(true);
13685 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
13687 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
13689 rsurface.texture = R_GetCurrentTexture(surface->texture);
13690 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
13692 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
13693 if (r_showtris.value > 0)
13695 if (!rsurface.texture->currentlayers->depthmask)
13696 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
13697 else if (ent == r_refdef.scene.worldentity)
13698 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
13700 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
13701 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
13702 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
13704 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
13707 if (r_shownormals.value < 0)
13709 qglBegin(GL_LINES);
13710 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13712 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13713 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13714 qglVertex3f(v[0], v[1], v[2]);
13715 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13716 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13717 qglVertex3f(v[0], v[1], v[2]);
13722 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
13724 qglBegin(GL_LINES);
13725 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13727 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13728 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13729 qglVertex3f(v[0], v[1], v[2]);
13730 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13731 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13732 qglVertex3f(v[0], v[1], v[2]);
13736 qglBegin(GL_LINES);
13737 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13739 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13740 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13741 qglVertex3f(v[0], v[1], v[2]);
13742 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
13743 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13744 qglVertex3f(v[0], v[1], v[2]);
13748 qglBegin(GL_LINES);
13749 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13751 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13752 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13753 qglVertex3f(v[0], v[1], v[2]);
13754 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13755 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13756 qglVertex3f(v[0], v[1], v[2]);
13763 rsurface.texture = NULL;
13767 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13768 int r_maxsurfacelist = 0;
13769 const msurface_t **r_surfacelist = NULL;
13770 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13772 int i, j, endj, flagsmask;
13773 dp_model_t *model = r_refdef.scene.worldmodel;
13774 msurface_t *surfaces;
13775 unsigned char *update;
13776 int numsurfacelist = 0;
13780 if (r_maxsurfacelist < model->num_surfaces)
13782 r_maxsurfacelist = model->num_surfaces;
13784 Mem_Free((msurface_t**)r_surfacelist);
13785 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13788 RSurf_ActiveWorldEntity();
13790 surfaces = model->data_surfaces;
13791 update = model->brushq1.lightmapupdateflags;
13793 // update light styles on this submodel
13794 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13796 model_brush_lightstyleinfo_t *style;
13797 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13799 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13801 int *list = style->surfacelist;
13802 style->value = r_refdef.scene.lightstylevalue[style->style];
13803 for (j = 0;j < style->numsurfaces;j++)
13804 update[list[j]] = true;
13809 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13813 R_DrawDebugModel();
13814 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13818 rsurface.lightmaptexture = NULL;
13819 rsurface.deluxemaptexture = NULL;
13820 rsurface.uselightmaptexture = false;
13821 rsurface.texture = NULL;
13822 rsurface.rtlight = NULL;
13823 numsurfacelist = 0;
13824 // add visible surfaces to draw list
13825 for (i = 0;i < model->nummodelsurfaces;i++)
13827 j = model->sortedmodelsurfaces[i];
13828 if (r_refdef.viewcache.world_surfacevisible[j])
13829 r_surfacelist[numsurfacelist++] = surfaces + j;
13831 // update lightmaps if needed
13832 if (model->brushq1.firstrender)
13834 model->brushq1.firstrender = false;
13835 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13837 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13841 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13842 if (r_refdef.viewcache.world_surfacevisible[j])
13844 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13846 // don't do anything if there were no surfaces
13847 if (!numsurfacelist)
13849 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13852 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13853 GL_AlphaTest(false);
13855 // add to stats if desired
13856 if (r_speeds.integer && !skysurfaces && !depthonly)
13858 r_refdef.stats.world_surfaces += numsurfacelist;
13859 for (j = 0;j < numsurfacelist;j++)
13860 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13863 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13866 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13868 int i, j, endj, flagsmask;
13869 dp_model_t *model = ent->model;
13870 msurface_t *surfaces;
13871 unsigned char *update;
13872 int numsurfacelist = 0;
13876 if (r_maxsurfacelist < model->num_surfaces)
13878 r_maxsurfacelist = model->num_surfaces;
13880 Mem_Free((msurface_t **)r_surfacelist);
13881 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13884 // if the model is static it doesn't matter what value we give for
13885 // wantnormals and wanttangents, so this logic uses only rules applicable
13886 // to a model, knowing that they are meaningless otherwise
13887 if (ent == r_refdef.scene.worldentity)
13888 RSurf_ActiveWorldEntity();
13889 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13890 RSurf_ActiveModelEntity(ent, false, false, false);
13892 RSurf_ActiveModelEntity(ent, true, true, true);
13893 else if (depthonly)
13895 switch (vid.renderpath)
13897 case RENDERPATH_GL20:
13898 case RENDERPATH_CGGL:
13899 case RENDERPATH_D3D9:
13900 case RENDERPATH_D3D10:
13901 case RENDERPATH_D3D11:
13902 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
13904 case RENDERPATH_GL13:
13905 case RENDERPATH_GL11:
13906 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
13912 switch (vid.renderpath)
13914 case RENDERPATH_GL20:
13915 case RENDERPATH_CGGL:
13916 case RENDERPATH_D3D9:
13917 case RENDERPATH_D3D10:
13918 case RENDERPATH_D3D11:
13919 RSurf_ActiveModelEntity(ent, true, true, false);
13921 case RENDERPATH_GL13:
13922 case RENDERPATH_GL11:
13923 RSurf_ActiveModelEntity(ent, true, false, false);
13928 surfaces = model->data_surfaces;
13929 update = model->brushq1.lightmapupdateflags;
13931 // update light styles
13932 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13934 model_brush_lightstyleinfo_t *style;
13935 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13937 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13939 int *list = style->surfacelist;
13940 style->value = r_refdef.scene.lightstylevalue[style->style];
13941 for (j = 0;j < style->numsurfaces;j++)
13942 update[list[j]] = true;
13947 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13951 R_DrawDebugModel();
13952 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13956 rsurface.lightmaptexture = NULL;
13957 rsurface.deluxemaptexture = NULL;
13958 rsurface.uselightmaptexture = false;
13959 rsurface.texture = NULL;
13960 rsurface.rtlight = NULL;
13961 numsurfacelist = 0;
13962 // add visible surfaces to draw list
13963 for (i = 0;i < model->nummodelsurfaces;i++)
13964 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13965 // don't do anything if there were no surfaces
13966 if (!numsurfacelist)
13968 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13971 // update lightmaps if needed
13975 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13980 R_BuildLightMap(ent, surfaces + j);
13985 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13987 R_BuildLightMap(ent, surfaces + j);
13988 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13989 GL_AlphaTest(false);
13991 // add to stats if desired
13992 if (r_speeds.integer && !skysurfaces && !depthonly)
13994 r_refdef.stats.entities_surfaces += numsurfacelist;
13995 for (j = 0;j < numsurfacelist;j++)
13996 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13999 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14002 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14004 static texture_t texture;
14005 static msurface_t surface;
14006 const msurface_t *surfacelist = &surface;
14008 // fake enough texture and surface state to render this geometry
14010 texture.update_lastrenderframe = -1; // regenerate this texture
14011 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
14012 texture.currentskinframe = skinframe;
14013 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
14014 texture.offsetmapping = OFFSETMAPPING_OFF;
14015 texture.offsetscale = 1;
14016 texture.specularscalemod = 1;
14017 texture.specularpowermod = 1;
14019 surface.texture = &texture;
14020 surface.num_triangles = numtriangles;
14021 surface.num_firsttriangle = firsttriangle;
14022 surface.num_vertices = numvertices;
14023 surface.num_firstvertex = firstvertex;
14026 rsurface.texture = R_GetCurrentTexture(surface.texture);
14027 rsurface.lightmaptexture = NULL;
14028 rsurface.deluxemaptexture = NULL;
14029 rsurface.uselightmaptexture = false;
14030 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14033 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)
14035 static msurface_t surface;
14036 const msurface_t *surfacelist = &surface;
14038 // fake enough texture and surface state to render this geometry
14040 surface.texture = texture;
14041 surface.num_triangles = numtriangles;
14042 surface.num_firsttriangle = firsttriangle;
14043 surface.num_vertices = numvertices;
14044 surface.num_firstvertex = firstvertex;
14047 rsurface.texture = R_GetCurrentTexture(surface.texture);
14048 rsurface.lightmaptexture = NULL;
14049 rsurface.deluxemaptexture = NULL;
14050 rsurface.uselightmaptexture = false;
14051 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);